# 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. – Fatalize 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. – Erik the Outgolfer May 24 '18 at 7:18
• Also, 3 isn't really necessary here, although it does increase the number of possible inputs. – Erik the Outgolfer 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. – Ørjan Johansen May 26 '18 at 1:02

# TI-Basic, 10 bytes

max(Ans)not(prod(Ans)ΔList(Ans


Multiply maximum value by result of (some element equals zero OR elements are equal)

• Yay for opcodes! – phyrfox May 27 '18 at 23:25

# C (gcc), 22 bytes

f(x,y){x=x*y&2?0:x|y;}


Try it online!

• Does this produce output? – Jakob May 24 '18 at 15:40
• In gcc and without optimizations, yes. It's undefined behavior though. It works because gcc computes x*y&2?0:x|y in the eax register, which is where a proper return statement would move it. – Dennis May 24 '18 at 16:29
• Ah, right. Shouldn't the language of this submission be C (GCC) on x86 then? Or is that not the established convention? – Jakob May 24 '18 at 17:14

a#b=max a b*0^(a*b*(a-b)^2)


Try it online!

# Octave, 28 bytes

@(a,b)~(a*b*(a~=b))*max(a,b)


Try it online!

or

@(a,b)(a==b|~(a*b))*max(a,b)


Try it online!

### Explanation:

The maximum value should be outputted if a*b=0 or if a==b. The function takes a and b as inputs. It multiplies a*b, thus getting a zero if one of them is zero, and checks that a~=b, thus getting a zero if the two are equal. We negate both, so that both conditions gives us a truthy value telling us that we should output the maximum value. We then multiply this boolean (0/1) by the maximum value, and outputs it.

# 05AB1E, 7 bytes

α*P_*Z


Try it online!

Explanation

α        # absolute difference of the inputs
*       # multiplied by the inputs
P      # product of the result
_     # logically negated
*    # multiplied by the inputs
Z   # max


# JavaScript (ES6)

## 27 bytes

A rather long formula, but without any conditional statement.

a=>b=>(a|4)*(b|4)*6%61%27&3


Try it online!

## 17 bytes

Simply a port of Dennis' method.

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


Try it online!

# Japt, 12 9 bytes

Takes input as an array of integers.

×&2?0:Ur|


Try it online!

• I had the same, but with logical OR (ª) instead of bitwise. – Shaggy May 24 '18 at 22:03

# R, 35 bytes

rep(unique(sort(c(0,scan()))),4)[4]


Try it online!

Shameless port of Sok's well-explained Pyth answer.

# Befunge-93, 20 bytes

&::&*#v_&+.@
@.*!-&<


Try it online!

## Explanation

this boils down to:

if(A * B = 0) {
output (A + B)
end
} else {
output A * (A = B)
end
}


# Python 3, 30 bytes

lambda a,b:0==a*b*(a-b)and a|b


Try it online!

-5 bytes thanks to Oliver
-1 byte thanks to Jo King

# Befunge-93, 17 bytes

&::&-!_&*!\&+*.@.


Try it online!

As psuedo-code:

f(a,b):
if a-b==0:
print(b)
else:
print((!(a*b))*(a+b))


# Retina 0.8.2, 20 18 bytes

-2 bytes thanks to Martin Ender.

(.)\1|0
$1 ..|^$
0


Try it online!

# JavaScript, 24 Bytes

x=>y=>!x*y|!y*x|(x==y)*x


Allows all numbers, no conditional, doesn't require sorted input

• Welcome to PPCG! I don't think this gives the right result for x=0, y=3. – Ørjan Johansen May 28 '18 at 6:42
• Welcome to PPCG. Great first answer. But sadly this doesn't give the right answer for some values. Also to make it easier for others, you should always provide a link for testing – Muhammad Salman May 28 '18 at 7:22

# Python 2, 42 34 bytes

lambda a,b:(0in(a,b)or a==b)*(a|b)


EDIT: -8 thanks to @TIO and @JonathanAllan

• a==0 or b==0 can be expressed shorter as 0 in(a,b). TIO – ovs May 27 '18 at 17:43
• Because the max(a,b) only has any effect when either one of a or b are zero or when a and b are equal it can be replaced by a bit-wise or: (a|b). Some of your spaces are redundant too... lambda a,b:(0in(a,b)or a==b)*(a|b) is 34 bytes (although Dennis's 25 byte solution, lambda x,y:(x|y)>>(x*y&2), also works in Python 2). – Jonathan Allan May 27 '18 at 20:15

# Shakespeare Programming Language, 216 208 bytes

,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ajax:Listen tothy!Ford:Listen tothy!Am I as bad as you?If soyou zero.Is the product ofyou I worse a cat?If soyou be the sum ofyou I.If notyou zero.Open heart


Try it online!

As psuedo-code:

f(a,b):
if a==b:
b=0
if a*b<1:
b=a+b
else:
b=0
return b


# Prolog (SWI), 27 bytes

N+N+N.
N+0+N.
0+N+N.
_+_+0.


Try it online!

The most naive translation ever.

# Glee, 2422 20 bytes

Idea to append zero taken from Sok’s Pyth solution.

=>n,0& *>0\+ >1~ *n\>>

=>n,0& *>0\+ <2*n\>>             <2 instead of >1~ (not > 1)


Explanation:

a b=>n,0& *>0\+ <2*n\>>
a b=>n                      3 1     2 2     0 3     0 0     assign a b to n
,0                    3 1 0   2 2 0   0 3 3   0 0 0   catenate 0
&                   0 1 3   0 2     0 3     0       unique elements
*>0               011     01      01      0       mark all > 0 (boolean)
\+             2       1       1       0       reduce by addition
<2          0       1       1       1       result <2 ?
*n        0 0     2 2     0 3     0 0     multiply with n
\>>     0       2       3       0       largest element


Old version

=>n--[2]=0|(n\* =0)*n\>>


Explanation for a pair of numbers (a b):

                              result for a b pairs
3 1    2 2    0 3
a b=>n--[2]=0|(n\* =0)*n\>>
a b                            3 1    2 2    0 3   create vector (a b)
=>n                                             assign vector to n
--                       0 _2   0 0    0 3   calculate the first difference vector of n (monadic --)
[2]=0                  0      1      0     result vector at index 2 equal to 0 ? (boolean)
(n\*             3      4      0     n reduced by multiplication
=0)         0      0      1     equal to 0 ? (boolean)
|                 0      1      1     OR (boolean) (dyadic |)
*n       0 0    2 2    0 3   multiplied by n (dyadic *)
\>>    0      2      3     largest element (monadic \>>)


# QBasic 1.1, 38 bytes

INPUT A,B
IF A*B THEN?A*-(A=B)ELSE?A+B


-1 thanks to DLosc.

Input is two comma-separated integers.

# Attache, 32 bytes

{If[_=_2,_,If[Min!__,0,Max!__]]}


Try it online!

Takes input as two arguments, such as f[0, 1] = 1.

## 34 bytes

{If[Same!_,_@0,If[Min!_,0,Max!_]]}


Try it online! The same as above, but takes input as an array

## 39 bytes

{ToBase[47483073034,5][FromBase&4!_]-1}


Try it online!

Hardcodes the solution in a base-5 integer. More interesting IMO but longer.

• Surely base 4 suffices? – Neil May 24 '18 at 8:04

# Pyth, 11 bytes

e+Z.-+xFQQ{


Try it here

### Explanation

e+Z.-+xFQQ{
+xFQQ      Prepend the XOR of the inputs to the inputs.
.-     {Q    Remove one copy of the deduplicated (implicit) input.
+Z             Prepend 0.
e               Take the last.


### Alternative solution, 11 bytes

e+0.-F{B+xF


# Pyth, 10 bytes

-iFQ&.AQnF


Try it online!

# JavaScript (Node.js), 20 bytes

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


Try it online!

# 12-basic, 36 bytes

FUNC M(A,B)?(A or B)*(!A~!B|A==B)END


This can probably be shortened.

~ is bitwise XOR (as well as bitwise NOT when used as a unary operator) (Just like in Lua)

# Elixir, 34 bytes

Pretty simple in a functional programming language, just get the first match. No maths here!

fn a,a->a
a,0->a
0,a->a
_,_->0 end


Try it online!

# dc, 28 bytes

[pq]sqsidli=qd0rli*0!=qli++p


Try it online!

I'll keep mulling over this, it feels like it must be golfable. [pq]sq just makes a print & quit macro. sidli stores one of our values in the register i, duplicates the other value, and then recalls i. =q consumes two values on the stack, and executes macro q if they're equal (so, prints the one value left behind). d0r duplicates the value on the stack again, and then puts a 0 on the stack in between them. li*0!= loads i, multiplies the two values, and runs q to print the 0 that we left on the stack if the two values were not equal. If none of these things has happened yet, we li to load i, and we now have three values on the stack - two zeroes and our one non-zero value. ++ add the three together, and print.

/ /;$_=($'|$)>>($'*$&2)  Try it online! Steals the method from @Dennis's Python answer. # Tcl, 43 bytes proc M a\ b {expr !$a?$b:!$b?$a:$a-$b?0:$a}


Try it online!

<?=($a=$argv[1])==($b=$argv[2])?$a:($a*$b?0:$a|$b);  Try it online! Explanation: $a==$b Check for equality, display first value if equal$a*$b If multiplication equates to non-zero, display 0 (Unknown) else...$a|$b Display the non-zero value.  # C#, 4827 bytes (x,y)=>x==y?x:(x*y>0?0:x|y)  Try it online Thanks @Charlie for the TIO link & helping trim 21 chars off the code • Welcome to the site! I don't know C#, but is it possible to remove the space between > a=? Also, would you mind editing in a link to an online tester, such as Try it online! so that others can test your submission? – caird coinheringaahing May 24 '18 at 10:01 • You can use this link in your answer, which also reduces your byte-count to just 27 bytes, as a simple lambda expression is a valid answer in code golf. – Charlie May 24 '18 at 11:15 • @cairdcoinheringaahing I have now included TIO link to my answer (Thanks to @Charlie). the space (and the variable) apparently seems to be not required, I wasn't aware on the guidelines around how to use lambda expressions for code golf answers, thanks again to Charlie for pointing it out. – jjk_charles May 27 '18 at 14:35 # PHP, 42 40 bytes [,$a,$b]=$argv;echo$a*$b&&$a-$b?0:$a|$b;


Run with php -r '<code>' <a> <b> or Try it online.

breakdown

[,$a,$b]=$argv; // import input echo$a*$b // if both not 0 &&$a-$b // and unequal ?0 // then print 0 :$a|\$b  // else print the non-zero value, if there is one
;