# Merge two values

You have two values each of which is either 0 representing "unknown", or one of 1,2,3. Merge them into a single value as follows:

• If both values are nonzero and equal, output that value:
(3,3) -> 3
• If both values are nonzero but unequal, output 0 for unknown:
(1,2) -> 0
• If one value is zero and the other is not, output the nonzero value:
(2,0) -> 2, (0,1) -> 1
• If both values are zero, output zero:
(0,0) -> 0

Test cases:

There are 16 possible input pairs.

| 0 1 2 3
--+--------
0 | 0 1 2 3
1 | 1 1 0 0
2 | 2 0 2 0
3 | 3 0 0 3

(0, 0) -> 0
(0, 1) -> 1
(0, 2) -> 2
(0, 3) -> 3
(1, 0) -> 1
(1, 1) -> 1
(1, 2) -> 0
(1, 3) -> 0
(2, 0) -> 2
(2, 1) -> 0
(2, 2) -> 2
(2, 3) -> 0
(3, 0) -> 3
(3, 1) -> 0
(3, 2) -> 0
(3, 3) -> 3

• The fourth rule fits in the first rule, so I dont know why you separated them. May 24 '18 at 7:14
• Nitpick: The 4th point is redundant, you can just remove "nonzero" from the first point. EDIT: Wow, what a ninja @Fatalize is. May 24 '18 at 7:18
• Also, 3 isn't really necessary here, although it does increase the number of possible inputs. May 24 '18 at 7:26
• I considered condensing the rules, but thought it would be clearest to just list all the zero/nonzero cases and leave the optimization up to the golfers.
– xnor
May 25 '18 at 0:17
• This needs a leaderboard, the first page is starting to get answers already beaten on the second one. May 26 '18 at 1:02

# Python 3, 27 25 bytes

lambda x,y:(x|y)>>(x*y&2)

Try it online!

• I like that this breaks for inputs over 3. How did you come up with this? May 24 '18 at 3:16
• Basically lots of trial and error. May 24 '18 at 3:26
• Interesting. For a moment I thought of automating a search through limited-length expressions involving two ints and a few operators, but the space is much too big even at around 20 bytes. Some intelligence is required! May 24 '18 at 4:39

# Jelly, 4 bytes

gf|S

Try it online!

### How it works

gf|S  Main link. Left argument: x. Right argument: y.

g     Compute a, the gcd of x and y.
|   Compute b, the bitwise OR of x and y.
f    Filter; yield all common elements of [a] and [b].
S  Take the sum.

# APL (Dyalog), 5 bytes

⌈×∧=⌊

Try it online!

Useful reference

∧=⌊: Returns 1 if the lowest common multiple is equal to the minimum. This is only true if one of the values is zero, or both are equal. Alternatively I could have =*⌊

⌈×: The maximum multiplied by the above.

# Shakespeare Programming Language, 296 bytes

Z.Ford,.Ajax,.Act I:.Scene I:.[Enter Ford and Ajax]Ajax:Listen to thy heart.Ford:Listen to thy heart.Am I as fat as you?Ajax:If so,let us Scene C.Am I as fat as zero?If so,let us Scene C.Ford:Am I as fat as zero?If not,you zero.open heart.let us Scene V.Scene C:.Ajax:open heart.Scene V:.[Exeunt]

Try it online!

First participation to a code-golf challenge, so let's start with one of my favorite joke languages !

Explanation : Declaration of the two variables Ford and Ajax (shortest variable names available)

Z.Ford,.Ajax,.

First Scene : Put the two values into the variable, then test them for equality, then test Ajax against 0. If the value that we have to return is stored in the variable Ford, go to Scene C.

Act I:.
Scene I:.
[Enter Ford and Ajax]
Ajax:
Listen to thy heart.
Ford:Listen to thy heart.
Am I as fat as you?
Ajax:
If so,let us Scene C.
Am I as fat as zero?
If so,let us Scene C.

If Ford is 0, print Ajax, else set Ajax as 0 then print Ajax. Then go to the end of the program.

Ford:Am I as fat as zero?
If not,you zero.
open heart.
let us Scene V.

Scene C : Print Ford

Scene C:.
Ajax:open heart.

Scene V: End of the program.

Scene V:.
[Exeunt]
• 221 bytes
– Jo King
May 26 '18 at 9:28
• @JoKing your version is undeniably better than mine, I think it would be better if you posted it as an answer as the reasoning behind the program is quite different and I don't want to take the credit for your work May 26 '18 at 19:20

# Ruby, 21 bytes

->a,b{(a|b)*531[a*b]}

Try it online!

Because Ruby

# Short explanation:

• a|b is bitwse OR, so it gives us the right number if a==b or one of them is zero.

• Magic number 531 is 2^9+2^4+2^1+2^0, and the [] operator extracts a single bit. This means: multiply by 1 if a*b is 0, 1, 2, 4 or 9, multiply by 0 otherwise.

• This won't work for values > 3

x!y=0^((x-y)^2*x)*y+0^y*x

Try it online!

# JavaScript (Node.js), 17 bytes, port somehow from Python answer

a=>b=>a*b&2?0:a|b

Try it online!

# JavaScript (Node.js), 21 bytes

a=>b=>a-b?a*b?0:a+b:a

Try it online!

• ?0:... Could you do ||, or does precedence mess that up? May 26 '18 at 20:55
• @StanStrum ?0: mean return zero if cond is not zero, || return non-zero if cond is not zero
– l4m2
May 27 '18 at 3:24

# Pyth, 8 7 bytes

@{+0SQ3

Try it online!

@{+0SQ3   Implicit: Q=input()

SQ    Sort input
+0      Prepend 0
{        Deduplicate
@     3    Get 4th element (index 3), modular indexing

Case 1 - Both values nonzero and equal

Sorted Input   [3,3]
Prepend 0      [0,3,3]
Deduplicate    [0,3] - index 3 yields 3

Case 2 - Both values nonzero and unequal

Sorted Input   [1,2]
Prepend 0      [0,1,2]
Deduplicate    [0,1,2] - index 3 yields 0

Case 3 - Exactly one value zero

Sorted Input   [0,1]
Prepend 0      [0,0,1]
Deduplicate    [0,1] - index 3 yields 1

Case 4 - Both values zero

Sorted Input   [0,0]
Prepend 0      [0,0,0]
Deduplicate    [0] - index 3 yields 0

Alternate solution, also 7 bytes

*eSQ}s{

Try it online

*eSQ}s{QQ   Trailing Q's inferred

{Q    Deduplicate input
s      Take the sum
}   Q   Is this in the input? True treated as 1, false as 0
*           Multiplied by
eSQ        Max from input (end of sorted input)

Previous version, 8 bytes

@+0{-QZ3
• @xnor Thanks for spotting that, it should be fixed now
– Sok
May 25 '18 at 17:43
• @{+0Q3 works for 6 bytes. May 28 '18 at 14:04

# Java 8, 20 bytes

Curried lambda. Stolen from here.

a->b->(a|b)>>(a*b&2)

# Stax, 8 bytes

Ç∞∟∙◄╥*♣

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

e.g.        [2, 0]
c:s [2, 0] 2    calculate the "span" of the input array (max(a) - min(a))
+   [2, 0, 2]   append the span to the input array
o   [0, 2, 2]   sort the 3-element array
E   0 2 2       explode the 3 elements into 3 separate stack entries
a   2 2 0       rotate the third stack element to the top of stack
!   2 2 1       logical not, produces 1 iff the top value was 0
*   2 2         multiply
implicitly print top of stack

Run this one

# Brain-Flak, 32 bytes

{(({}[({})]<>)){{}<>}(<>)}{}({})

Try it online!

(first submission so please don't kick too hard)

# Python 2, 57 44 43 bytes

lambda a,b:(0 if a*b else a+b)if a-b else a

Try it online!

(compressed a bit after looking at first python answer)

• 33 bytes
– Jo King
May 26 '18 at 9:20
• Crossed out 44 is still 44 ;(
– Jo King
May 26 '18 at 9:52
• @JoKing huh wut? Your solution is great, i tried to do it with arithmetics, but failed and fell back to if/else May 26 '18 at 16:20

# C (gcc), 25 bytes

f(a,b){a=a^b&&a*b?0:a|b;}

pseudo-code:

foo(A,B)
if A XOR B and A*B are > 0
return 0
else
return A OR B

# C (gcc), 26 bytes

f(a,b){a=a*b?a-b?0:a:a+b;}

Try it online!

Expanation / Ungolfed:

int f(int a, int b) { // implicit-int (C89)
// return replaced with assignment: link
return a*b ? // if a and b are both not zero, then
a-b ? // if a != b
0 : // a != b, so return 0
a // a == b, so return a
: a+b // one of a,b is zero, so return whichever is nonzero
;
}

# MATL, 9 bytes

dGp*~GX>*

Try it online!

### Explanation:

% Implicit input as a vector with two elements implicitly. Stack: [0,2]
d          % The difference between the two elements. Stack: [2]
G         % Push input again. Stack: [2], [0,2]
p        % The product of the last element (the input). Stack: [2], [0]
*       % Multiply the two elements on the stack. Stack: [0]
~      % Negate. Stack: [1]
G     % Push input again. Stack: [1], [0,2]
X>   % Maximum value. Stack: [1], [2]
*  % Multiply the two elements on the stack. Stack: [2]
% Implicit output
• Failed outgolf: t?td~*]X> Jul 5 '18 at 13:55

s/^0?(.)\1?0?$/\1/ t c0 (must be run with -r flag) Try it online! • Welcome to PPCG :) The current consensus is that flags not be counted (I'm on my phone so can't link the relevant Meta). May 24 '18 at 22:08 • Oh cool! I'll edit later since I'm also on my phone; a free -3 bytes is a great welcome to PPCG :) May 24 '18 at 22:11 # QBasic, 34 bytes Different approach! INPUT a,b ?(a OR b)*-(a*b=0OR a=b) Observe that the nonzero values in the output grid are all the bitwise OR of the two input numbers. This is just a OR b in QBasic. We want to output this value when a*b=0 OR a=b, and 0 otherwise, which we can do by multiplying by the negative of the aforementioned conditional (negative, since truthy is -1 in QBasic). # brainfuck, 25 bytes ,>,[>]<<[[->->+<<]>[>]]>. Input is two byte values (not ascii) # Swift, 118 bytes func c(n1:Int,n2:Int){n1==n2 ? print("\(n1)") : (n1*n2 != 0 ? print("0") : (n1==0 ? print("\(n2)") : print("\(n1)")))} • Welcome to PPCG! I don't know Swift, but you can probably save a lot of bytes by making the variable names 1 character each, and removing whitespace around operators like != and the ternary. May 24 '18 at 1:30 • Hi, welcome to PPCG! As mentioned by @Οurous, you can change n1 and n2 to single chars to shorten them; remove some white-spaces and parenthesis, and remove some spaces. In addition, ==0 can be <1 and !=0 can be >0, since we know only the inputs 0,1,2,3 are possible. Never programmed in Swift before either, but I got it down to 91 bytes like this: func c(a:Int,b:Int){a==b ?print("\(a)"):a*b>0 ?print("0"):a<1 ?print("\(b)"):print("\(a)")} Try it online. May 24 '18 at 8:08 • In addition, it seems you can shorten it to 51 bytes like this: func c(a:Int,b:Int){print(a==b||a*b<1 ?max(a,b):0)} Try it online. Again welcome to PPCG, and enjoy your stay! May 24 '18 at 8:09 • In addition to @KevinCruijssen's golfs, you can turn your submission into an anonymous closure to save 87 bytes: {$0==$1||1>$0*$1 ?max($0,\$1):0} Try it online! May 24 '18 at 9:47

## Batch, 383635 30 bytes

@cmd/cset/a"(%1|%2)>>(%1*%2&2)

Port of @Dennis's Python answer, as conditionals are too expensive in Batch.

=h|∋0&⌉|∧0

Try it online!

# J, 8 7 bytes

1 byte saved by H.PWiz.

>.*=^<.

Try it online!

A J port of H.PWiz's APL solution

= are the numbers equal? (results in 1 or 0)

^ to the power of

<. the smaller number

* multiplied by

>. the larger number

• >.*=^<. for 7 bytes May 24 '18 at 8:06
• @ H.PWiz Thank you! Clever use of = and^! May 24 '18 at 8:57

# 05AB1E, 9 8 bytes

àIËIP_+*

-1 byte thanks to @MagicOctopusUrn.

Explanation:

à         # Take the maximum of the input-list
#  [0,2] → 2
IË        # Are all elements in the input-list equal?
#  [0,2] → 0
IP_     # Take the product of the input-list, and verify if it equals 0
# (_` transforms 0 into 1; everything else into 0)
#  [0,2] → 0 (product) → 1 (==0)
+    # Add them together (since only 1 is truthy in 05AB1E, this is basically an OR)
#  0+1 → 1
*         # Multiply both values on the stack
#  2*1 → 2

Generalized explanation:

IËIP_+    # If both values are equal, or one of them is a zero:
à        #  Output the maximum of the two values
# Else:
#  Output 0
• Ës0å~iZë0 was mine; nice one. Not actually sure you can beat 9 bytes by much. May 24 '18 at 21:53
• I take that back à®Ë®P_+* where _ is logically equivalent to May 24 '18 at 21:55
• _ turns 0 into 1, all other values into 0. May 24 '18 at 22:05
• @MagicOctopusUrn Thanks! When I made this answer I was looking at the docs to see if there was a == 0 command, didn't knew _ does exactly that. Should be useful for other challenges in the future as well. TIL. :) May 25 '18 at 6:45

# Javascript, 35 bytes

f=(m,n)=>(m||n)&&(m!=n)?(m>n?m:n):0

ê0ýÙ7è

Try it online!

# Javascript ES6, 252221 20 bytes

a=>b=>a?b-a?!b*a:a:b

14 13 bytes, If the arguments are provided in sorted order

a=>b=>a%b?0:b

# Python 2, 34 28 bytes

lambda i,j:(i|j,0)[0<i!=j>0]

Try it online!

-6 with thanks to @Dennis

• [0<i!=j>0] saves a few bytes. May 26 '18 at 13:15

# QBasic, 3836 35 bytes

INPUT a,b
?(a*b>0)*(b-a*(a<>b))+a+b

Partly inspired by Erik's IF ... THEN ... ELSE answer, here's a math-only solution.

### How I got here

Important note for understanding math-with-conditionals: in QBasic, the results of comparison operators are 0 and -1, not 0 and 1.

IF a*b THEN?a*-(a=b)ELSE?a+b

In other words, if a and b are both nonzero, then print a*-(a=b) (a if a=b, otherwise 0); else (at least one of a and b is zero), output a+b (the nonzero number, or 0 if they're both zero).

There's already some math with conditionals going on here. Let's take it a step farther and see if we can eliminate the IF statement entirely. We'll have to use a*b>0 for the outer condition: a*b can have multiple different truthy values, which is fine for IF but causes problems for math.

c=a*b>0
?c*a*(a=b)+(c+1)*(a+b)

This is the standard trick of IF-elimination. When c is true, c*a*(a=b) is -a*(a=b) and (c+1)*(a+b) is 0; when c is false, c*a*(a=b) is 0 and (c+1)*(a+b) is a+b. So this expression gives the same results as the IF ... THEN ... ELSE. The only problem is, it makes our program 40 bytes instead of 38. Maybe we can shorten it by rearranging the math.

c=a*b>0
?c*a*(a=b)+c*(a+b)+a+b

Still 40 bytes...

c=a*b>0
?c*(a+b+a*(a=b))+a+b

Now our program is back to 38 bytes. But since we're only using c once, we don't have to assign it to a variable anymore:

?(a*b>0)*(a+b+a*(a=b))+a+b

Now we're down to 36 bytes.

But wait there's more... That a+b+a*(a=b) expression looks a bit redundant. a*(a=b) is -a if a=b and 0 otherwise. When we add it to a, we get 0 if a=b and a otherwise. Maybe we can achieve the same thing in fewer bytes by reversing the condition.

b+a*-(a<>b)

At first, this doesn't look shorter. But we can save a byte by subtracting instead of adding a negative:

b-a*(a<>b)

And there we have our 35-byte solution.

• Nice trick over there... Jun 19 '18 at 20:01

# Clean, 4643 42 bytes

import StdEnv
?[a,b]|a<1||a==b=b=0
?o sort

Try it online!

Anonymous composition :: [Int] -> Int, sorts the pair and then matches off the first member.

Doing it as a composed lambda is the same length:

import StdEnv
(\[a,b]|a<1||a==b=b=0)o sort

# Jelly, 7 6 bytes

×¬o=a»

How?

×        Multiply the two arguments.
¬       Logical not. Gives 1 if one argument is 0, 1 otherwise.
=     Are the two arguments equal?
o      Logical or the result of = and ¬.
»   Greater of the two arguments.
a    Logical and. Gives the greater of the two arguments if they are equal
or if one of them is zero and gives 0 otherwise.

Using the method in the APL answer, we get the same byte count. One byte longer than that answer because lowest common multiple is two bytes.

6 bytes

«=æl×»

Try it online!

• I also note an alternate method below May 24 '18 at 0:12
• @H.PWiz Oh, I thought you were using the same method as the one in the link May 24 '18 at 0:17
• I give two methods ∧=⌊ and =*⌊. The second of which is prefered by Jelly May 24 '18 at 0:20
• @H.PWiz I don't speak APL, I was just using the method you described. What does =*⌊ do? May 24 '18 at 0:22
• It's pretty much the same as Jelly, except that is minimum. Or one could use × in both languages May 24 '18 at 0:25