Hack the elections

46

5

You're a professional hacker and your boss has just ordered you to help a candidate win an upcoming election. Your task is to alter the voting machines data to boost the candidate's results.

Voting machines store voting results as two integers : the number of votes for your candidate (v1) and the number of votes for their opponent (v2).

After weeks of research, you have found a security hole in the system and you can increase the value of v1 by an integer x, and decrease the value of v2 by the same x. But there is a constraint, you have to keep the security hash code constant:

  • security hash code : (v1 + v2*2) modulo 7

Also, the value for x must be minimal so your changes can go unnoticed.

Your program should accept as input v1 and v2 ; it should output the optimal value for x so v1>v2.

There are some cases for which you cannot hack the results; you don't have to handle them (this might lead to problems with your boss, but that's another story).

Test cases

100,123 --> 14
47,23 --> 0
40,80 --> 21
62,62 --> 7
1134,2145 --> 511

Arnaud

Posted 2017-01-11T03:45:01.930

Reputation: 8 231

4

Comments are not for extended discussion; this conversation has been moved to chat.

– Dennis – 2017-01-11T17:00:56.977

11Also, to the close voters: This is perfectly on-topic. If you don't like it, you can downvote it. – Rɪᴋᴇʀ – 2017-01-11T17:51:37.877

10What a secure hash function! – Cruncher – 2017-01-11T21:25:23.150

Can you assume the inputs are followed by .0 (Like 100.0 123.0)? – Esolanging Fruit – 2017-01-18T17:55:48.863

Answers

21

Python 2, 30 bytes

lambda u,t:max(0,(t-u)/14*7+7)

u is our votes, t is their votes.

orlp

Posted 2017-01-11T03:45:01.930

Reputation: 37 067

3Couldn't (t-u)/14*7 be just (t-u)/2? – Conor O'Brien – 2017-01-11T04:32:44.493

2Oh, wait, nevermind, Py2 does integer division – Conor O'Brien – 2017-01-11T04:37:51.807

@ConorO'Brien Nope. Consider t-u == 16. Then 16/14*7 = 7, but 16/2 = 8. Also, you aren't running as Python 2. – orlp – 2017-01-11T04:37:55.223

@orlp I don't know which one to ask, so I'll ask both of you, can you please explain to me how you thought of this? y<x?0:(y-x)/2-(y-x)/2%7+7;, I thought that I should take the difference split it in half, and then find the nearest multiple of 7. How did you arrive to this? – Wade Tyler – 2017-01-11T07:53:48.577

1the same solution is above – username.ak – 2017-01-13T11:24:31.080

20

Python 2, 30 bytes

lambda a,b:max((b-a)/14*7+7,0)

xnor

Posted 2017-01-11T03:45:01.930

Reputation: 115 687

After fixing the bug we basically have the same answer =/ – orlp – 2017-01-11T04:02:11.317

3@orlp Yeah, I think this is just the way to write the expression. Unless a recursive solution is shorter, which I doubt. – xnor – 2017-01-11T04:06:24.080

1@xnor I don't know which one to ask, so I'll ask both of you, can you please explain to me how you thought of this? y<x?0:(y-x)/2-(y-x)/2%7+7;, I thought that I should take the difference split it in half, and then find the nearest multiple of 7. How did you arrive to this? – Wade Tyler – 2017-01-11T07:53:39.007

2@WadeTyler We're looking the the smallest multiple of 7 that is strictly greater than half the difference. To find that from (b-a)/2, we do /7*7 to round downs to the nearest multiple of 7, and then +7 to go up to the next up. That is, unless the we would get a negative number, in which case we're winning anyway can just do 0. Taking the max with 0 achieves this. Some of it was also just tweaking the expression and running it on the test cases to see what works. – xnor – 2017-01-11T08:08:47.997

@xnor What I don't understand is why /7*7? – Wade Tyler – 2017-01-11T08:14:23.947

@xnor I pretty much thought of the same thing except I don't know how to transform my formula to look like yours. – Wade Tyler – 2017-01-11T08:15:07.027

2@WadeTyler The /7*7 is a kind of expression that shows up often enough in golfing that I think of it as an idiom. The idea is the n/7 takes the floor of n/7, i.e. finds how many whole multiples of 7 fit within n. Then, multiplying by 7 brings it to that number multiple of 7. – xnor – 2017-01-11T08:16:49.847

@xnor I got it. Thanks a lot. I don't like using formulas without knowing what they mean, so I usually spend as much time as needed to fully understand them. – Wade Tyler – 2017-01-11T08:22:09.663

In ruby: instead of (b-a)/147+7 I am using (a-b)/14-7, which should work in python too and save a byte. – G B – 2017-01-12T12:18:31.557

@GB That doesn't work if the vote is tied (like 62,62). – mathmandan – 2017-01-12T18:06:58.680

Oops, you are right, I didn't check that test case... – G B – 2017-01-12T22:12:03.740

just out of curiosity, how does this handle inputs where a is greater than b but by less than 7 (ie a=100 b=98)? if i understood the tests correctly, the returned value should be 0 – Jack Ammo – 2017-01-14T04:24:11.520

1@JackAmmo That example gives -2/7*7, and since Python floor-division rounds towards negative infinity, 2/7 is -1, so 7*-7+1 is 0. So, both sides give 0, which works out fine. – xnor – 2017-01-14T04:35:01.200

13

Mathematica, 22 bytes

0//.x_/;2x<=#2-#:>x+7&

Pure function with arguments # and #2. Hits maximum recursion depth if the discrepancy is more than 7*2^16 = 458752.

Explanation

0                       Starting with 0,
 //.                    repeatedly apply the following rule until there is no change:
    x_                    if you see an expression x
      /;                    such that
        2x<=#2-#            2x <= #2-# (equivalently, #+x <= #2-x)
                :>        then replace it with
                  x+7       x+7 (hash is preserved only by multiples of 7)
                     &  End the function definition

ngenisis

Posted 2017-01-11T03:45:01.930

Reputation: 4 600

4Can you add an explanation for all this? – Pavel – 2017-01-11T04:26:38.180

@Pavel Maybe your comment has continued getting upvotes because my explanation was unclear? – ngenisis – 2017-01-11T20:52:56.437

I thought it was fine, but then again I also know Mathematica. – Pavel – 2017-01-11T21:46:46.470

@Pavel Well it's better now :) – ngenisis – 2017-01-11T21:48:41.377

7

Jelly, 9 bytes

IH:7‘×7»0

Try it online!

How it works

IH:7‘×7»0  Main link. Argument: [v1, v2]

I          Increments; compute [v2 - v1].
 H         Halve the result.
  :7       Perform integer division by 7.
    ‘      Increment the quotient.
     ×7    Multiply the result by 7.
       »0  Take the maximum of the product and 0.

Dennis

Posted 2017-01-11T03:45:01.930

Reputation: 196 637

6

Actually, 13 bytes

7;;τ((-\*+0kM

Try it online!

Uses the same max((b-a)/14*7+7,0) formula that xnor and orlp use.

Explanation:

7;;τ((-\*+0kM
7;;            3 copies of 7
   τ           double one of them
    ((-        bring the inputs back to the top, take their difference
       \*+     integer divide by 14, multiply by 7, add 7
          0kM  maximum of that and 0

Mego

Posted 2017-01-11T03:45:01.930

Reputation: 32 998

5Actually, this is a great answer – TrojanByAccident – 2017-01-11T06:48:56.553

I feel like the name of this language was intentional to make the submission titles sound like punchlines: "Guys, Actually, this is 13 bytes! Come on!" – Patrick Roberts – 2017-01-12T10:31:52.417

@PatrickRoberts Actually, that's correct. – Mego – 2017-01-12T10:39:00.017

6

Groovy, 41 37 bytes

{x,y->[Math.floor((y-x)/14)*7+7,0].max()}

This is an unnamed closure. Thanks to xnor and orlp for the formula and James holderness for pointing out a bug.

The previous solution used intdiv() for integer division but it behaves differently from // used in python.

Try it here!

Gurupad Mamadapur

Posted 2017-01-11T03:45:01.930

Reputation: 1 791

5

Haskell, 30 24 bytes

a#b=max 0$div(b-a)14*7+7

An infix operator taking the number of votes of your preferred candidate first. Uses the same logic as the other answers of rounding with /14*7+7.

Renzeee

Posted 2017-01-11T03:45:01.930

Reputation: 599

2Finding the first value that meets a condition is a good use for until: a#b=until(\c->a+c>b-c)(+7)0, or better a%b=until(>(b-a)/2)(+7)0. Though an arithmetic formula is still likely shorter. – xnor – 2017-01-11T08:22:20.907

1Note that apart from xnor's shorter alternatives head[...] can almost always be shortened to [...]!!0 – Laikoni – 2017-01-11T12:25:18.633

@xnor: your until solution returns a Fractional a, I'm not sure if that is accepted. With div it is though shorter, so thanks! Eventually used the mathematical approach - and indeed, it was another two bytes shorter than until. @Laikoni: nice golfing, didn't know about that one, will remember it. – Renzeee – 2017-01-12T12:03:59.377

4

J, 15 bytes

0>.7+7*14<.@%~-

Kinda interesting, I was working on a problem and I thought I had a solution but as it turns out I was wrong. Oh well. Try it online! Here's the result:

   f =: 0>.7+7*14<.@%~-
   tests =: 123 100 ; 23 47 ; 80 40 ; 62 62 ; 2145 1134
   (,. f/ each) tests
┌─────────┬───┐
│123 100  │14 │
├─────────┼───┤
│23 47    │0  │
├─────────┼───┤
│80 40    │21 │
├─────────┼───┤
│62 62    │7  │
├─────────┼───┤
│2145 1134│511│
└─────────┴───┘

Conor O'Brien

Posted 2017-01-11T03:45:01.930

Reputation: 36 228

In the future, please use TIO.run/nexus – Pavel – 2017-01-11T05:38:59.157

@Pavel No, tio.run is v2, nexus is there only for v1 compatibility – ASCII-only – 2017-01-11T11:10:20.623

@ASCII-only https://tio.run has a disclaimer at the bottom that all generated permalinks might break in the future. I think I should make that more prominent. Except for testing purposes, nobody should be using v2 at his moment.

– Dennis – 2017-01-11T16:26:20.490

@Dennis Oh, I didn't know! Will edit asap. – Conor O'Brien – 2017-01-11T16:35:59.473

4

CJam, 13 12 15 bytes

  • Saved a byte thanks to Martin Ender.
  • Added 3 bytes thanks to Martin Ender.
  • Changed ] to [ thanks to ETHproductions.

q~\-Ed/m[)7*0e>

Blatantly stole orlp and xnor's methods.

Input is the two numbers separated by a space: 100 123

Explanation:

q~\-Ed/m])7*0e>
q~\-            e# Input two numbers, swap and subtract them.
    E           e# Push 0xE (15)
     d/m]       e# Float divide and take the floor.
         )7*    e# Increment and multiply by 7.
            0e> e# Max of this and 0.

Esolanging Fruit

Posted 2017-01-11T03:45:01.930

Reputation: 13 542

D is only 13. And you can save a byte by incrementing the value before multiplication instead of adding 7 afterwards. – Martin Ender – 2017-01-11T12:26:53.900

@JamesHolderness The issue is that Python's integer division works rounds towards -inf whereas CJam's rounds towards zero. – Martin Ender – 2017-01-11T14:04:34.000

I may be misunderstanding, but I thought m] is ceil; m[ is floor. – ETHproductions – 2017-01-11T19:03:47.210

@ETHproductions You're right, edited. – Esolanging Fruit – 2017-01-12T04:29:02.513

4

Excel VBA, 24 20 Bytes

Immediates window function that takes input from cells A1 and B1 and outputs to the VBE immediates window.

?Int([A1-B1]/14)*7+7

Subroutine Version, 43 Bytes

takes input b, c as variant\integer and prints to the VBE immediates window

Sub a(b,c):Debug.?Int((c-b)/14)*7+7:End Sub

Taylor Scott

Posted 2017-01-11T03:45:01.930

Reputation: 6 709

3

Julia 0.5, 26 bytes

v\w=max(fld(w-v,14)*7+7,0)

Try it online!

Dennis

Posted 2017-01-11T03:45:01.930

Reputation: 196 637

3

Japt, 14 bytes

V-U /2+7 f7 w0

Run it here!

Thank you ETHproductions for shaving off 3 bytes!

Oliver

Posted 2017-01-11T03:45:01.930

Reputation: 7 160

1Very nice. f accepts an argument and floors to a multiple of that number, so I think you can so V-U /2+7 f7 w0 to save three bytes. – ETHproductions – 2017-01-11T18:59:33.970

3

PHP, 41 39 bytes

    <?=7*max(0,1+($argv[2]-$argv[1])/14|0);

takes input from command line arguments; run with -r.

7 5 extra bytes just to handle $a>$b :-/

Titus

Posted 2017-01-11T03:45:01.930

Reputation: 13 814

3

05AB1E, 9 bytes

-14÷>7*0M

Try it online!

Explanation

-          # push difference of inputs
 14÷       # integer divide by 14
    >      # increment
     7*    # times 7
       0   # push 0
        M  # take max

Or a corresponding function with same byte-count operating on a number-pair

Î¥14÷>7*M

Try it online!

Emigna

Posted 2017-01-11T03:45:01.930

Reputation: 50 798

2

Dyalog APL, 14 bytes

Takes v1 as right argument and v2 as left argument.

0⌈7×1+(⌊14÷⍨-)

0 ⌈ the maximum of zero and

7 × seven times

1 + (...) one plus...

 the floor of

14 ÷⍨ a fourteenth of

- the difference (between the arguments)

TryAPL online!

Adám

Posted 2017-01-11T03:45:01.930

Reputation: 37 779

2

Befunge, 19 bytes

777+:&&\-+\/*:0`*.@

Try it online!

This relies on a slightly different formula to that used by orlp and xnor, since the Befunge reference interpreter has different rounding rules to Python. Befunge also doesn't have the luxury of a max operation.

The basic calculation looks like this:

x = (v2 - v1 + 14)/14*7
x = x * (x > 0)

Examining the code in more detail:

7                     Push 7                                      [7]
 77+:                 Push 14 twice.                              [7,14,14]
     &&               Read v1 and v2 from stdin.                  [7,14,14,v1,v2]
       \-             Swap the values and subtract.               [7,14,14,v2-v1]
         +            Add the 14 that was pushed earlier.         [7,14,14+v2-v1]
          \/          Swap the second 14 to the top and divide.   [7,(14+v2-v1)/14]
            *         Multiply by the 7 that was pushed earlier.  [7*(14+v2-v1)/14 => x]
             :        Make a copy of the result                   [x,x]
              0`      Test if it's greater than 0.                [x,x>0]
                *     Multiply this with the original result.     [x*(x>0)]
                 .@   Output and exit.

James Holderness

Posted 2017-01-11T03:45:01.930

Reputation: 8 298

2

Go, 36 bytes

func(a,b int)int{return(b-a)/14*7+7}

Try it online!

powelles

Posted 2017-01-11T03:45:01.930

Reputation: 1 277

2

JavaScript (ES6), 31 bytes

(a,b,c=(b-a)/14|0)=>c>0?c*7+7:0

f=(a,b,c=(b-a)/14|0)=>c>0?c*7+7:0
document.write(f(1134,2145))

darrylyeo

Posted 2017-01-11T03:45:01.930

Reputation: 6 214

2

Java 8, 31 bytes

(a,b)->b<a?0:(a=(b-a)/2)+7-a%7;

This is a lambda expression assignable to IntBinaryOperator.

a is your candidate's votes, b is your opponent's.

java rounds down for division with positive integers, so +7-a%7 is used to bump up the value to the next multiple of 7.

Jack Ammo

Posted 2017-01-11T03:45:01.930

Reputation: 430

a->b->(b=(b-a)/14*7+7)>0?b:0 is 3 bytes shorter, but I kinda like your approach more, so +1 from me. Almost every answer given already uses max((b-a)/14*7+7,0).. – Kevin Cruijssen – 2017-10-11T11:26:19.863

i prefer using lambdas that return the result directly. and yeahb everyone did the formula a bit shorter but this was how i reasoned about the answer before checking everyone elses – Jack Ammo – 2017-10-17T13:27:08.797

a->b->(b=(b-a)/14*7+7)>0?b:0 does return the result directly as well: Try it here. Or do you mean you prefer single-method lambdas above currying lambdas; (a,b)-> preference over a->b->, even though it's longer? – Kevin Cruijssen – 2017-10-17T13:47:28.690

single method over currying, but thats just a personal preference – Jack Ammo – 2017-10-17T14:15:45.613

1

Ruby, 26 27 bytes

->a,b{[(b-a)/14*7+7,0].max}

Basically the same as xnor's and orlp's Python solution, with a twist (no need to add 7, because of negative modulo, saves 1 byte in ruby, don't know about python)

No twist, the twist was just a bad case of cognitive dissonance. Forget it. Really. :-)

G B

Posted 2017-01-11T03:45:01.930

Reputation: 11 099

1

Noodel, 16 bytes

⁻÷14ɲL×7⁺7ḋɲl⁺÷2

Pulled equation from xor and orlp answers, but since Noodel does not have a max capability had to work around that.

Try it:)

How it works

⁻÷14ɲL×7⁺7       # The equation...
⁻                # v2 - v1
 ÷14             # Pops off the difference, then pushes on the (v2 - v1)/14
    ɲL           # Applies lowercase which for numbers is the floor function.
      ×7         # Multiplies that by seven.
        ⁺7       # Then increments it by seven.

          ḋɲl⁺÷2 # To relate with the other answers, this takes the max between the value and zero.
          ḋ      # Duplicates what is on the top of the stack (which is the value just calculated).
           ɲl    # Pops off the number and pushes on the magnitude (abs value).
             ⁺   # Add the abs to itself producing zero if the number came out negative (which means we are already winning).
              ÷2 # Divides the result by two, which will either be zero or the correct offset.

tkellehe

Posted 2017-01-11T03:45:01.930

Reputation: 605

1

Scala, 31 bytes

(a,b)=>Math.max((b-a)/14*7+7,0)

The ternary version is 2 bytes longer

jaxad0127

Posted 2017-01-11T03:45:01.930

Reputation: 281

1

Pyth, 16 bytes

MtS+0[+7*7/-HG14

Try it here!

Gurupad Mamadapur

Posted 2017-01-11T03:45:01.930

Reputation: 1 791