## Assign Y

### July 3, 2015

I’m sorry I missed Tuesday’s exercise; I’ve been very busy at work. Today’s exercise is an interview question of the kind I don’t like: it’s tricky, you either know the answer or you don’t, and it’s unlikely to be useful in any real programming situation:

You are give four integers

x(which must be either 0 or 1),y,aandb. Your first task is to assignatoyifx= 0, or assignbtoyifx= 1, without using any conditional operator, including the ternary operator. Your second task is to perform the same assignment without using any arithmetic operators.

Your task is to complete the two-part puzzle given above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

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:

xmust 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.