63
\$\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\$
11
  • 1
    \$\begingroup\$ @JonathanAllan Yes, added rules for that. \$\endgroup\$ – Tezra Jun 3 '17 at 4:09
  • 75
    \$\begingroup\$ Coincidentally the question id has 42 twice in it. \$\endgroup\$ – Erik the Outgolfer Jun 3 '17 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\$ – Please stop being evil Jun 3 '17 at 8:23
  • 15
    \$\begingroup\$ @EriktheOutgolfer …and the 12 stands for what to subtract if input is 6 and 9. \$\endgroup\$ – Adám Jun 3 '17 at 23:43
  • 12
    \$\begingroup\$ @EriktheOutgolfer Even if you read the ID backwards. \$\endgroup\$ – T. Sar Jun 5 '17 at 12:57

81 Answers 81

1 2
3
0
\$\begingroup\$

Pyth, 11 bytes

?qQ,6tT42*F

Try it online! Takes input as a list of two numbers.

Explanation

?qQ,6tT42*FQ    Implicit imput
?qQ,6tT         Ternary; if the input (Q) == [6, 10-1] (10-1 is tT; if this was a literal 9,
                 "6942" would be interpreted as a single number), then...
       42       42, else...
         *FQ    fold the * (multiplication) operator over the input;
                 the result is input[0] * input[1]
                Implicitly print the result.
\$\endgroup\$
0
\$\begingroup\$

TI-BASIC, 23 tokens (38 bytes in RAM)

TI-BASIC makes use of a token system. Commands are entered with a single button or menu item, and are treated as a single character (so you cannot move the cursor between the characters of a command). For instance, " and " is a single token.

Input A
Input B
A*B->C
If A=6 and B=9
42->C
Disp C
\$\endgroup\$
2
  • \$\begingroup\$ Using input as a list in Ans: If Ans={6,9 (newline) {42 (newline) prod(Ans is 14 tokens. Also newlines count as tokens (0x3F), so your solution is 27 tokens \$\endgroup\$ – pizzapants184 Jul 11 '17 at 2:09
  • \$\begingroup\$ Minor tips: You can prompt for 2+ variables shorter like Prompt A,B. Also, you can do implicit multiplication like AB->C. Also, you can use Ans to get rid of the ->C. And you don't need to display Ans because it is "returned" as with all TI-Basic functions. \$\endgroup\$ – Timtech Dec 14 '17 at 0:43
0
\$\begingroup\$

C#, 22 bytes

n=>m=>n==6&m==9?42:n*m
\$\endgroup\$
0
\$\begingroup\$

Braingolf, 30 bytes

VR.9e1M|*.69*e1M|vl2e76*_:R_|;

Try it online!

Explanation

VR.9e1M|*.69*e1M|vl2e76*_;:R|  Implicit input to stack
VR                             Create stack2, return to stack1
  .                            Duplicate last item
   9                           Push 9
    e                          Pop last 2 items, if they are equal..
     1M                        ..Push 1 and move it to stack2
       |                       Endif
        *                      Multiply last 2 items
         .                     Duplicate last item
          69*                  Push 54
             e                 Pop last 2 items, if they are equal..
              1M               ..Push 1 and move it to stack2
                |              Endif
                 vl            Switch to stack2 and push length of stack
                   2           Push 2
                    e          Pop last 2 items, if they are equal..
                     76*_      ..Push 42 and print it
                         ;     ..Suppress implicit output
                          :     Else
                           R   ..Return to stack1
                            |  Endif
                               Implicit if semicolon was not reached:
                                 Print last item on current stack
\$\endgroup\$
0
\$\begingroup\$

QBIC, 19 bytes

~:=6|~:=9|_x42}?a*b

Explanation:

~:=6|    If the first cmd line input is 6
~:=9|    If the second cmd line input is 9
_x42     PRINT 42 and quit
}        END IF x2
?a*b     PRINT the actual calculation

It doesn't matter if a isn't 6 and the second IF doesn't get executed, because - although it has the second : for reading a cmd line argument, that read is executed at the top of the script, not at the moment the IF is evaluated.

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

Javascript WebBrowsers - 43 41 bytes

a=function(a,b){return a==6&b==9?42:a*b;}

a is now a function call it with x & y

a(4,6) => 24
a(6,9) => 42
a(9,6) => 54

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ removed spaces around function body saved 2 bytes \$\endgroup\$ – Martin Barker Jun 6 '17 at 15:02
0
\$\begingroup\$

Perl, 32 bytes (31 + 1)

Run with -p on the command line. Takes its input as a pair of numbers, separated by a space, through stdin.

s/^6 9$/42/;s/(.+) (.+)/$1*$2/e
\$\endgroup\$
0
\$\begingroup\$

T-SQL, 36 35 bytes

SELECT IIF(a=6AND b=9,42,a*b)FROM t

Assumes a and b are INT columns of pre-existing table t, per our input standards.

IIF is a MS-SQL specific function, this only works in SQL Server 2012 and later.

-1 byte: Removed extra space before AND.

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

R, 28 bytes

Anonymous function that takes two arguments.

pryr::f(`if`(a-6|b-9,a*b,42))

Explanation

             a-6      # If a is 6, this is zero, else non-zero.
                 b-9  # If b is 9, this is zero, else non-zero.
             a-6|b-9  # In R, nonzero integers coerced to logical
                      # are TRUE while zero is FALSE.
                      # This `or` expression evaluates FALSE when
                      # a==6 and b==9, TRUE otherwise.
        `if`(       ,a*b,42) # Conditional. If TRUE, return
                             # a*b, else return 42.
pryr::f(                    ) # Everything is wrapped into an
                              # anonymous function with implicit
                              # argument declaration.
\$\endgroup\$
0
\$\begingroup\$

Modern Pascal 2.0, 34, 26 bytes

iif((a=6)&&(b=9),42,a*b);

Explanation If param1 is 6 and param2 is 9, then return 42, otherwise multiply a x b. Modern Pascal supports the alias of && for and

// Author of Modern Pascal

\$\endgroup\$
2
  • \$\begingroup\$ Could you provide a link to that language/interpreter's documentation? Is weird to see && in a language with “Pascal” in name. \$\endgroup\$ – manatwork Jun 12 '17 at 16:05
  • \$\begingroup\$ I am the author of the compiler... Tutorials \$\endgroup\$ – Ozz Nixon Jun 13 '17 at 17:31
0
\$\begingroup\$

Perl 5, 26 + 1 (-p) = 27 bytes

s/^6 9$/42/;y/ /*/;$_=eval

Try it online!

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

K (oK), 14 bytes

Solution:

(*/x;42)6 9~x:

Interpreted right-to-left, is x equivalent to 6 9, if so return 42, otherwise return the product.

Try it online!

Examples:

>(*/a;42)6 9~a:3 4
12
>(*/a;42)6 9~a:6 9
42
>(*/a;42)6 9~a:9 6
54

Notes:

My port of the J/APL solutions is 15 bytes:

(*/x)-12*6 9~x:
\$\endgroup\$
0
\$\begingroup\$

C + ecpp, 23 bytes

#def a*b a^6|b^9?a*b:42

Redefines the * operator. 42 if 6*9, the proper result otherwise.

Try it online!

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

Javascript can do it with 24 bytes: a==6&&b==9?42:a*b;

Okay 39 bytes for function a(a,b){c=(a==6&&b==9)?42:a*b}

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Welcome! By default, all submissions must be either full programs or functions. Currying is allowed, so a=>b=>a==6&&b==9?42:a*b would do. \$\endgroup\$ – Dennis Jan 7 '18 at 22:35
0
\$\begingroup\$

Add++, 51 bytes

D,e,@@,9=&!!
_
+?
$e>x>?
I,-x,+42,O,-41
-1
I,G,*G,O

Try it online!

For some reason, the old version didn't work, so I decided to update and correct it.

Old version, 52 bytes

D,e,@@,       ; Define a dyadic function, $e.
       9=     ;   Does the first argument equal 9?
       &!!    ;   AND with the second argument
_             ; Save the inputs
+?            ; Take the first input
$e>x>?        ; Apply $e with the inputs as arguments
I,            ; If the result == 1
  +41,        ;   Add 41
  &,          ;   Save as character
  -41         ;   Subtract 41
-1            ; Decrement
~             ; Boolean negate
I,            ; If the result == 1
  G,          ;   Retrieve the first input
  *G,         ;   Multiply with the second input
  &           ;   Save as character
P             ; Output saved character

Try it online!

This outputs by char code (42 -> *)

It is, so far, the only Add++ program that uses all 4 of the memory types that Add++ has.

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

CJam, 15 bytes

{:T69Ab=42T:*?}

Really straightforward.

Try it online!

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

Elixir, 23 bytes

fn 6,9->42
a,b->a*b end

Try it online!

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

Fortran (GFortran), 50 bytes

READ*,I,J
K=I*J
IF(I==6.AND.J==9)K=42
PRINT*,K
END

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I don't know Fortran, but couldn't you write IF(I==6.AND.J==9)J=7? \$\endgroup\$ – Sagittarius Dec 27 '19 at 2:13
  • \$\begingroup\$ @Sagittarius Sure thing! Why didn't I do that in the first place? No idea... \$\endgroup\$ – rafa11111 Feb 15 '20 at 17:50
0
\$\begingroup\$

x86, 14 bytes

Inputs in eax and edx, output in eax. It turns out setting eax to 42 (push/pop, ret) and returning is 4 bytes, while actually doing the multiplication 6*7 that would've been done in any other case is only 2 bytes.

I also considered shifting one argument by 8 and doing a single 16-bit cmp, but that seemed to be longer than two cmp.

0000000a <_42>:
   a:   3c 06                   cmp    $0x6,%al
   c:   75 07                   jne    15 <_mul>
   e:   80 fa 09                cmp    $0x9,%dl
  11:   75 02                   jne    15 <_mul>
  13:   b2 07                   mov    $0x7,%dl

00000015 <_mul>:
  15:   f7 e2                   mul    %edx
  17:   c3                      ret      
\$\endgroup\$
0
\$\begingroup\$

MathGolf, 10 bytes

α96α=¿ÅJ∞*

Try it online!

Explanation

The footer is just to format the output.

α                      wrap last two elements in array
 9                     push 9
  6                    push 6
   α                   wrap last two elements in array
    =                  pop(a, b), push(a==b)
     ¿                 if/else (uses one of the next two characters/blocks in the code)
      Å                start block of length 2
       J               push 21
        ∞              pop a, push 2*a
         *             pop a, b : push(a*b)
\$\endgroup\$
0
\$\begingroup\$

Wren, 30 bytes

Fn.new{|a,b|a==6&&b==9?42:a*b}

Try it online!

Explanation

Performs an extra check on 6 & 9. In other cases return the product.

Fn.new{|a,b|a==6&&b==9?42:a*b}
\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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