70
\$\begingroup\$

I love math. But I can't find a single calculator that can multiply correctly. They seem to get everything right except 6*9 (It's the question to life, the universe, and everything! How could they get that wrong?!). So I want you all to write a function for me that can multiply 2 numbers correctly (and 6*9 equals 42 instead of 54. 9*6 equals 54 still).

Oh, and I'm going to have to build the source in Minecraft so... fewest bytes win!

Recap

  • Take 2 numbers as input (type doesn't matter, but only 2 items will be passed, and order must be consistent. So streams, and arrays are ok as long as they preserve the order they where passed in. I.e., a map won't work because it doesn't preserve the order)
  • Output multiple of both numbers except if they are 6 and 9, then output 42 (order matters!)
    • PS. I never was really good with counting, so I think only integers from 0 to 99 are real numbers (type used doesn't matter)
  • Fewest bytes per language wins!

Leaderboard:

var QUESTION_ID=124242,OVERRIDE_USER=61474;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:+r.match(SCORE_REG)[0],language:r.match(LANG_REG)[0].replace(/<\/?[^>]*>/g,"").trim(),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=/\d+((?=$)|(?= Bytes))/i,OVERRIDE_REG=/^Override\s*header:\s*/i;LANG_REG=/^[^,(\n\r]+/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/Sites/codegolf/all.css?v=617d0685f6f3"> <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\$
12
  • 83
    \$\begingroup\$ Coincidentally the question id has 42 twice in it. \$\endgroup\$ Commented Jun 3, 2017 at 6:00
  • 2
    \$\begingroup\$ if only integers up to 99 are real numbers, then e.g. 9 * 11 is a valid prompt but 10 * 10 is not, right? \$\endgroup\$ Commented Jun 3, 2017 at 8:23
  • 18
    \$\begingroup\$ @EriktheOutgolfer …and the 12 stands for what to subtract if input is 6 and 9. \$\endgroup\$
    – Adám
    Commented Jun 3, 2017 at 23:43
  • 3
    \$\begingroup\$ @Adám Just the absolutely perfect question id for this question. \$\endgroup\$ Commented Jun 4, 2017 at 7:16
  • 15
    \$\begingroup\$ @EriktheOutgolfer Even if you read the ID backwards. \$\endgroup\$
    – T. Sar
    Commented Jun 5, 2017 at 12:57

89 Answers 89

68
+100
\$\begingroup\$

Mathematica, 15 bytes

Byte count assumes Windows ANSI encoding (CP-1252).

6±9=42
±n__:=1n

Defines a binary operator ± which solves the problem. We simply define 6±9=42 as a special case which takes precedence and then add a fallback definition which makes ± equal to multiplication. The latter uses a fairly interesting golfing trick. The reason this works is actually quite elaborate and we need to look into sequences. A sequence is similar to what's known as a splat in other languages. It's basically a "list" without any wrapper around it. E.g. f[1, Sequence[2, 3, 4], 5] is really just f[1, 2, 3, 4, 5]. The other important concept is that all operators are just syntactic sugar. In particular, ± can be used as a unary or binary operator and represents the head PlusMinus. So ±x is PlusMinus[x] and a±b is PlusMinus[a,b].

Now we have the definition ±n__. This is shorthand for defining PlusMinus[n__]. But n__ represents an arbitrary sequence of arguments. So this actually adds a definition for binary (and n-ary) usagess of PlusMinus as well. The value of this definition is 1n. How does this multiply the arguments? Well, 1n uses Mathematica's implicit multiplication by juxtaposition so it's equivalent to 1*n. But * is also just shorthand for Times[1,n]. Now, n is sequence of arguments. So if we invoke a±b then this will actually become Times[1,a,b]. And that's just a*b.

I think it's quite neat how this syntax abuse lets us define a binary operator using unary syntax. We could now even do PlusMinus[2,3,4] to compute 24 (which can also be written as ±##&[2,3,4] or 2±Sequence[3,4] but it's just getting crazy at that point).

\$\endgroup\$
9
  • 5
    \$\begingroup\$ @Tezra well, * is a built-in operator, so you'd have to Unprotect it to add further definitions, but Unprotect[Times];6*9=42 should work (can't test right now though). \$\endgroup\$ Commented Jun 3, 2017 at 5:24
  • 1
    \$\begingroup\$ Doing this to the * operator is just so evil.... I love it! >:3 \$\endgroup\$
    – Tezra
    Commented Jun 3, 2017 at 15:51
  • 1
    \$\begingroup\$ How can I upvote when there are exactly 42 others?!? Here's my "future +1" to be awarded after someone else breaks it! :-) \$\endgroup\$
    – The Vee
    Commented Jun 5, 2017 at 15:11
  • 1
    \$\begingroup\$ @MartinEnder Aww; But it's the shortest Mathematica one, and my favorite so far. :3 \$\endgroup\$
    – Tezra
    Commented Jun 5, 2017 at 15:17
  • 1
    \$\begingroup\$ The trick with ±n__ getting parsed as PlusMinus[n__] and accepting infix notation further on is my favourite Mathematica hack of all time. I don't have much but I think there'll be enough for a little bounty! \$\endgroup\$
    – The Vee
    Commented Jun 5, 2017 at 16:14
60
\$\begingroup\$

Haskell, 14 bytes

6&9=42
a&b=a*b

Try it online!

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

C, 32 31 29 28 bytes

-2 thanks to Digital Trauma
-1 thanks to musicman523

#define f(a,b)a^6|b^9?a*b:42

Pretty simple. Declares a macro function f that takes two arguments, a and b.
If a is 6 and b is 9, return 42. Otherwise return a x b.

Try it online!

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Use ^ instead of == and adjust the logic a bit: #define f(a,b)a^6||b^9?a*b:42 - saves 2 bytes. \$\endgroup\$ Commented Jun 2, 2017 at 21:51
  • 2
    \$\begingroup\$ I think you can use | instead of || to save another byte, since it still has lower precedence than ^ \$\endgroup\$ Commented Jun 2, 2017 at 22:07
  • 1
    \$\begingroup\$ You should update your shortC version to take these changes as well \$\endgroup\$ Commented Jun 2, 2017 at 22:21
19
\$\begingroup\$

JavaScript (ES6), 20 bytes

x=>y=>x-6|y-9?x*y:42

Explanation:

Iff x==6 and y==9, x-6|y-9 will be 0 (falsy), and 42 will be the result.

Snippet:

f=

x=>y=>x-6|y-9?x*y:42

console.log(f(6)(9));
console.log(f(9)(6));

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Very nicely done; wish I'd thought of it. +1 \$\endgroup\$
    – Shaggy
    Commented Jun 2, 2017 at 21:55
14
\$\begingroup\$

Python 2, 30 29 bytes

Thanks to Jonathan Allan for saving a byte!

lambda x,y:x*[y,7][6==x==y-3]

Try it online!

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Save a byte using the fact that 6*7 is 42: lambda x,y:x*[y,7][6==x==y-3] \$\endgroup\$ Commented Jun 2, 2017 at 22:18
  • \$\begingroup\$ @JonathanAllan Ohh, that's neat! Thanks! :) \$\endgroup\$
    – Adnan
    Commented Jun 3, 2017 at 8:13
  • \$\begingroup\$ This solution also works in Python 3 \$\endgroup\$
    – AMK
    Commented Aug 22, 2017 at 20:18
  • \$\begingroup\$ Exactly what I got! Can't seem to find any way to golf it further. \$\endgroup\$
    – FlipTack
    Commented Oct 24, 2017 at 11:17
11
\$\begingroup\$

05AB1E, 15 11 9 bytes

-4 bytes thanks to @Emigna

-2 bytes thanks to @Adnan

P¹69SQi42

Try it online!

How it works

P          # multiply input
 ¹         # push first number
  69       # the number 69
    S      # split per character
     Q     # equality for both inputs
       i42 # if so, print 42
           # otherwise print product
\$\endgroup\$
6
  • \$\begingroup\$ You could save 4 bytes with ‚D96SQi42ëP \$\endgroup\$
    – Emigna
    Commented Jun 2, 2017 at 21:23
  • \$\begingroup\$ @Emigna huh... Why the , at the beginning? \$\endgroup\$
    – Neil A.
    Commented Jun 2, 2017 at 21:26
  • \$\begingroup\$ Pairing the 2 inputs to compare only once as a list. \$\endgroup\$
    – Emigna
    Commented Jun 2, 2017 at 21:45
  • \$\begingroup\$ I suppose 6Qs9Q* would have worked as well for the same byte count. \$\endgroup\$
    – Emigna
    Commented Jun 2, 2017 at 21:46
  • \$\begingroup\$ Changing the input format saves 2 bytes: P¹69SQi42 \$\endgroup\$
    – Adnan
    Commented Jun 3, 2017 at 8:33
11
\$\begingroup\$

Java (OpenJDK 8), 24 22 bytes

-2 bytes thanks to @OlivierGrégoire

a->b->a==6&b==9?42:a*b

Try it online!

\$\endgroup\$
13
  • 3
    \$\begingroup\$ Welcome to PPCG! I don't know much about Java, but could you remove the System.out.println() call and just let the function return the result? \$\endgroup\$ Commented Jun 2, 2017 at 23:04
  • 2
    \$\begingroup\$ @LưuVĩnhPhúc not in Java, because I'd have to write (a^6|b^9)==0 since there is no implicit "different than 0" comparison. The resulting code snippet would be 27 bytes long. Anyways, thanks for the suggestion, and please tell me if I got your tip wrong. \$\endgroup\$ Commented Jun 4, 2017 at 2:59
  • 1
    \$\begingroup\$ @Riker nope, it does not work like that in java. E.g. the snippet int a = 5; if (a) do_some_stuff(); else do_other_stuff(); gives a Type mismatch: cannot convert from int to boolean compilation error. They must be made explicitly with boolean values; refer to SO and ORACLE. \$\endgroup\$ Commented Jun 4, 2017 at 4:10
  • 3
    \$\begingroup\$ You can use currying to spare one byte, and you can get rid of the semicolon as it's not part of the lambda to spare another byte: a->b->a==6&b==9?42:a*b. \$\endgroup\$ Commented Jun 4, 2017 at 16:14
  • 1
    \$\begingroup\$ Just a note why the 0 is not false. Java is type safe so 0 is an integer not a boolean and unsafe typecasting is not allowed so you can't use falsy values \$\endgroup\$ Commented Jun 6, 2017 at 14:52
6
\$\begingroup\$

Ruby, 24 bytes

->a,b{a==6&&b==9?42:a*b}
\$\endgroup\$
4
  • \$\begingroup\$ a^6|b^9<1 might work as boolean. Hard to test on my smartphone. \$\endgroup\$ Commented Jun 2, 2017 at 22:53
  • 1
    \$\begingroup\$ @EricDuminil Unfortunately that expression is parsed as (((a^6)|b)^9), i.e. a.^(6).|(b).^(9), so it won't work correctly. a-6|b-9==0 would work, but that's no shorter. \$\endgroup\$
    – Ventero
    Commented Jun 3, 2017 at 1:05
  • \$\begingroup\$ @Ventero: I didn't think about that. Thanks. a,b==6,9 would be nice, but it also doesn't work. \$\endgroup\$ Commented Jun 3, 2017 at 8:38
  • \$\begingroup\$ a<<b==69 doesn’t quite work either :( Try it online! \$\endgroup\$
    – roblogic
    Commented Jan 1, 2023 at 23:05
6
\$\begingroup\$

Brain-Flak, 158 154 148 140 138 126 bytes

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

Try it online!

Explanation

This code is pretty simple. We make copies of the top two items on the stack, we subtract 6 from one and 9 from the other. We then take the not of the two values. We and those values, multiply the result by 12. Multiply the inputs and subtract the two results.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You might want to capitalize not and and (or backtick them), reading your description rather tripped me up. \$\endgroup\$
    – MD XF
    Commented Jun 2, 2017 at 21:39
6
\$\begingroup\$

Factorio, 661 bytes, 6 combinators with 9 connections

There is one constant combinator set to output A and B. Change these to set the input.

Blueprint string (0.15.18):

0eNrNVm2O2jAQvcv8rEKFvSHLRuqPtrfYCkUhGWAkYkfOGDVCOUBv0bP1JLWTLQuB3U0QbfcPYvzxZt68eYr3sNxaLA0phngPlGlVQfxtDxWtVbr1a1yXCDEQYwEBqLTwUY4Z5WgmmS6WpFLWBpoASOX4HWLRBG8C+EScKr6MIJtFAKiYmLCrpw3qRNliicaleK2SAEpduata+fQObiI+zgKo/R+XIyeDWbcrA18IG71NlrhJd+RuuytPmInby1ucyq+uyFScnPHakWHrVg4VdScmnz2fPzQhjnxQlKlpS4zhk7ugLZd2BCTu0NS8IbXusMvalWgVJyuji4SUA4OYjcWmS606nm31wv8YzI+7SS66axbusHxh1zeITGaJ21C4w41XtyeHHCXH9D+o8eVUjYd3qoY47bc86rWPo158/yze2iCqPtxsmHx3r9ry3E6ylU9cTUv0aITDygwPZaaGeFMgUzbM99NBg/aMegPnV+gxRg6oLtFNZFsjfLhiJB+huZn1B87O7Crr/0Pnfz11vug5/9ePn+/E+2Hf++4beNHV8uzgRWWica6ejnDKiraM5oWXwhtC2CcVDo+FxfAWDfwc3Y9jLv4288cj5qG8IXU3Ie2zKj56xgXgZrNqOURhKGfR/GE6nzfNb7OMaxo=

The output is signal Z and is to be taken from the top and bottom deciders.

Screenshot

\$\endgroup\$
2
  • \$\begingroup\$ waaa... first time i ever see a factorio answer in ppcg xD \$\endgroup\$ Commented Sep 12, 2017 at 21:52
  • 2
    \$\begingroup\$ Not golfy enough. \$\endgroup\$
    – jimmy23013
    Commented Apr 1, 2018 at 14:04
6
\$\begingroup\$

Jelly, 8 7 bytes

Vf96SạP

Input is as an array of two integers: first the right operand, then the left one.

Try it online!

How it works

Vf96SạP  Main link. Argument: [b, a]

V        Cast [b, a] to string, then eval the resulting string.
         For [b, a] = [9, 6], this yields 96.
 f96     Filter with 96, yielding [96] if V returned 96, [] otherwise.
    S    Take the sum, yielding either 96 or 0.
      P  Compute the product of [b, a], yielding ba = ab.
     ạ   Compute the absolute difference of the results to both sides.
         When the sum is 0, this simply yields the product.
         However, when [b, a] = [9, 6], this yields 96 - 54 = 42.
\$\endgroup\$
1
  • \$\begingroup\$ This has like -1 degree of freedom. How do these coincidences even occur to you? \$\endgroup\$
    – lirtosiast
    Commented Nov 29, 2018 at 8:46
6
\$\begingroup\$

Factorio, 581 bytes, 3 combinators with 4 connections

Blueprint string (0.16.36):

0eNqllNtu4jAQht9lLldmldNCFWkvto/RCkUhGWAkYkfOGDVCefeOnV1Km7ACemPJ9vibf04+webgsLWkGfITUGV0B/nrCTra6fLgz7hvEXIgxgYU6LLxO2/HpeZFZZoN6ZKNhUEB6RrfII+HtQLUTEw44sKmL7RrNmjF4AyqsaIa7SVHQWs6eWq0dy+46OcvBT3ki1hc1GSxGi8T5XWwNYdig/vySPJYXvxFFnJXB0znT7dkOy4mYR3JspOTs6DRYoFHtD3vSe98XP/CFZ9xtsqe0mW29KdNW9qgOYffgjCOW3eHk+eR3fai1WkuttY0BWlhQM7W4TC61mPAIYzYLxbry6yS7FKxJFs54rANFdhZRP3VMBnWQk08ZvZ+ChpExqSCyX9bYVLCRfxRwbmabenAaK+03rX0/RnT5z7VJbroQnUH7HkGlq7OsDFtc8WYzWJ8WxbTs4rSEu8bZKpuGoXopkn4gH5vGEKiO/SMO5vbtCgDEjTCjwcm5AWGO4ZgknX16Tq7OhRfHiZXypU91PTRd6ZYdIjo8PnmF3+1AvmfuuBq+bRKYmnWKM2G4R1hAPnz

The bottom left constant combinator should be set to output A and B as input. The output is signal Z from the bottom right arithmetic combinator.

enter image description here

Top left: 2147483640 A, 2147483637 B
Top right: If everything = 2147483646 output B, input count
Bottom left: (input) A, (input) B
Bottom right: A * B -> Z
\$\endgroup\$
6
\$\begingroup\$

MATL, 11 bytes

[BE]=?42}Gp

Input is an array with the two numbers.

Try it online!

Explanation

[BE]    % Push array [6, 9]
=       % Implicit input: array of two numbers. Compare with [6, 9] element-wise
?       % If the two entries are true
  42    %   Push 42
}       % Else
  G     %   Push input
  p     %   Product of array
        % Implicit end. Implicit display
\$\endgroup\$
5
\$\begingroup\$

R, 33 bytes

function(a,b)`if`(a-6|b-9,a*b,42)

Returns a function.

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ You can save 3 bytes with a*b-12*!(a-6|b-9). \$\endgroup\$ Commented Jan 2, 2023 at 15:11
4
\$\begingroup\$

GW-BASIC, 55 bytes

1INPUT A:INPUT B
2IF A=6THEN IF B=9THEN ?"42":END
3?A*B

Output:

output

The first machine at pcjs has IBM BASIC, which is practically the same thing. To test this, head over there, hit Run on the machine, Press Enter-Enter and type BASICA to get into BASIC mode. Then enter the source code (it will automatically prettyprint for you), type RUN, input two integers, and done!

\$\endgroup\$
9
  • 3
    \$\begingroup\$ Are you sure the bytecount is correct? GW-BASIC uses an encoding in which some words, like INPUT, are encoded in fewer bytes than the characters that make them up would suggest. The count therefore seems high to me. \$\endgroup\$
    – user62131
    Commented Jun 2, 2017 at 21:33
  • \$\begingroup\$ @ais523 Well, I ran it through wc, and I got 55... Copy-pasted into my emulator and it had the expected behavior. \$\endgroup\$
    – MD XF
    Commented Jun 2, 2017 at 21:34
  • 3
    \$\begingroup\$ Right, my point is that you're probably scoring your submission higher than it needs to be. Get GW-BASIC to save the file, and then look at the size of the resulting file on disk; it should be smaller. \$\endgroup\$
    – user62131
    Commented Jun 2, 2017 at 21:35
  • \$\begingroup\$ @ais523 Saved as OUT.BAS: i.sstatic.net/32eH1.png Bytecount is the middle value. \$\endgroup\$
    – MD XF
    Commented Jun 2, 2017 at 21:38
  • \$\begingroup\$ OK, I wasn't expecting that, but I guess it's a wash in this situation. (Or perhaps there's more than one save format?) \$\endgroup\$
    – user62131
    Commented Jun 2, 2017 at 21:45
4
\$\begingroup\$

JavaScript (ES6), 25 bytes

x=>y=>[x*y,42][x==6&y==9]
\$\endgroup\$
4
\$\begingroup\$

Check, 34 33 bytes

.:+&>#v
#>42#v#9-!\>6-!*?
 d* ##p

Check is my new esolang. It uses a combination of 2D and 1D semantics.

Input is two numbers passed through command line arguments.

Explanation

The stack starts with the command line arguments on it. Let's call the arguments a and b.

The first part, .:+&, essentially duplicates the stack, leaving it as a, b, a, b. > pushes 0 to the stack (it is part of a numeric literal completed by 9).

# switches to 2D semantics, and v redirects the IP downwards. The IP immediately runs into a #, which switches back to 1D semantics again.

9-! checks whether b is equal to 9 (by subtracting 9 and taking the logical NOT). \>6-! then checks whether a is equal to 6. The stack now contains a, b, 1, 1 if and only if b==9 and a==6. Multiplying with * takes the logical AND of these two values, giving a, b, 1 if the inputs were 6 and 9, and a, b, 0 otherwise.

After this, the IP runs into a ?. This will switch to 2D mode if the top stack value is nonzero, and otherwise will continue in 1D mode.

If the top stack value was 1, this means that the other stack values are 6 and 9, so we push 42 to the stack with >42 and then move down to the second # on the last line.

If the top stack value was 0, then execution moves down to the next line. d removes the 0 (as ? does not do so), and then we multiply the two inputs with *. The ## switches in and out of 2D mode, doing nothing.

The branches have now joined again. The stack either contains 6, 9, 1, 42, or a*b. p prints the top stack value and then the program ends, discarding the rest of the stack.

\$\endgroup\$
1
  • \$\begingroup\$ This looks like a nifty language! \$\endgroup\$
    – Not a tree
    Commented Jun 3, 2017 at 13:12
4
\$\begingroup\$

Japt, 13 11 12 bytes

¥6&V¥9?42:N×

Try it online

  • 2 1 bytes saved thanks to obarakon.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ N¬¥69?42:N× for 11 bytes \$\endgroup\$
    – Oliver
    Commented Jun 3, 2017 at 1:54
  • \$\begingroup\$ Nice one, @obarakon. \$\endgroup\$
    – Shaggy
    Commented Jun 3, 2017 at 12:44
3
\$\begingroup\$

Pyth, 12 bytes

-*FQ*12q(6 9

Try it online

Explanation

 -*FQ*12q(6 9
  *FQ             Take the product
        q(6 9)Q   Check if the (implicit) input is (6, 9)
 -   *12          If so, subtract 12
\$\endgroup\$
1
  • \$\begingroup\$ Clever solution. I tried it with ternary statements in 15: AQ?&q6Gq9G42*GH \$\endgroup\$
    – Tornado547
    Commented Dec 14, 2017 at 2:54
3
\$\begingroup\$

Python 3, 36 33 bytes

lambda x,y:42if x==6==y-3else x*y

Try it online!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Alternate version, same size: lambda x:x[0]*x[1]if x!=(6,9)else 42. The only difference is the input type. \$\endgroup\$ Commented Jun 2, 2017 at 21:46
  • \$\begingroup\$ Nevermind - your edited version is shorter :) \$\endgroup\$ Commented Jun 2, 2017 at 21:58
  • \$\begingroup\$ The code you posted doesn't actually work, so I switched it to the working version on TIO that you linked to. \$\endgroup\$ Commented Jun 2, 2017 at 22:49
  • \$\begingroup\$ It works for me: In [1]: f=lambda x,y:42if 6==x==y-3else x*y In [2]: f(6,9) Out[2]: 42 In [3]: f(9,6) Out[3]: 54 @ETHproductions \$\endgroup\$
    – Martmists
    Commented Jun 2, 2017 at 22:56
  • \$\begingroup\$ @Martmists You were missing a space then, because your code was f=lambda x,y:42if6==x==y-3else x*y \$\endgroup\$ Commented Jun 2, 2017 at 22:58
3
\$\begingroup\$

APL (Dyalog), 10 bytes

×-12×6 9≡,

Try it online!

× the product (of the arguments)

- minus

12× twelve times

6 9≡ whether (6,9) is identical to

, the concatenation (of the arguments)

\$\endgroup\$
2
  • \$\begingroup\$ Oh wow I just saw this and my J answer is exactly the same as this :/ except one byte longer \$\endgroup\$ Commented Jun 5, 2017 at 0:36
  • \$\begingroup\$ @ConorO'Brien Makes sense. J and tacit APL are mostly equivalent, save for J's multi-char primitives (and needing Cap for a final atop). \$\endgroup\$
    – Adám
    Commented Jun 5, 2017 at 0:39
3
\$\begingroup\$

R, 41 I think I don't know how to count bytes I am new :D

function(a,b){

if(a==6&b==9){42} else {a*b}

}

I define a funtion whose arguments are a and b in this order. If a equals to 6 and b equals to 9 it returns 42, otherwise, a times b

\$\endgroup\$
5
  • \$\begingroup\$ Welcome to the site! :) \$\endgroup\$
    – DJMcMayhem
    Commented Jun 6, 2017 at 16:07
  • \$\begingroup\$ Welcome. Take into account that newlines and spaces count too. In your case, if you remove newlines and spaces (which you can) it's only 41. \$\endgroup\$
    – Masclins
    Commented Jun 12, 2017 at 14:27
  • 1
    \$\begingroup\$ You can cut two bytes by using ifelse(a==6&b==9,42,a*b) \$\endgroup\$
    – Masclins
    Commented Jun 12, 2017 at 14:33
  • \$\begingroup\$ You can cut the whole thing down to 33 bytes as function(a,b)`if`(a-6|b-9,a*b,42). \$\endgroup\$
    – rturnbull
    Commented Jun 12, 2017 at 14:45
  • \$\begingroup\$ This is only 41 bytes after you remove the unneeded whitespace, unil then, it's 47 bytes. \$\endgroup\$
    – Pavel
    Commented Jul 11, 2017 at 1:24
3
\$\begingroup\$

SPL, 356 bytes

a.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:Listen to your heart!Puck:Listen to your heart!Are you as big as the sum of a big big big cat and a cat?If so, am I as big as the sum of a big big cat and a big cat?If so, you are as big as the product of I and the sum of I and a cat.If not, you are as big as the product of you and I.Open your heart

With newlines and spaces:

a.                       *Title*
Ajax,.                   *Declare variable Ajax*
Puck,.                   *Declare variable Puck*
Act I:.
Scene I:.
[Enter Ajax and Puck]
Ajax: Listen to your heart!                  *Set Puck's value to user input*
Puck: Listen to your heart!                  *Set Ajax's value to user input*
      Are you as big as the sum of a big 
       big big cat and a cat?                *Is Ajax=9?* 
      If so, am I as big as the sum of a 
       big big cat and a big cat?            *Is Puck=6?* 
      If so, you are as big as the product 
       of I and the sum of I and a cat.      *If so, set Ajax=42* 
      If not, you are as big as the product 
       of you and I.                         *If not set Ajax=(Ajax)(Puck)*
      Open your heart                        *Print Ajax's value*
\$\endgroup\$
3
\$\begingroup\$

Standard ML (MLton), 22 20 bytes

Saved 2 bytes thanks to @Laikoni!

fun$6 $9=42| $x y=x*y

Try it online!

This is the kind of thing SML is meant for, which is why it beats shortC and Python.

The old version looked much nicer. :P

\$\endgroup\$
3
  • \$\begingroup\$ 20 bytes: Try it online! \$\endgroup\$
    – Laikoni
    Commented Jun 23, 2017 at 13:29
  • \$\begingroup\$ @Laikoni Wow, I had no idea you could use $ as an identifier! Why doesn't this compile if you remove the space between | and $? \$\endgroup\$ Commented Jun 23, 2017 at 14:14
  • \$\begingroup\$ SML distinguishes alphanumeric and symbolic identifiers, which can be quite handy for golfing. |$ is parsed as a single symbolic identifier, so everything breaks. I plan to write a tips question for SML soon and add an answer about those two types of identifiers. \$\endgroup\$
    – Laikoni
    Commented Jun 23, 2017 at 15:21
3
\$\begingroup\$

Brachylog, 8 bytes

c69∧42|×

Try it online!

A predicate which takes a pair of numbers as its input variable and outputs their correct product through its output variable.

            If the input
c           concatenated
 69         is 69,
   ∧42      then output 42,
      |     otherwise
       ×    output the product of all numbers in the input.

I have no clue why [0,69]c69 fails, but I am very glad that it does! (Running 69~cᶠw confirms that [6,9] is the only two-element list that concatenates to 69.)

\$\endgroup\$
3
\$\begingroup\$

Python 3, 33 bytes

lambda x,y:42*(x==6)*(y==9)or x*y

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Pascal, 69 characters

function p(x,y:integer):integer;begin p:=x*y-12*ord(x=6)*ord(y=9)end;

expanded

function product(x, y: integer): integer;
begin
    product := x * y - 12 * ord(x = 6) * ord(y = 9)
end;
\$\endgroup\$
2
\$\begingroup\$

Bash, 24

echo $[$1$2-69?$1*$2:42]

Saves a couple of bytes by just doing one test - checking if the string concatenation of the inputs is 69.

Try it online.

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

Retina, 36 bytes

^6 9$
6 7
\d+
$*
1(?=1* (1+))|.
$1
1

Try it online! Standard unary multiplication, just alters the input to handle the special case.

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

Jelly, 10 bytes

⁼6,9ȧ42ȯ⁸P

A monadic link taking a list of the two numbers.

Try it online!

How?

⁼6,9ȧ42ȯ⁸P - Link: list of numbers [a,b]
 6,9       - 6 paired with 9, [6,9]
⁼          - equals? (non-vectorising) (1 or 0)
     42    - literal answer, 42
    ȧ      - logical and               (42 or 0)
        ⁸  - link's left argument, [a,b]
       ȯ   - logical or                (42 or [a,b])
         P - product                   (42 or a*b)
\$\endgroup\$
3
  • \$\begingroup\$ You could've just used ?, like I did. ;) \$\endgroup\$ Commented Jun 3, 2017 at 5:52
  • \$\begingroup\$ Ah because , is special in that it is part of the literal regex pattern, so 6,9 is parsed as a single token and the quick $ can combine it with . Did you reason that, or just try it and notice that it worked? \$\endgroup\$ Commented Jun 3, 2017 at 19:53
  • 1
    \$\begingroup\$ I reasoned that. \$\endgroup\$ Commented Jun 4, 2017 at 6:52

Your Answer

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

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