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

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.