# 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


var QUESTION_ID=165314,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• The fourth rule fits in the first rule, so I dont know why you separated them. May 24, 2018 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, 2018 at 7:18
• Also, 3 isn't really necessary here, although it does increase the number of possible inputs. May 24, 2018 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, 2018 at 0:17
• This needs a leaderboard, the first page is starting to get answers already beaten on the second one. May 26, 2018 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, 2018 at 3:16
• Basically lots of trial and error. May 24, 2018 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, 2018 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, 2018 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, 2018 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!

# 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, 2018 at 17:43
• @{+0Q3 works for 6 bytes. May 28, 2018 at 14:04

# Java 8, 20 bytes

Curried lambda. Stolen from here.

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


# 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, 2018 at 20:55
• @StanStrum ?0: mean return zero if cond is not zero, || return non-zero if cond is not zero
– l4m2
May 27, 2018 at 3:24

# 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, 2018 at 9:20
• Crossed out 44 is still 44 ;(
– Jo King
May 26, 2018 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, 2018 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


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, 2018 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, 2018 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, 2018 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, 2018 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, 2018 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, 2018 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.

# Brachylog, 10 bytes

=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, 2018 at 8:06
• @ H.PWiz Thank you! Clever use of = and^! May 24, 2018 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, 2018 at 21:53
• I take that back à®Ë®P_+* where _ is logically equivalent to >Θ May 24, 2018 at 21:55
• _ turns 0 into 1, all other values into 0. May 24, 2018 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, 2018 at 6:45

# Javascript, 35 bytes

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


# 05AB1E, 6 bytes

ê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, 2018 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, 2018 at 20:01

# Shakespeare Programming Language, 187 bytes

,.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:Listen tothy!Puck:Listen tothy!Be
you nicer zero?If notyou be I.Am I worse a cat?If notam I as big as you?If notyou zero.Open heart


Try it online!

# Vyxal, 15 bytes

?0⁼?0⁼∨??⁼∨??∴*


Try it Online!

Surprisingly no Vyxal answer yet. Return the max, multiplied by the boolean value indicating whether the values are equal or one of them is zero.

# Vyxal, 6 bytes

s0pU3i
`

Try it Online!

Thanks @lyxal for this version which ports the Pyth answer.

• Try it Online! for 9 bytes. Mar 21, 2022 at 4:48
• or port Pyth for 6 bytes Mar 21, 2022 at 4:53