47
\$\begingroup\$

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

Leaderboards

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>

\$\endgroup\$
8
  • 10
    \$\begingroup\$ The fourth rule fits in the first rule, so I dont know why you separated them. \$\endgroup\$
    – Fatalize
    May 24, 2018 at 7:14
  • 1
    \$\begingroup\$ Nitpick: The 4th point is redundant, you can just remove "nonzero" from the first point. EDIT: Wow, what a ninja @Fatalize is. \$\endgroup\$ May 24, 2018 at 7:18
  • \$\begingroup\$ Also, 3 isn't really necessary here, although it does increase the number of possible inputs. \$\endgroup\$ May 24, 2018 at 7:26
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    May 25, 2018 at 0:17
  • 2
    \$\begingroup\$ This needs a leaderboard, the first page is starting to get answers already beaten on the second one. \$\endgroup\$ May 26, 2018 at 1:02

64 Answers 64

1
\$\begingroup\$

Clean, 46 43 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
\$\endgroup\$
1
\$\begingroup\$

Jelly, 7 6 bytes

׬o=a»

Try it online! or Try all combinations!

How?

׬o=a»   Dyadic link
×        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!

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

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)

\$\endgroup\$
1
  • \$\begingroup\$ Yay for opcodes! \$\endgroup\$
    – phyrfox
    May 27, 2018 at 23:25
1
\$\begingroup\$

C (gcc), 22 bytes

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

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Does this produce output? \$\endgroup\$
    – Jakob
    May 24, 2018 at 15:40
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    May 24, 2018 at 16:29
  • \$\begingroup\$ Ah, right. Shouldn't the language of this submission be C (GCC) on x86 then? Or is that not the established convention? \$\endgroup\$
    – Jakob
    May 24, 2018 at 17:14
1
\$\begingroup\$

Haskell, 27 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Japt, 12 9 bytes

Takes input as an array of integers.

×&2?0:Ur|

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I had the same, but with logical OR (ª) instead of bitwise. \$\endgroup\$
    – Shaggy
    May 24, 2018 at 22:03
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

R, 35 bytes

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

Try it online!

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

\$\endgroup\$
1
\$\begingroup\$

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
}
\$\endgroup\$
0
1
\$\begingroup\$

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

\$\endgroup\$
0
1
\$\begingroup\$

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))
\$\endgroup\$
1
\$\begingroup\$

Retina 0.8.2, 20 18 bytes

-2 bytes thanks to Martin Ender.

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

Try it online!

\$\endgroup\$
2
1
\$\begingroup\$

JavaScript, 24 Bytes

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

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

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! I don't think this gives the right result for x=0, y=3. \$\endgroup\$ May 28, 2018 at 6:42
  • \$\begingroup\$ 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 \$\endgroup\$ May 28, 2018 at 7:22
1
\$\begingroup\$

Python 2, 42 34 bytes

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

EDIT: -8 thanks to @TIO and @JonathanAllan

\$\endgroup\$
2
  • 3
    \$\begingroup\$ a==0 or b==0 can be expressed shorter as 0 in(a,b). TIO \$\endgroup\$
    – ovs
    May 27, 2018 at 17:43
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ May 27, 2018 at 20:15
1
\$\begingroup\$

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
\$\endgroup\$
0
1
\$\begingroup\$

Prolog (SWI), 27 bytes

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

Try it online!

The most naive translation ever.

\$\endgroup\$
1
\$\begingroup\$

Glee, 24 22 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 \>>)
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
0
\$\begingroup\$

Attache, 32 bytes

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

Try it online!

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

Other solutions

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.

\$\endgroup\$
1
  • \$\begingroup\$ Surely base 4 suffices? \$\endgroup\$
    – Neil
    May 24, 2018 at 8:04
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Pyth, 10 bytes

-iFQ&.AQnF

Try it online!

\$\endgroup\$
0
\$\begingroup\$

JavaScript (Node.js), 20 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please link to implementation in the answer. \$\endgroup\$
    – snail_
    May 25, 2018 at 17:38
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Perl 5 -p, 25 bytes

/ /;$_=($'|$`)>>($'*$`&2)

Try it online!

Steals the method from @Dennis's Python answer.

\$\endgroup\$
0
\$\begingroup\$

Tcl, 43 bytes

proc M a\ b {expr !$a?$b:!$b?$a:$a-$b?0:$a}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

PHP - 52 bytes

<?=($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.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.