62
\$\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\$
  • 1
    \$\begingroup\$ @JonathanAllan Yes, added rules for that. \$\endgroup\$ – Tezra Jun 3 '17 at 4:09
  • 74
    \$\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
  • 14
    \$\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
  • 11
    \$\begingroup\$ @EriktheOutgolfer Even if you read the ID backwards. \$\endgroup\$ – T. Sar Jun 5 '17 at 12:57

82 Answers 82

2
\$\begingroup\$

J, 11 bytes

*-12*6 9-:,

Try it online!

Surprisingly elegant.

*-12*6 9-:,
     6 9-:,     see if 6 9 matches the paired input
  12*           multiply that by 12
 -              and subtract this from
*               the product of the inputs
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

PHP, 35 bytes

<?=([$a,$b]=$_GET)==[6,9]?42:$a*$b;
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Sadly this fails for more than just 6 * 9 e.g. 7 * 9 = 49. \$\endgroup\$ – Christoph Jun 4 '17 at 9:50
  • \$\begingroup\$ couldn't get the above to work, this works <?=($a=$_GET)==[6,9]?42:$a[0]*$a[1]; \$\endgroup\$ – inarilo Jun 5 '17 at 12:51
  • 1
    \$\begingroup\$ @inarilo It requires PHP 7.1: sandbox.onlinephpfunctions.com/code/…. \$\endgroup\$ – user63956 Jun 5 '17 at 12:56
  • \$\begingroup\$ @inarilo $b!=9|$a!=6 could have solved the problem ... but at what cost! \$\endgroup\$ – Titus Jun 12 '17 at 16:13
2
\$\begingroup\$

Prolog, 45 Bytes

m(6,9,42).
m(X,Y,Z):-(X=\=6;Y=\=9),Z is X*Y.
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! Always good to see someone golfing in Prolog :). I have edited this answer to include code formatting. \$\endgroup\$ – Ad Hoc Garf Hunter Jun 5 '17 at 16:15
  • \$\begingroup\$ @WheatWizard Thank you :). Yes I've noticed it's a very rare occurrence :D \$\endgroup\$ – s3attar Jun 7 '17 at 0:40
2
\$\begingroup\$

Octave, 23 bytes

@(x,y)x*y-12*~(x-6|y-9)

Try it online!

Explanation

~ is logical NOT, and | is logical OR. So, in pseudocode, this computes

x*y - 12*NOT(x-6 OR y-9)
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Python3, 59 bytes

-1 bytes thanks to Stephen

a=input();print(42if a=='6 9'else eval(a.replace(' ','*')))

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @StephenS thanks \$\endgroup\$ – motatoes Jun 6 '17 at 15:25
2
\$\begingroup\$

C#, 144 bytes

class I{I(int x)=>v=x;int v;public static int operator*(I a,I b)=>a.v==6&&b.v==9?42:a.v*b.v;public static implicit operator I(int x)=>new I(x);}

Run in C# Pad

Usage: (I)6*9

Explanation

class I {
    // Constructor saves the int value in field v
    I(int x) => v = x;
    int v;

    // Redefine the multiplication operator
    public static int operator*(I a, I b) => 
        a.v==6 && b.v==9 ? // If the values are 6 and 9,
            42 : // return 42, else
            a.v * b.v; // return the normal multiplication

    // Add implicit conversion from int to I, so `I x = 5;` is valid
    public static implicit operator I(int x) => 
        new I(x);
}

Usage:

(I)6*9; // Convert 6 to I. To be able to apply the operator, 9 will
        // be implicitly converted as well.

It's not the shortest possible approach within the challenges terms, but I figured it interesting enough to post.


C#, 25 bytes, but not as fun

(x,y)=>x==6&&y==9?42:x*y;

Run in C# Pad

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Why not use a lambda? You could probably implement one in a small fraction of the bytes as this solution. \$\endgroup\$ – user18932 Jun 5 '17 at 0:13
  • \$\begingroup\$ This is code golf not a business solution. Can you at least try to golf this solution? \$\endgroup\$ – TheLethalCoder Jun 5 '17 at 8:39
2
\$\begingroup\$

x86_64 machine language for Linux, 20 19 18 bytes

00:       83 fe 09                cmp    $0x9,%esi
03:       75 09                   jne    0xe
05:       31 c0                   xor    %eax,%eax
07:       83 ff 06                cmp    $0x6,%edi
0a:       b0 2a                   mov    $0x2a,%al
0c:       74 03                   je     0x11
0e:       96                      xchg   %esi,%eax
0f:       f7 ef                   imul   %edi
11:       c3                      retq

If you want to Try it online! for youself, compile and run the following C program

#include<stdio.h>
#include<math.h>

int h(int a,int b){return a-6|b-9?a*b:42;}
const char hh[]="\x83\xfe\tu\t1\xc0\x83\xff\6\xb0*t\3\x96\xf7\xef\xc3";
int main(){
  for( int f=-10; f<10; f++ ) {
    for( int g = -10; g<10; g++ ) {
      printf( "%d %d %d %d\n", f, g, h(f, g), ((int(*)(int,int))hh)(f,g) );
    }
  }
}
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

><>, 16 bytes

:{:}*}9=$6=*c*-n

Try it online!

Pretty simple. Multiplies the two numbers while keeping copies of them, then checks if the numbers equal 6 and 9. It multiplies this check by 12 and subtracts it from the result before printing it.

| improve this answer | |
\$\endgroup\$
2
\$\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.)

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Ohm, 11 bytes

*┼6E┘9E&?42

Try it online!

*            Implicit inputs. Multiply
 ┼6E         First input == 6?
    ┘9E      Second input == 9?
       &     Logical and
        ?42  If true push (and output) 42
             Else implicit output the product
| improve this answer | |
\$\endgroup\$
1
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Batch, 30 bytes

@cmd/cset/a%1*%2-12*!(%1%2-69)

Subtracts 12 if the input numbers were 6 and 9.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

dc, 22 bytes

[42 1]sX[k6=X]sZd9=Z*p

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

GolfScript, 18 bytes

."6 9"={;42}{~*}if

Try it online!

Strict input format: numbers on a single line separated by a single space, nothing else.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 23 22 bytes

x=>y=>x==6&y==9?42:x*y

-1 byte thanks to Shaggy

f=
x=>y=>x==6&y==9?42:x*y

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

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Save a byte by using a single &. \$\endgroup\$ – Shaggy Jun 3 '17 at 10:27
1
\$\begingroup\$

F#, 25 bytes

function 6,9->42|x,y->x*y

Try it!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @WheatWizard May be of help: tio.run/#fs-mono \$\endgroup\$ – Beta Decay Jun 5 '17 at 12:16
  • \$\begingroup\$ @WheatWizard I know, I just thiught you didn't have a method of running F# programs \$\endgroup\$ – Beta Decay Jun 5 '17 at 13:44
  • 1
    \$\begingroup\$ @WheatWizard I added a link where you can run the code. The code contains more stuff (binding the function to an identifier, calling it, printing the result) so you can see what's going on. \$\endgroup\$ – Asik Jun 5 '17 at 14:34
  • \$\begingroup\$ You can get rid of the () around x,y and 6,9 it is not necessary. \$\endgroup\$ – Ad Hoc Garf Hunter Jun 5 '17 at 14:39
1
\$\begingroup\$

PowerShell, 42 bytes

Appropriately, but not very impressively, a 42 byte scriptblock function which is a basic if/else made from array indexing with a little number-to-string type coercing happening:

$f={param($a,$b)(($a*$b),42)["$a$b"-eq69]}

e.g.

PS C:\> & $f 6 9
42

PS C:\> & $f 9 6
54

Previous approach, 44 bytes:

$f={(($a=$args-join"*"),42)[$a-eq'6*9']|iex}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Prolog

multiplication(6, 9, 42) :- !.
multiplication(X, Y, Z) :- Z is X * Y.

Ugly Prolog, 33 bytes

m(6,9,42):-!.
m(X,Y,Z):-Z is X*Y.

Test it here

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It looks like you have a good deal of extra whitespace here. You could save some bytes by removing almost all of the whitespace in this answer. \$\endgroup\$ – Ad Hoc Garf Hunter Jun 6 '17 at 14:55
  • \$\begingroup\$ Oh but I like white spaces and bytes. It wouldn't be Prolog if it was optimised under any metric and not pretty. \$\endgroup\$ – pluraliseseverythings Jun 6 '17 at 15:02
  • 5
    \$\begingroup\$ This is a code-golf competition. The goal is to minimize bytes. \$\endgroup\$ – Ad Hoc Garf Hunter Jun 6 '17 at 15:05
  • \$\begingroup\$ You need to take input of a sort. How does this work? Does the second line define a function? \$\endgroup\$ – Rɪᴋᴇʀ Jun 6 '17 at 15:11
  • \$\begingroup\$ OkIAddedANewVersion! \$\endgroup\$ – pluraliseseverythings Jun 6 '17 at 15:11
1
\$\begingroup\$

GNU sed, 98 75 + 1 = 99 76 bytes

+1 byte for -r flag. Takes input as two unary numbers separated by a newline. -23 bytes thanks to Ephphatha.

y/1/0/
N
s/^(0{6}\n1{7})11$/\1/
h
s/0+//
x
s/1+//
:
s/0//;TX
G;b
:X
s/\n//g

Try it online! (Delete the # in the "Footer" section if you don't want to count 1s by hand.)

Explanation

Almost a third of this code (line 3 below) is devoted to converting 6×9 to 6×7. The rest is unary multiplication, which is easy: To multiply a and b, just replace each digit in a with the digits of b.

y/1/0/    # Replace 1s on this line with 0s
N         # Append next line to this line
s/^(0{6}\n1{7})11$/\1/  # If the inputs are 6 and 9,, replace the 9 with 7
h         # Copy to hold space
s/0+//    # Delete 0s (1st argument)
x         # Swap pattern and hold space
s/1+//    # Delete 1s (2nd argument)
:
  s/0//;TX  # Delete a 0; if there weren't any, branch to :X
  G;b       # Append a copy of the hold space (1s) to pattern space; branch to :
:X
s/\n//g   # Remove all newlines
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ "and 6*9 equals 42 instead of 54. 9*6 equals 54 still" - you can save some bytes by only handling the 6\n9 order - s/^(0{6}\n)11(1{7})$/\1\2/ \$\endgroup\$ – Ephphatha Jun 4 '17 at 11:37
  • \$\begingroup\$ s/^(0{6}\n1{7})11$/\1/ should work as well \$\endgroup\$ – Ephphatha Jun 5 '17 at 5:27
1
\$\begingroup\$

Noether, 24 bytes

{I~a6=I~b9=&}{42P}{ab*P}

Try it here!

Explanation:

{           }            - If
 I                       - Push user input
  ~a                     - Store top item of stack in variable a
    6                    - Push 6
     =                   - Pop top two items and return 1 if they are equal
      I                  - Push user input
       ~b                - Store top item of stack in variable b
         9               - Push 9
          =              - Pop top two items and return 1 if they are equal
           &             - Pop top two items and bitwise AND
             {   }       - If true then
              42         - Push 42
                P        - Print top item
                  {    } - Else
                   a     - Push variable a onto the stack
                    b    - Push variable b onto the stack
                     *   - Pop top two items and multiply
                      P  - Print top item
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ What do I put in input to make this work? \$\endgroup\$ – Tezra Jun 18 '17 at 15:15
  • \$\begingroup\$ @Tezra Hold on I'll edit the link \$\endgroup\$ – Beta Decay Jun 18 '17 at 16:01
  • \$\begingroup\$ @Tezra See the new link :D \$\endgroup\$ – Beta Decay Jun 18 '17 at 16:04
1
\$\begingroup\$

q/kdb+, 19 17 bytes

Solution:

{(prd x;42)x~6 9}

Example:

q){(prd x;42)x~6 9}6 9
42
q){(prd x;42)x~6 9}6 10
60
q){(prd x;42)x~6 9}9 6
54

Explanation:

If the input is the exact list (6;9) return 42 else multiply together:

{(prd x;42)x~6 9} / the solution
{               } / lambda function
           x~6 9  / is input the list (6;9) (0b or 1b)
 (     ;  )       / two item list 
  prd x           / if false (index 0) then multiply together
        42        / if true (index 1) then return 42
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Excel, 28 bytes

Takes inputs in A1 and B1

=IF(AND(A1=6,B1=9),42,A1*B1)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

TI-Basic, 16 15 13 bytes

prod(Ans)-12prod(Ans={6,9

Value is returned as from any function.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Input :XY-12(X=6 and Y=9 is a byte shorter. \$\endgroup\$ – lirtosiast Jul 11 '17 at 1:05
  • \$\begingroup\$ @lirtosiast Thanks! \$\endgroup\$ – Timtech Jul 11 '17 at 1:07
  • \$\begingroup\$ prod(Ans)-12prod(Ans={6,9 using input in Ans for 13 bytes \$\endgroup\$ – pizzapants184 Dec 12 '17 at 16:45
  • \$\begingroup\$ @pizzapants184 Smart! That's probably the optimal solution. \$\endgroup\$ – Timtech Dec 14 '17 at 0:38
1
\$\begingroup\$

Commentator, 223 bytes

//{-//
?{-{- {- -}-}-}e# e#
-}
?{- {- -}-}e# e#
{-{-{-{-{-         e#-}//
:# 
<#-}-}-}-}      e#//
:# 
<#
:{-{-{-{-{-# -}-}-}-}-}
<#
:{-{-{-{-#{-#-}-}-}-}-}
{-{-{-{-!{-!-}-}-}!{-{-{-            -}!-}#{-
?-} {-e# e#
-}e#-}//

Try it online!

How it works

An s is used to denote a space. Example inputs 6 and 9. Tape head denoted with a surrounding ()

//                                             - Take input;     TAPE = [ (6)  0   0   0   0   0 ]
  {-                                           - Move right;     TAPE = [  6  (0)  0   0   0   0 ]
    //                                         - Take input;     TAPE = [  6  (9)  0   0   0   0 ]
?                                              - While tape head...
 {-                                            -   Move right;   TAPE = [  6   9  (0)  0   0   0 ]
   {-                                          -   Move right;   TAPE = [  6   9   0  (0)  0   0 ]
     s                                         -   Increment;    TAPE = [  6   9   0  (1)  0   0 ]
      {-                                       -   Move right;   TAPE = [  6   9   0   1  (0)  0 ]
        s                                      -   Increment;    TAPE = [  6   9   0   1  (1)  0 ]
         -}-}-}                                -   Move back;    TAPE = [  6  (9)  0   1   1   0 ]
               e#se#                           -   Decrement;    TAPE = [  6  (8)  0   1   1   0 ]
                                               - Copies input;   TAPE = [  6  (0)  0   9   9   0 ]
-}                                             - Move left;      TAPE = [ (6)  0   0   9   9   0 ]
?                                              - While tape head...
 {-                                            -   Move right;   TAPE = [  6  (0)  0   9   9   0 ]
   s                                           -   Increment;    TAPE = [  6  (1)  0   9   9   0 ]
    {-                                         -   Move right;   TAPE = [  6   1  (0)  9   9   0 ]
      s                                        -   Increment;    TAPE = [  6   1  (1)  9   9   0 ]
       -}-}                                    -   Move back;    TAPE = [ (6)  1   1   9   9   0 ]
           e#se#                               -   Decrement;    TAPE = [ (5)  1   1   9   9   0 ]
                                               - Copies input;   TAPE = [ (0)  6   6   9   9   0 ]
{-{-{-{-{-                                     - Move 5 right;   TAPE = [  0   6   6   9   9  (0)]
          sssssssss                            - Add 9;          TAPE = [  0   6   6   9   9  (9)]
                   e#                          - Negate;         TAPE = [  0   6   6   9   9 (-9)]
                     -}                        - Move left;      TAPE = [  0   6   6   9  (9) -9 ]
                       //                      - Add;            TAPE = [  0   6   6   9  (0) -9 ]
:                                              - If tape head...
 #                                             -   Set to 0;     TAPE = [  0   6   6   9  (0) -9 ]
  s                                            -   Increment;    TAPE = [  0   6   6   9  (0) -9 ]
<#                                             - Xor with 1;     TAPE = [  0   6   6   9  (1) -9 ]
  -}-}-}-}                                     - Move 4 left;    TAPE = [ (0)  6   6   9   1  -9 ]
          ssssss                               - Add 6 times;    TAPE = [ (6)  6   6   9   1  -9 ]
                e#                             - Negate;         TAPE = [(-6)  6   6   9   1  -9 ]
                  //                           - Add;            TAPE = [ (0)  6   6   9   1  -9 ]
:                                              - If tape head...
 #                                             -   Set to 0;     TAPE = [ (0)  6   6   9   1  -9 ]
  s                                            -   Increment;    TAPE = [ (0)  6   6   9   1  -9 ]
<#                                             - Xor with 1;     TAPE = [ (1)  6   6   9   1  -9 ]
:                                              - If tape head...
 {-{-{-{-{-                                    -   Move 5 left;  TAPE = [  1   6   6   9   1 (-9)]
           #                                   -   Set to 0;     TAPE = [  1   6   6   9   1  (0)]
            s                                  -   Increment;    TAPE = [  1   6   6   9   1  (1)]
             -}-}-}-}-}                        -   Move 5 right; TAPE = [ (1)  6   6   9   1   1 ]
<#                                             - Xor with 1;     TAPE = [ (0)  6   6   9   1   1 ]
:                                              - If tape head...
 {-{-{-{-                                      -   Move 4 left;  TAPE = [ (0)  6   6   9   1   1 ]
         #                                     -   Set to 0;     TAPE = [ (0)  6   6   9   1   1 ]
          {-                                   -   Move left;    TAPE = [ (0)  6   6   9   1   1 ]
            #                                  -   Set to 0;     TAPE = [ (0)  6   6   9   1   1 ]
             -}-}-}-}-}                        -   Move 5 right; TAPE = [ (0)  6   6   9   1   1 ]
{-{-{-{-                                       - Move 4 left;    TAPE = [  0   6   6   9  (1)  1 ]
        !                                      - Product;        TAPE = [  0   6   6   9  (1)  1 ]
         {-                                    - Move left;      TAPE = [  0   6   6   9   1  (1)]
           !                                   - Product;        TAPE = [  0   6   6   9   1  (0)]
            -}-}-}                             - Move 3 right;   TAPE = [  0   6  (6)  9   1   0 ]
                  !                            - Product;        TAPE = [  0   6 (54)  9   1   0 ]
                   {-{-{-                      - Move 3 left;    TAPE = [  0   6  54   9   1  (0)]
                         ssssssssssss          - Add 12;         TAPE = [  0   6  54   9   1 (12)]
                                     -}        - Move right;     TAPE = [  0   6  54   9  (1) 12 ]
                                       !       - Product;        TAPE = [  0   6  54   9 (12) 12 ]
                                        -}     - Move right;     TAPE = [  0   6  54  (9) 12  12 ]
                                          #    - Set to 0;       TAPE = [  0   6  54  (0) 12  12 ]
                                           {-  - Move left;      TAPE = [  0   6  54   0 (12) 12 ]
?                                              - While tape head...
 -}                                            -   Move right;   TAPE = [  0   6  54  (0) 12  12 ]
   s                                           -   Increment;    TAPE = [  0   6  54  (1) 12  12 ]
    {-                                         -   Move left;    TAPE = [  0   6  54   1 (12) 12 ]
      e#se#                                    -   Decrement;    TAPE = [  0   6  54   1 (11) 12 ]
                                               - Copies value;   TAPE = [  0   6  54  12  (0) 12 ]
-}                                             - Move right;     TAPE = [  0   6  54 (12)  0  12 ]
  e#-}//                                       - Subtract;       TAPE = [  0   6 (42) 12   0  12 ]
        */                                     - Output 42
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

PHP, 63 bytes

<?php function mult($a,$b){return ($a==6&&$b==9)?42:$a*$b;}?>

and this returns the proper values for 6*9 and 9*6

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! You can save a few bytes by shortening the name of your function mult to a single character. If you are interested in further PHP golfing then we have a page full of tips here. \$\endgroup\$ – 0 ' Jan 7 '18 at 22:04
1
\$\begingroup\$

Forth (gforth), 27 bytes

2dup 9 = swap 6 = * 2 * - *

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Julia 0.6, 26 bytes

This isn't the shortest answer, but it may be the most transformative. This define a new infix function (not *!). Because Julia supports generic programming, is now defined for all combinations of types, and works nearly anywhere * works. For example:

6 ∗ 9 = 42 # with integers
9 ∗ 6 = 54
5 ∗ 5 = 25
6.0 ∗ 9 = 42 # and floating points
(6 + 0 ∗ im) ∗ 9 = 42 # and complex
6.0 ∗ 9 // 1 = 42 # rational numbers
"abc" ∗ "def" = "abcdef" # string concatenation
6 .∗ [1 4 9; 4 5 6; 7 8 9] = [6 24 42; 24 30 36; 42 48 42] 
# even elementwise multiplication with an array
∗(x,y)=x==6&&y==9?42:x*y

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Minecraft Functions (18w11a, 1.13 snapshots), 317 bytes

minecraft calculator

Uses two functions

a:

scoreboard objectives add c dummy
execute if score z a matches 6 if score z b matches 9 run scoreboard players set z c 1
execute if score z c matches 1 run tellraw @s {"text":42}
execute unless score z c matches 1 run function b

b:

scoreboard players operation z a *= z b
tellraw @s {"score":{"name":"z","objective":"a"}}

Usage

Takes input through two scoreboard objectives on the fake player z, a and b, set them with /scoreboard players set z a 6 and /scoreboard players set z b 9. Then call the function with /function a

For the function to run again, the c objective has to be zeroed with /scoreboard players set z c 0

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Whitespace, 120 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input1][S S S T    T   S N
_Push_6][T  S S T   _Subtract][N
T   S T N
_If_0_jump_to_Label_SIX][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][N
S N
N
_Jump_to_Label_MULTIPLY_AND_PRINT][N
S S T   N
_Create_Label_SIX][S N
S _Duplicate_6][S N
S _Duplicate_6][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input2][S S S T    S S T   N
_Push_9][T  S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_NINE][N
S N
N
_Jump_to_Label_MULTIPLY_AND_PRINT][N
S S S N
_Create_Label_NINE][S N
T   _Swap_top_two][S S S T  T   T   N
_Push_7][N
S S N
_Create_Label_MULTIPLY_AND_PRINT][T S S N
_Multiply][T    N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer a = input_1
If a is 6:
  Call function SIX()
Else:
  Integer b = input_2
  Call function MULTIPLY_AND_PRINT()

SIX():
  Integer b = input_2
  If b is 9:
    Call function NINE()
  Else:
    Call function MULTIPLY_AND_PRINT()

NINE():
  Swap [6,9] to [9,6]
  Push 7
  Call function MULTIPLY_AND_PRINT()

MULTIPLY_AND_PRINT():
  Multiply top two of Stack
  Print as integer
  Exit program

Example runs:

Inputs: -5 and 3

Command    Explanation                  Stack         Heap         STDIN    STDOUT   STDERR

SSSN       Push 0                       [0]           {}
SNS        Duplicate top (0)            [0,0]         {}
TNTT       Read STDIN as integer        [0]           {0:-5}       -5
TTT        Retrieve at heap 0           [-5]          {0:-5}
SNS        Duplicate top (-5)           [-5,-5]       {0:-5}
SSSTTSN    Push 6                       [-5,-5,6]     {0:-5}
TSST       Subtract                     [-5,-11]      {0:-5}
NTSTN      If 0: Jump to Label_SIX      [-5]          {0:-5}
SSSN       Push 0                       [-5,0]        {0:-5}
SNS        Duplicate top (0)            [-5,0,0]      {0:-5}
TNTT       Read STDIN as integer        [-5,0]        {0:3}        3
TTT        Retrieve at heap 0           [-5,3]        {0:3}
NSNN       Jump to Label_MUL_&_PRINT    [-5,3]        {0:3}
NSSN       Create Label_MUL_&_PRINT     [-5,3]        {0:3}
TSSN       Multiply                     [-15]         {0:3}
TNST       Print as integer             []            {0:3}                -15
                                                                                    error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).

Inputs: 6 and -4

Command    Explanation                  Stack         Heap         STDIN   STDOUT   STDERR

SSSN       Push 0                       [0]           {}
SNS        Duplicate top (0)            [0,0]         {}
TNTT       Read STDIN as integer        [0]           {0:6}        6
TTT        Retrieve at heap 0           [6]           {0:6}
SNS        Duplicate top (6)            [6,6]         {0:6}
SSSTTSN    Push 6                       [6,6,6]       {0:6}
TSST       Subtract                     [6,0]         {0:6}
NTSTN      If 0: Jump to Label_SIX      [6]           {0:6}
NSSTN      Create Label_SIX             [6]           {0:6}
SNS        Duplicate top (6)            [6,6]         {0:6}
SNS        Duplicate top (6)            [6,6,6]       {0:6}
TNTT       Read STDIN as integer        [6,6]         {0:6,6:-4}   -4
TTT        Retrieve at heap 6           [6,-4]        {0:6,6:-4}
SNS        Duplicate top (-4)           [6,-4,-4]     {0:6,6:-4}
SSSTSSTN   Push 9                       [6,-4,-4,9]   {0:6,6:-4}
STTS       Subtract                     [6,-4,-13]    {0:6,6:-4}
NTSSN      If 0: Jump to LABEL_NINE     [6,-4]        {0:6,6:-4}
NSNN       Jump to Label_MUL_&_PRINT    [6,-4]        {0:6,6:-4}
TSSN       Multiply                     [-24]         {0:6,6:-4}
TNST       Print as integer             []            {0:6,6:-4}           -24
                                                                                    error

Program stops with an error: No exit defined
Try it online (with raw spaces, tabs and new-lines only).

Inputs: 6 and 9:

Command    Explanation                  Stack         Heap         STDIN   STDOUT   STDERR

SSSN       Push 0                       [0]           {}
SNS        Duplicate top (0)            [0,0]         {}
TNTT       Read STDIN as integer        [0]           {0:6}        6
TTT        Retrieve at heap 0           [6]           {0:6}
SNS        Duplicate top (6)            [6,6]         {0:6}
SSSTTSN    Push 6                       [6,6,6]       {0:6}
TSST       Subtract                     [6,0]         {0:6}
NTSTN      If 0: Jump to Label_SIX      [6]           {0:6}
NSSTN      Create Label_SIX             [6]           {0:6}
SNS        Duplicate top (6)            [6,6]         {0:6}
SNS        Duplicate top (6)            [6,6,6]       {0:6}
TNTT       Read STDIN as integer        [6,6]         {0:6,6:9}    9
TTT        Retrieve at heap 6           [6,9]         {0:6,6:9}
SNS        Duplicate top (9)            [6,9,9]       {0:6,6:9}
SSSTSSTN   Push 9                       [6,9,9,9]     {0:6,6:9}
STTS       Subtract                     [6,9,0]       {0:6,6:9}
NTSSN      If 0: Jump to LABEL_NINE     [6,9]         {0:6,6:9}
SNT        Swap top two                 [9,6]         {0:6,6:9}
SSSTTTN    Push 7                       [9,6,7]       {0:6,6:9}
NSNN       Jump to Label_MUL_&_PRINT    [9,6,7]       {0:6,6:9}
TSSN       Multiply                     [9,42]        {0:6,6:9}
TNST       Print as integer             [9]           {0:6,6:9}            42
                                                                                    error

Program stops with an error: Label does not exist
Try it online (with raw spaces, tabs and new-lines only).

| improve this answer | |
\$\endgroup\$
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.
| improve this answer | |
\$\endgroup\$

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.