g | x | w | all
Bytes Lang Time Link
081C gcc171025T155122Zcleblanc
052Racket230722T182751ZEd The &
008Thunno 2 S230722T170329ZThe Thon
017Add++171030T001307Zcaird co
011Japt x171024T145220ZOliver
013MATL171024T114212ZStewie G
047Haskell171024T105350Ztotallyh
028Ruby171027T183821Zearksiin
048R171024T155923ZBLT
036R171025T103641ZMark
009Husk171026T033252ZLeo
035Jq 1.5171026T175604Zjq170727
153C gcc171026T012358Zpizzapan
024q/kdb+171026T171930Zmkst
116PHP171024T160532ZRealit&#
5654C++17171025T224720Zecatmur
081Lua171024T123047ZFelipe N
nanC# .NET Core171025T195321ZAyb4btu
066Java 8171024T103714ZKevin Cr
034Octave171024T103704ZStewie G
00905AB1E171024T093040ZOkx
010MATL171024T094305ZCinaski
037Haskell171025T082916Zxnor
017J171024T203341ZJonah
015APL Dyalog171024T103546ZUriel
029Ruby171024T180916Zanna328p
123PL/SQL 123 Bytes171024T173602ZLeo Vesq
034Perl 5171024T155029Zgogators
049Racket171024T154851ZMisha La
025Perl 5171024T153803Zgogators
039Python 2171024T105637ZFlipTack
067Swift171024T142437ZDominik
044Haskell171024T134925ZLynn
109C++171024T135500ZSteadybo
044Kotlin171024T124835Zjrtapsel
044PowerShell171024T124609ZAdmBorkB
021Retina171024T115546ZMartin E
009Pyth171024T115142ZFelipe N
009Jelly171024T093929Zcaird co
039Python 2171024T095904ZFelipe N
008Jelly171024T113457ZErik the
009Pyth171024T111917ZMr. Xcod
012Pushy171024T104956ZFlipTack
039Javascript ES6171024T095427ZWeedoze
028Mathematica171024T093208ZZaMoC

C (gcc), 136 131 125 97 91 83 81 bytes

Thanks to @landfill babby, and @ceilingcat (of course we're not using c anymore)

r,t;main(i,v)int**v;{for(;*++v;t|=1<<i)r+=i=atoi(*v);printf("%d",r>6|t-14?r:24);}

Try it online!

Racket, 52 bytes

(define(c x)(if(equal?(sort x <)'(1 2 3))24(sum x)))

Try it online!


Explanation

We create a function called c that checks whether x is equal to '(1 2 3) when x is sorted. If it is, we return 24, otherwise we take the sum of the list.

(define (calc xs)
  (if (equal? (sort xs <) '(1 2 3))
      24
      (sum xs)))

Thunno 2 S, 8 bytes

ṠD3R⁼6×+

Try it online!

Explanation

ṠD3R⁼6×+  # Implicit input
ṠD        # Sort and duplicate
  3R⁼     # Equals [1,2,3]?
     6×+  # Multiply by 6 and add
          # Implicit output of sum

Add++, 17 bytes

L,dB#3R=''1$o$b+*

Try it online!

Japt -x, 14 11 bytes

n e3õ)?24:U

Try it online!

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

Haskell, 47 bytes

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

Try it online!

Ruby, 28 bytes

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

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.

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

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!

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!

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;
}

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:

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.

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.

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.

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;

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].

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.

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!

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

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.

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!

APL (Dyalog), 20 15 bytes

5 bytes saved thanks to @EriktheOutgolfer

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

Try it online!

Ruby, 29 bytes

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

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;

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.

Racket, 49 bytes

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

Try it online!

Perl 5, 25 bytes

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

Try it online!

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.

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 :(

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.)

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!

Kotlin, 46 44 bytes

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

Try it online!

Edits

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.

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.

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!

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

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])

Jelly, 8 bytes

3R⁼Ṣ4*×S

Try it online!

Pyth, 9 bytes

?qS3SK24s

Verify all the test cases.

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.

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]));

Mathematica, 28 bytes

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

Try it online!