Implement the iOS 11 Calculator

44

3

iOS 11 has a bug that makes the result of 1+2+3 to be 24. This is related to the animation speed, but anyway:

The task is to make 1 + 2 + 3 == 24. But only that. So you should provide a function that correctly sums most sequences but returns 24 when the arguments are 1, 2 and 3 in any order.

Example inputs:

1 2 => 3
3 4 => 7
1 2 3 4 5 6 7 8 9 => 45
3 2 1 => 24
2 1 3 => 24
1 1 => 2
1 2 3 => 24
40 2 => 42
1 2 2 4 => 9
1 2 3 4 1 2 3 => 16
1 => 1
1 23 => 24
0 1 2 => 3
3 2 3 => 8

Input can be in any format as long as your code accepts any number of arguments.

  • Support for negative numbers isn't required (all non negative numbers are required to work, that includes 0)
  • We assume correct input

Differences from another similar question: "What do you get when you multiply 6 by 9? (42)":

  • In this case your function is required to accept any number of arguments. The old question specifies exactly 2.
  • In this case order doesn't matter, while the old question specified that order 6 9 is required and 9 6 should be evaluated correctly.

Hauleth

Posted 2017-10-24T09:25:53.187

Reputation: 1 472

23

Also, iOS 11 doesn't work like that. It should be like this instead. (code explanation)

– user202729 – 2017-10-24T09:39:51.460

3@user202729 The question is probably inspired by iOS 11. I don't think the OP is asking you to replicate it entirely. – Okx – 2017-10-24T09:42:58.527

2@Okx exactly. This is for fun, not to implement it 1 to 1. Of course this could be changed to the user202729 proposal, but if he want he can create new challenge with such task. – Hauleth – 2017-10-24T09:45:36.567

3Are the inputs integer? – xnor – 2017-10-24T15:46:51.860

9

One reason this is a beautiful challenge is because of the property linked to wherein this combination of numbers is very special. The other reason this is a beautiful challenge is that it pokes fun at Apple for prioritizing (their idea of) UX over functionality.

– NH. – 2017-10-24T22:05:08.170

Possibly related: Solving twenty-four puzzles

– Greg Bacon – 2017-11-06T17:09:56.363

Answers

11

05AB1E, 9 bytes

Os{3LQi4*

Explanation:

Os{         Get the sum of the input, and then get the sorted input list
     Qi     If it is equal to...
   3L       [1, 2, 3]
       4*   Then multiply the sum by four.

Try it online!

Okx

Posted 2017-10-24T09:25:53.187

Reputation: 15 025

11

MATL, 11 10 bytes

St3:X=6*+s

Try it online! or verify all test cases

Explanation

        % implicit input [3,1,2]
S       % sort
        % STACK: [1,2,3]
t       % duplicate elements
3:      % push range 1..3
        % STACK: [1,2,3], [1,2,3], [1,2,3]
X=      % true if arrays are numerically equal
        % STACK: [1,2,3], 1
6*+     % multiply result of comparison by 6 and add to the original array
        % STACK: [7,8,9]
s       % sum
        % (implicit) convert to string and display

Cinaski

Posted 2017-10-24T09:25:53.187

Reputation: 1 588

11

Java 8, 109 106 101 90 75 74 71 66 bytes

a->{int s=0,p=0;for(int i:a){s+=i;p|=1<<i;}return s<7&p==14?24:s;}

-12 bytes thanks to @OlivierGrégoire.
-31 bytes thanks to @Nevay.

Explanation:

Try it here.

a->{                  // Method with integer-array parameter and boolean return-type
  int s=0,            //  Sum-integer, starting at 0
      p=1;            //  Product-integer, starting at 1
  for(int i:a){       //  Loop over the input-array
    s+=i;             //   Add current item to sum
    p|=1<<i;          //   Take 1 bitwise left-shifted with `i`, and bitwise-OR it with `p`
  }                   //  End of loop
  return p==14        //  If `p` is now exactly 14 (`0b1110`)
    &s<7?             //  and the sum is 6 or lower:
     24               //   Return 24
    :                 //  Else:
     s;               //   Return the sum
}                     // End of method

(Inefficient) proof that only [1,2,3] (in any order) will be the possible results when p is 0b1110 (p==14) and the sum is below 6 or lower (s<7): Try it here.

p==14 (0b1110) evaluates to true iff the input values modulo 32 cover the values 1, 2 and 3 and contain no other values (p|=1<<i) (each value has to occur 1+ times). The sum of input that matches p==14 will be larger than 6 for any input except 1,2,3 (s=a*1+b*2+c*3+u*32 with a>0,b>0,c>0,u>=0).
@Nevay


Old 71 bytes answer:

a->{int s=0,p=1;for(int i:a){s+=i;p*=i;}return a.length==3&p==s?s*4:s;}

Proof that for any three given non-zero natural numbers, only [1,2,3] (in any order) will have a sum equal to its product (1+2+3 == 1*2*3) (with a positive sum):
When the sum equals the product by Leo Kurlandchik & Andrzej Nowicki

(Inefficient) proof that only [1,2,3] (in any order) and [0,0,0] will be the possible results with non-negative numbers and a length of 3: Try it here.
So s*4 will becomes 6*4 = 24 for [1,2,3], and 0*4 = 0 for [0,0,0].

Kevin Cruijssen

Posted 2017-10-24T09:25:53.187

Reputation: 67 575

7

Jelly, 8 bytes

3R⁼Ṣ4*×S

Try it online!

Erik the Outgolfer

Posted 2017-10-24T09:25:53.187

Reputation: 38 134

7

MATL, 13 bytes

stGp=18*Gda*+

Try it online!

It's two bytes longer than the other MATL answer, but it uses a completely different (and IMO more interesting) approach, so I figured it's worth posting.

Explanation:

This solution uses the fact that:

The sum and product of an array with three elements are only equal if the array is a permutation of 1,2,3.

This takes the input, calculates the sum s, and duplicates it t. It then checks if the sum equals the product Gp=. We multiply the boolean 1/0 by 18, 18*, and checks if there are non-identical values in the vector da* (again, multiply by a boolean any(diff(x)). We then multiply the two add the last number to the original sum.

A step by step explanation:

Assume the input is [1, 2, 3]:

s                              % Implicit input, calculate the sum
                               % 6
 t                             % Duplicate the sum:
                               % 6, 6
  G                            % Grab input
                               % 6, 6, [1,2,3]
   p                           % Calculate the product
                               % 6, 6, 6
    =                          % Check if the last two elements are equal
                               % 6, 1 (true)
     18*                       % Push 18, multiply by the last number
                               % 6, 18
        G                      % Grab input
                               % 6, 18, [1,2,3]
         d                     % Calculate the difference between each element
                               % 6, 18, [1,1]
          a                    % any non zero elements?
                               % 6, 18, 1 (true)
           *                   % Multiply last two numbers
                               % 6, 18
            +                  % Add numbers. Result: 24

Stewie Griffin

Posted 2017-10-24T09:25:53.187

Reputation: 43 471

6

Python 2, 39 bytes

lambda*a:sum(a)+18*(sorted(a)==[1,2,3])

Try it online!

Uses an alternate method of adding 18 if the sorted input is [1, 2, 3] to beat the other Python answer by a byte.

FlipTack

Posted 2017-10-24T09:25:53.187

Reputation: 13 242

sorted(a)==[1,2,3] can become set(a)=={1,2,3} to save 3 bytes. – mypetlion – 2017-10-24T19:30:42.467

1@mypetlion Unfortunately that would yield true for lists with duplicates such as [1, 2, 3, 3] – FlipTack – 2017-10-24T19:31:44.693

Woops. I though we were restricted to exactly 3 inputs. – mypetlion – 2017-10-24T19:32:48.430

6

Haskell, 37 bytes

f[a,b,c]|2^a+2^b+2^c==14=24
f l=sum l

Try it online!

We use pattern matching to catch the exceptional case.

Haskell doesn't have sorting built-in. The equality 2^a+2^b+2^c==14 is satisfied only by [a,b,c] a permutation of [1,2,3] among non-negative integers. A shorter a+b+c=a*b*c almost works, but is satisfied by [0,0,0], and appending the check ,a>0 makes it 1 byte longer.

xnor

Posted 2017-10-24T09:25:53.187

Reputation: 115 687

4

Octave, 34 bytes

@(x)sum(x)+isequal(sort(x),1:3)*18

Try it online!

or

@(x)(s=sum(x))+18*~(s-6|prod(x)-6)

Try it online!

or

@(x)(s=sum(x))+18*~(s-prod(x)|s-6)

This is shorter than the approach others use: @(x){24,sum(x)}{2-isequal(sort(x),1:3)}.

Explanation:

It takes the sum of the vector, and adds 18 if the sorted vector is equal to 1,2,3. This will give 6+18=24 if the vector is a permutation of 1,2,3, and just the sum of the vector if not.

Stewie Griffin

Posted 2017-10-24T09:25:53.187

Reputation: 43 471

4

PHP, 116 bytes

This is my first attempt at a golfing challenge ever, AND it's PHP, a language which apparently sucks at golfing since I rarely see it here, so ... uhm, I tried?

<?php
//call as var/www/html/cg_ios.php --'1 2 3 4 5'
$i=$argv[1];$a=(explode(' ',$i));echo((($b=array_sum($a))==6&&count($a)==3&&in_array(3,$a)&&!in_array(0,$a)?24:$b));

Note: I did not include the comment into the bytecount.

Ungolfed

It's nothing special tbh:

$i=$argv[1];             //Read the input from the command line
$a=array_filter($c=explode(' ',$i)) //Split the input string into an array, use Whitespace as delimiter
                         //also, remove all 0 from the array, since they are not important at all
echo(                    //print the result
    ($b=array_sum($a) == 6  //If The SUM of the Array is 6 ...
        &&               //... AND ...
    (count($c) == 3)     //... the array has exactly 3 values ...
        &&               //... AND ...
    in_array(3,$a)       // ... the array contains the value 3 ...
        &&               // ... AND ...  
    !in_array(0,$a)      //... the array contains no zeros
        ?
    24                   //print 24
        :
    $b));     //print the sum of the array values we saved earlier

If you want to test this in PHPFiddle and not on console, you can obviously replace $i with anything you'd like.

Thanks to Olivier Grégoire who made me aware of the string combination [0,3,3] which returned 24 before and also helped me saving a few chars by storing the array_sum and returning that instead of running the function again.

Y U NO WORK

Posted 2017-10-24T09:25:53.187

Reputation: 181

Welcome to the site, and nice first post! – caird coinheringaahing – 2017-10-24T16:11:42.213

What about input values [0, 3, 3]? Also, can't you save the result of array_sum($a) in a variable and reuse it? – Olivier Grégoire – 2017-10-25T08:45:02.923

@OlivierGrégoire That's fixed too now, I obviously missed that case. I probably could think of a better solution tho, this is - even for my standards - really ... messy. – Y U NO WORK – 2017-10-25T09:45:59.260

Golfed code is missing $ on argv[1] – manassehkatz-Moving 2 Codidact – 2017-10-26T03:18:58.053

4

R, 47 bytes 34 bytes 36 bytes

x=scan();all(sort(x)==1:3)*18+sum(x)

Try it online!

Sum the input and add 18 if the input set is 1:3.
Thanks to @mlt for golfing off 11 bytes. Thanks to @Ayb4btu for identifying an error with the overgolfed code

Mark

Posted 2017-10-24T09:25:53.187

Reputation: 411

3

Javascript ES6, 39 bytes

Thanks to @Herman Lauenstein

a=>a.sort()=="1,2,3"?24:eval(a.join`+`)

f=a=>a.sort()=="1,2,3"?24:eval(a.join`+`)

console.log(f([1,2,3]));
console.log(f([1,2,3,4]));

Previous answer

Javascript ES6, 66 bytes

a=>(n=[1,2,3],a.every(_=>n.includes(_))?24:a.reduce((x,y)=>x+y,0))

Try it

f=a=>(n=[1,2,3],a.every(_=>n.includes(_))?24:a.reduce((x,y)=>x+y,0))

console.log(f([1,2,3]));
console.log(f([1,3,2]));
console.log(f([1,2,3,4]));

Weedoze

Posted 2017-10-24T09:25:53.187

Reputation: 931

58 bytes: a=>(Array.sort(a).join()=="1,2,3"?24:a.reduce((x,y)=>x+y)) – Okx – 2017-10-24T10:24:53.193

a.sort()=="1,2,3" works. – Neil – 2017-10-24T10:36:38.473

39 bytes: a=>a.sort()=="1,2,3"?24:eval(a.joinBT+BT) (replace BT with backticks) – Herman L – 2017-10-24T10:46:31.180

3

Swift, 67 Bytes

func z(i: [Int])->Int{return i.sorted()==[1,2,3] ?24:i.reduce(0,+)}

Could make it to 27 bytes with extensions on [Int], but that would be cheating :(

Dominik Bucher

Posted 2017-10-24T09:25:53.187

Reputation: 131

1Welcome to the site! This is a code golf competition, please can you golf you code as much as possible, such as by removing spaces. Also, I don't know Swift, but if I'm correct, this saves the input in a variable, which isn't allowed. You are however, allowed to turn this into a function. – caird coinheringaahing – 2017-10-24T14:33:42.117

1Golfed down a little: func z(i:[Int]){print(i.sorted()==[1,2,3] ?24:i.reduce(0,+))}. – Mr. Xcoder – 2017-10-24T14:46:30.503

1

Or 55 bytes (-12): {$0.sorted()==[1,2,3] ?24:$0.reduce(0,+)}as([Int])->Int, as anonymous functions are allowed by our standard rules. You can see how it works here.

– Mr. Xcoder – 2017-10-24T14:53:05.353

@Mr.Xcoder you could omit the casting and add it to the f constant you are declaring. or put the type inside the closure and you get rid of as :) – Dominik Bucher – 2017-10-24T14:59:37.650

@DominikBucher That way you'd have to add var f= into the byte count, which would eventually waste bytes. – Mr. Xcoder – 2017-10-24T15:01:57.980

2+1 for Swift. Is this the original source code of the iOS calculator? – G B – 2017-10-25T12:08:56.607

@GB yes it is original idea. – Dominik Bucher – 2017-10-25T12:21:36.967

2

Mathematica, 28 bytes

If[Sort@#=={1,2,3},24,Tr@#]&

Try it online!

J42161217

Posted 2017-10-24T09:25:53.187

Reputation: 15 931

2

Lua, 116 81 bytes

-7 bytes thanks to Jonathan

Takes input as command line arguments

Z=0S={}for i=1,#arg do
j=arg[i]+0S[j]=0Z=Z+j
end
print(#S>2 and#arg<4 and 24or Z)

Try it online!

Explanation:

Works by creating an sparse array S and adding zeroes in the indices corresponding to the input values. If parameters are 3, 4, 7 the sparse array will only have numbers at those indices. With that array, we get it's length with the operator # that counts from index 1 up to the higher index that has a value in it, if this length is exactly 3, it means that there were elements in the position 1, 2 and 3 wich is what we're looking for. The length of the sparse array will be always between 0 and N where N is the number of parameters. So we just have to check if the length of both the parameters array and the sparse array is 3.

Felipe Nardi Batista

Posted 2017-10-24T09:25:53.187

Reputation: 2 345

180 bytes – Kevin Cruijssen – 2017-10-24T13:39:17.907

You saw nothing (I edited my comment, since it wasn't after 5 minutes yet. ;P) – Kevin Cruijssen – 2017-10-24T13:43:14.280

Yeah, just found the same flaw in my own answer.. I fixed it by using array-length==3 AND A==S AND S>0. But I guess checking the length of the #args in Lua is a bit too byte-heavy? In that case you can rollback to your 90-bytes answer I guess.. :( – Kevin Cruijssen – 2017-10-24T14:22:59.393

83 bytes – Jonathan S. – 2017-10-25T17:18:54.043

@JonathanS. nice one – Felipe Nardi Batista – 2017-10-25T23:18:11.083

2

R, 55 45 54 49 57 54 48 bytes

Saved many bytes and incorrect solutions thanks to Ayb4btu.

Saved 3 9 bytes thanks to Giuseppe. I keep learning new ways to abuse the fact that F==0.

"if"((s=sum(x<-scan()))-prod(x)|sum(x|1)-3,s,24)

Try it online!

The other R answer won in the end.

BLT

Posted 2017-10-24T09:25:53.187

Reputation: 931

Fails for [0,0,0]: returns 24 instead of 0. – Olivier Grégoire – 2017-10-25T08:37:20.987

I apparently missed both 'non-negative' and 'can be a single number' in the spec. Hold on. – BLT – 2017-10-25T16:13:55.403

c(1,1,2,3) returns 28 instead of 7 – Ayb4btu – 2017-10-26T02:06:57.930

@Ayb4btu Thank you, nice catch. – BLT – 2017-10-26T02:16:29.160

@BLT I think the issue is still there, it's like the length check isn't working (I don't think it is just TIO not being updated). – Ayb4btu – 2017-10-26T05:45:59.720

@BLT Nevermind, just realised that the code section isn't the code being run. – Ayb4btu – 2017-10-26T05:54:39.007

@Ayb4btu Yep, just updated the TIO link. Should work now. – BLT – 2017-10-26T15:22:59.747

You can change s*4 to 24 and save a byte. – Ayb4btu – 2017-10-26T19:05:33.853

Me again, c(1,1,6) returns 24. Also, neat that you could get rid of the s variable. – Ayb4btu – 2017-10-26T21:42:41.367

1x=scan();s=sum(x);"if"(s-prod(x)|s-6|length(x)-3,s,24) is 54 bytes swapping the condition and using | instead of & so we can subtract. – Giuseppe – 2017-10-27T14:26:39.780

From Stewie Griffin's MATL answer: "The sum and product of an array with three elements are only equal if the array is 1,2,3.", so 48 bytes

– Giuseppe – 2017-10-27T16:35:37.520

@Giuseppe yes, that's right. the s=6 thing was left over from me trying not to check the length. I ended up having to in the end, and forgot I didn't need to check the value of the sum anymore. – BLT – 2017-10-27T16:44:54.443

2

J, 17 bytes

-6 bytes thanks to Frowny Frog

+/*1+3*1 2 3-:/:~

Sum all the numbers +/ and multiply the result by (pseudocode) 1 + 3*(is123 ? 1 : 0). That is, return the results unchanged unless the sorted list is 1 2 3 in which case we multiply the result by 4.

Try it online!

original answer

+/`(24"_)@.(1 2 3-:/:~)

Check if the sorted input is 1 2 3 -- if yes, invoke the constant function 24 (24"_); if not, return the sum +/

Try it online!

Jonah

Posted 2017-10-24T09:25:53.187

Reputation: 8 729

I don't really know J, but can 1 2 3i.3? – Uriel – 2017-10-24T20:46:33.810

@Uriel, i.3 produces 0 1 2, so you'd have to do 1+i.3 which saves no chars but is less clear. – Jonah – 2017-10-24T20:53:01.697

right, I forgot J is 0 indexed – Uriel – 2017-10-24T21:19:06.300

[:+/8"0^:(1 2 3-:/:~) – FrownyFrog – 2017-10-24T23:01:28.043

+/@,[*3*1 2 3-:/:~ – FrownyFrog – 2017-10-24T23:40:44.983

@FrownyFrog the last one is a really clever golf – Jonah – 2017-10-25T00:13:15.163

+/*1+3*1 2 3-:/:~ now it's golfed :P – FrownyFrog – 2017-10-25T00:31:15.550

2

C (gcc), 136 131 125 97 91 bytes

i,r,t;main(c,v)char**v;{for(;c-->1;)i=atoi(v[c]),r+=i,t|=1<<i;printf("%d",r<7&t==14?24:r);}

Try it online!

cleblanc

Posted 2017-10-24T09:25:53.187

Reputation: 3 360

2

C# (.NET Core), 57+18=75 bytes

a=>a.OrderBy(x=>x).SequenceEqual(new[]{1,2,3})?24:a.Sum()

Try it online!

+18 for using System.Linq;

Ayb4btu

Posted 2017-10-24T09:25:53.187

Reputation: 541

1

Retina, 21 bytes

O`
^1¶2¶3$
24
.+
$*
1

Try it online!

Input is linefeed-separated, but the test suite uses comma-separation for convenience.

Explanation

O`

Sort the numbers (lexicographically, actually, but we only care about the case that the inputs are 1, 2, 3 in some order, where that doesn't make a difference).

^1¶2¶3$
24

If the input is 1,2,3 (in some order), replace it with 24.

.+
$*

Convert each number to unary.

1

Count the number of 1s, which adds the unary numbers and converts them back to decimal.

Martin Ender

Posted 2017-10-24T09:25:53.187

Reputation: 184 808

Out of curiosity, based on your explanation I understand the final line counts all occurrences of the match (all 1s in this case). Does Retina always do this for a single final line? Or is it also possible to count all 1s somewhere in between, and then after that continue with the result to do something else (which uses two lines again for replace-actions)? Also, another related question: which functions in Retina require only a single line? The sorting (`O``) is one of them, and the other functions as well; but any other? Just trying to understand Retina a bit more. :) – Kevin Cruijssen – 2017-10-24T12:26:23.370

1

@KevinCruijssen Yes you can use a (counting) match stage somewhere in the middle, but you'll have to explicitly mark it as a match stage with M\``. It's only if there is a single trailing line that Retina defaults toMatch instead ofReplace.AGMTSare all single-line stages,Ris two lines,OandDare one or two lines depending on whether the$` option is used (which turns them into sort/deduplicate-by stages). Feel free to ping me in the Retina chatroom if you have more questions: https://chat.stackexchange.com/rooms/41525/retina

– Martin Ender – 2017-10-24T12:31:27.963

1

Haskell, 44 bytes

f a|sum a==6,product a==6,a<[6]=24|1<2=sum a

Try it online!

The permutations of [1,2,3] are the only partitions of 6 whose product is 6, barring 6 itself. (This assumes the inputs are non-negative, which seems to be the case for all the test cases… I’ve asked the OP about this.)

Lynn

Posted 2017-10-24T09:25:53.187

Reputation: 55 648

43 bytes. – totallyhuman – 2017-10-28T02:47:20.653

1

PL/SQL - 135 123 Bytes

Assuming i as an integer array input of any size:

if (select sum(s) = exp(sum(ln(s))) from unnest(i) s) then
    return 24;
else
    return (select sum(s) from unnest(i) s);
end if;

Leo Vesque

Posted 2017-10-24T09:25:53.187

Reputation: 11

Welcome to PPCG! Could you try to golf it by removing all the extra spaces, even if it makes the answer unreadable (as long as it compiles, though)? – Olivier Grégoire – 2017-10-25T08:43:10.323

1

C++17, 56 54 bytes

[](auto...i){return(-i&...)+4|(~i*...)+24?(i+...):24;}

Try it online!

Note that the function object created is usable at compile time, so the tests are performed by the compiler without having to run a program.

Explanation:

[]             // Callable object with empty closure,
(auto...i)     // deduced argument types,
{              // and deduced return type
  return       //
      (-i&...) //   If the fold over the bitwise AND of the negation of each argument
    +4|        // is unequal to -4, or
      (~i*...) //   if the product of the bitwise complements of the arguments
    +24?       // is unequal to -24, then
      (i+...): //   return the sum of the arguments, otherwise
      24;}     //   return 24.

Proof that the only nonnegative i... for which (-i&...) equals -4 and (~i*...) equals -24 are the permutations of 1, 2, 3:

We first observe that since -0 = 0, if any i = 0 then (-i&...) = 0, so we conclude that all the i are positive.

Now, note that in 2's complement, -i is equivalent to ~(i - 1), and ~i is equivalent to -(i + 1). Applying De Morgan's rule, we find that (-i & ...) = ~((i - 1) | ...) = -(((i - 1) | ...) + 1), so ((i - 1) | ...) = 3; similarly, -1 ** n * ((i + 1) * ...) = -24, so n is odd and ((i + 1) * ...) = 24.

The prime factors of 24 are 2**3 * 3, so n <= 4. If n = 1, we have i - 1 = 3 and i + 1 = 24, so n = 3. Write the i wlog as a <= b <= c, then clearly a = 1 as otherwise (a + 1)(b + 1)(c + 1) >= 27. Also c <= 4 as otherwise (a - 1)|(b - 1)|(c - 1) >= 4. c cannot be 4 as 5 is not a factor of 24, so c <= 3. Then to satisfy (a - 1)|(b - 1)|(c - 1) = 3 c = 3, b = 2 as required.

ecatmur

Posted 2017-10-24T09:25:53.187

Reputation: 1 675

1

Husk, 9 bytes

?K24Σ=ḣ3O

Try it online!

Explanation

?K24Σ=ḣ3O
        O    Sort the input
?    =ḣ3     If it is equal to [1,2,3]:
 K24           Return 24
             Else:
    Σ          Return the sum of the input

Previous solution

Gives the wrong result to [2,2], and probably other inputs too, but it was more interesting.

?ṁD→E§eΠΣ
     §eΠΣ    Build a two-element list with the product and sum of the input
?   E        If the two elements are equal:
             (true for any permutation of [1,2,3] and the list [0,0,0]
 ṁD            Double both elements and sum them
               (This is 4 times the sum: 24 for permutations of [1,2,3], 0 for [0,0,0])
             Else:
   →          Return the last element (the sum)

Try it online!

Leo

Posted 2017-10-24T09:25:53.187

Reputation: 8 482

This gives 24 for 2,2 – recursive – 2017-10-26T16:38:55.957

@recursive actually it gives 16, but you are right. And probably this gives wrong results for some longer arrays too... Damn, I need to switch to a boring solution – Leo – 2017-10-26T22:12:38.123

0

Jelly, 10 9 bytes

Ṣ24S⁼?3R¤

Try it online!

-1 byte thanks to Erik

Alternative (by Mr. Xcoder), also for 9 bytes:

3R⁼Ṣ×18+S

Try it online!

How it works

Ṣ24S⁼?3R¤ - Main link. Argument: l (list)

Ṣ         - Sort
     ?    - Ternary if statement
    ⁼     -  Condition: Is l equal to...
      3R¤ -    [1, 2, 3]
 24       -  If condition: Return 24          
   S      -  Else: Return the sum of the list

caird coinheringaahing

Posted 2017-10-24T09:25:53.187

Reputation: 13 702

You can do Ṣ24S⁼?3R¤ for 9 bytes. – Erik the Outgolfer – 2017-10-24T11:32:07.213

Or 3R⁼Ṣ×18+S for 9 bytes too. – Mr. Xcoder – 2017-10-24T11:37:07.360

0

Python 2, 41 39 bytes

-1 byte thanks to caird

-1 by inspiration from FlipTack's answer

lambda*a:sum(a)*4**(sorted(a)==[1,2,3])

Try it online!

Alternative 39 bytes solution

lambda*a:sum(a)<<2*(sorted(a)==[1,2,3])

Felipe Nardi Batista

Posted 2017-10-24T09:25:53.187

Reputation: 2 345

140 bytes – caird coinheringaahing – 2017-10-24T10:01:13.957

0

APL (Dyalog), 20 15 bytes

5 bytes saved thanks to @EriktheOutgolfer

{4*⍵[⍋⍵]≡⍳3}×+/

Try it online!

Uriel

Posted 2017-10-24T09:25:53.187

Reputation: 11 708

{4*⍵[⍋⍵]≡⍳3}×+/ – Erik the Outgolfer – 2017-10-24T19:08:50.237

0

Pushy, 12 bytes

gF3RFx?18;S#

Try it online!

This works by sorting the input and, if it is equal to [1, 2, 3], appending 18. Then, the sum is calculated and printed, yielding 24 is 18 was appended, and the normal answer otherwise.

         \ Implicit: Input on stack.
g        \ Sort input ascendingly
F3RF     \ On auxiliary stack, push range(3) -> [1, 2, 3]
x?       \ If the stacks are equal:
  18     \    Append 18 to the input
;
S#       \ Print sum of input.

FlipTack

Posted 2017-10-24T09:25:53.187

Reputation: 13 242

0

Haskell, 47 bytes

import Data.List
f l=sum$l++[18|sort l==[1..3]]

Try it online!

totallyhuman

Posted 2017-10-24T09:25:53.187

Reputation: 15 378

0

Pyth, 9 bytes

?qS3SK24s

Verify all the test cases.

Mr. Xcoder

Posted 2017-10-24T09:25:53.187

Reputation: 39 774

0

Pyth, 9 bytes

Different aproach from the other Pyth answer.

*sQ^4qS3S

Explanation:

A port from my Python answer

*sQ^4qS3SQ  # Full program (Q at the end is implicit and represents the input)

*           # A * B where A and B are the next two lines
  sQ        # Sum elements of input
  ^4        # 4 to the power of:
    qS3SQ   # Compares sorted input to [1, 2, 3] and returns 0 or 1

Try it online!

Felipe Nardi Batista

Posted 2017-10-24T09:25:53.187

Reputation: 2 345

0

PowerShell, 44 bytes

param($a)($a-join'+'|iex)+18*!(diff(1..3)$a)

Try it online!

Similar algorithm to the Python and JavaScript answers. Takes input as a literal array $a. Then immediately sums $a together, which forms the left-hand operator of the +.

The right-hand is the diff (alias for Compare-Object) of 1,2,3 and $a -- this is either an empty array if they are equal, or a non-empty array of the different items if they are not equal -- enclosed in a Boolean-not. So, if they are equal, that makes the empty array (a falsey value) into $true.

That's then multiplied by 18 which implicitly casts $true to 1 and $false to 0. So the right-hand side will be 18 if the arrays are the same, and 0 otherwise. That gives the correct result of 24 if the input array is 1,2,3 in any permutation, and the summation of the input array otherwise.

AdmBorkBork

Posted 2017-10-24T09:25:53.187

Reputation: 41 581

0

Kotlin, 46 44 bytes

if(i.sorted()==listOf(1,2,3))24 else i.sum()

Try it online!

Edits

jrtapsell

Posted 2017-10-24T09:25:53.187

Reputation: 915

Could you use listOf(1,2,3) to save 2 bytes? I don't know Kotlin, so I'm not sure. – Mr. Xcoder – 2017-10-24T12:56:12.287

0

C++, 109 bytes

#import<list>
int f(std::list<int>l){l.sort();int s=0;for(int i:l)s+=i;return l==std::list<int>{1,2,3}?24:s;}

Try it online!

Steadybox

Posted 2017-10-24T09:25:53.187

Reputation: 15 798

0

Japt -x, 14 11 bytes

n e3õ)?24:U

Try it online!

Oliver

Posted 2017-10-24T09:25:53.187

Reputation: 7 160

Nice technique, but I think this would fail on inputs [1,23] and [123]. – ETHproductions – 2017-10-24T20:02:57.263

@ETHproductions Thanks. I wish there were a better way to compare arrays. – Oliver – 2017-10-24T20:59:26.300

0

Perl 5, 25 bytes

[sort@_]~~[1..3]?24:sum@_

Try it online!

gogators

Posted 2017-10-24T09:25:53.187

Reputation: 191

As it stands, this is a code fragment. You need to include all of the bytes in your score, including command line options. – Xcali – 2017-10-30T22:30:53.157

0

Racket, 49 bytes

(λ x(if(equal?(sort x <)'(1 2 3))24(apply + x)))

Try it online!

Misha Lavrov

Posted 2017-10-24T09:25:53.187

Reputation: 4 846

0

Perl 5, 34 bytes

[sort@_]~~[1..3]?24:0+map{1..$_}@_

Try it online!

This is similar to my other answer, but does not use the import sum function. Instead it creates an array whose size is the sum of the number. But only works for non-negative integers.

gogators

Posted 2017-10-24T09:25:53.187

Reputation: 191

0

Ruby, 29 bytes

->a{a.sort==[*1..3]?24:a.sum}

dkudriavtsev

Posted 2017-10-24T09:25:53.187

Reputation: 5 781

0

C (gcc), 111 153 bytes

#define A(x)if(v[x]>v[x+1]&c>2)t=v[x],v[x]=v[x+1],v[x+1]=t;
i;s;t;f(c,v)int*v;{for(s=i=0;i<c;s+=v[i++]);A(0)A(1)A(0)return c!=3|*v-1|v[1]-2|v[2]-3?s:24;}

Try it Online!

+42: Fixed {3,2,3}, {1,1,1}, {2,2,2}, etc.

I will try to golf more later.

f is a function which takes the length of the array as an int and a pointer to the first element of the array (of unsigned ints) and returns the 'IOS 11 Calculator Sum' of the array.

Ungolfed (Old, broken version):

#define not_one_two_or_three(index) (arr[index] > 3 || arr[index] == 0)
int counter;
int sum;
int ios_sum(int length, unsigned int *arr) {
    sum = 0;
    for (counter = 0; counter < length; counter++) {
        sum += arr[counter];
    }
    if (length != 3 || not_one_two_or_three(0) || not_one_two_or_three(1) || not_one_two_or_three(2))
        return sum;
    else return 24;
}

pizzapants184

Posted 2017-10-24T09:25:53.187

Reputation: 3 174

This doesn't work for input 3, 2, 3. – cleblanc – 2017-10-26T12:55:55.543

148 bytes – ceilingcat – 2019-11-02T09:00:50.620

0

q/kdb+, 24 bytes

Solution:

(sum x;24)1 2 3~x:asc(),

Try it online!

Note: Link is to a K (oK) port of the K4 version below as there is no TIO for q/kdb+.

Examples:

q)(sum x;24)1 2 3~x:asc(),1
1
q)(sum x;24)1 2 3~x:asc(),1 2
3
q)(sum x;24)1 2 3~x:asc(),1 2 3
24
q)(sum x;24)1 2 3~x:asc(),1 2 3 4
10
q)(sum x;24)1 2 3~x:asc(),1 3 2
24

Explanation:

q is interpreted right-to-left:

(sum x;24)1 2 3~x:asc(), / the solution
                     (), / convert to list if not already a list (cannot sort atom)
                  asc    / sort list ascending
                x:       / store input in variable x                      
          1 2 3~         / is sorted list equal to list 1 2 3? boolean 0 or 1
(     ;  )               / two item list which we index into
       24                / index 1 (true), the fake result 24
 sum x                   / index 0 (false), sum the input list

Notes:

  • K4 version that aligns with TIO link: (+/x;24)1 2 3~x@<x:(), for 22 bytes
  • Q is just syntactic sugar on top of K4, sum is +/, asc is x@<x

streetster

Posted 2017-10-24T09:25:53.187

Reputation: 3 635

0

Jq 1.5, 35 bytes

if[1,2,3]==sort then 24else add end

Assumes input is an array e.g. [2,1,3]

Try it online!

jq170727

Posted 2017-10-24T09:25:53.187

Reputation: 411

0

Ruby, 28 bytes

->s{s&[*1..3]==s&&24||s.sum}

earksiinni

Posted 2017-10-24T09:25:53.187

Reputation: 121

0

Add++, 39 bytes

D,f,?!,db*@b+6B]B=VaE#3RBcB=B]b*G*18*As

Try it online!

caird coinheringaahing

Posted 2017-10-24T09:25:53.187

Reputation: 13 702

OP says negative numbers don't have to be supported, implying that non-negative numbers do... however on this answer 1 + 2 + 3 + 0 = 24 – FlipTack – 2017-10-30T19:52:37.017

Given 3, 2, 1, this outputs 6. – FlipTack – 2017-10-30T20:26:24.500