## 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, a and b. Your first task is to assign a to y if x = 0, or assign b to y if x = 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.

Pages: 1 2

### 6 Responses to “Assign Y”

1. Lucas A. Brown said

In Python:

```y = (1-x) * a + x * b
y = [a,b][x]
```

In C:

```uint64_t a=/* blah */, b=/* blah */, x=/* 0 or 1 */, y;
x = (x <<  1) | x; x = (x <<  2) | x; x = (x <<  4) | x;
x = (x <<  8) | x; x = (x << 16) | x; x = (x << 32) | x;
y = (b & x) | (a & (~x));
```

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.

2. Gil Martinez said

In Racket:

```; arithmetic solution
(let ((a 2) (b 3) (x 1))
(let ((y (+ (* a (modulo x 2))
(* b (modulo (add1 x) 2)))))
y))

; non-arithmetic solution
(let ((a 2) (b 3) (x 1))
(let ((y (or (and (= 0 x)
a)
b)))
y))
```

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.

3. captain falcom said

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
“`

4. Mike said

Is it okay to answer that the problem is under specified? What if x isn’t 0 or 1? ;-)

```# equation of a line with slope (b-a)/(1-0) and y-intercept of a
# this works if x isn't an integer, and assigns some value even if x isn't 0 or 1.
y = (b - a)*x + a

# standard short circuit logical expression - no arithmetic operators
y = x and b or a

# Don't think I've seen this answer before
try:
y = b // x
except ZeroDivisionError:
y = a

```
5. programmingpraxis said

@MIke: x must be either 0 or 1. I’ve changed the problem statement to make that explicit.

6. Brett Warrem said

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.