Assign Y
July 3, 2015
The first solution uses arithmetic:
(define (solve1 a b x)
(+ (* (- 1 x) a) (* x b)))
> (solve1 13 17 0)
13
> (solve1 13 17 1)
17
If x is 0, then the second clause is 0 and the sum is a; if x is 1, then the first clause is 0 and the sum is b. The second solution uses an array:
(define (solve2 a b x)
(vector-ref (vector a b) x))
> (solve2 13 17 0)
13
> (solve2 13 17 1)
17
The two numbers a and b are stored in a array that is indexed by variable x. You can run the program at http://ideone.com/FqvamB.
In Python:
In C:
This is basically a translation of the first Python line for 64-bit data. If you’re feeling pedantic, you might declare the bit-twiddling to be both arithmetic and conditional, but it’s branch-free and technically avoids the arithmetic operators.
In Racket:
The arithmetic solution uses modular addition on x to determine the coefficients of a and b. The resulting terms are added to produce b.
The non-arithmetic solution uses logical operators.
I can’t decide if this is cheating or not. Both a and b get assigned to something, which might not be the intended outcome.
“`
vars = [nil, nil]
vars[x] = y
a, b = vars
“`
Is it okay to answer that the problem is under specified? What if x isn’t 0 or 1? ;-)
@MIke: x must be either 0 or 1. I’ve changed the problem statement to make that explicit.
I derived a formula ((a**(1-x)/b**x)**(1-2*x)) that assigns a or b to y depending on x:
def assign_y(x, a, b):
y = int((a**(1-x)/b**x)**(1-2*x))
return y
if __name__ == “__main__”:
print(assign_y(0, 3, 2))
print(assign_y(1, 3, 2))
Results:
3
2
As for the second part of the question; not a franking clue.