Skip to content

Instantly share code, notes, and snippets.

@CodeGolfScotland
Last active October 23, 2016 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodeGolfScotland/e409eee0585351aa3dc7b295750fa74e to your computer and use it in GitHub Desktop.
Save CodeGolfScotland/e409eee0585351aa3dc7b295750fa74e to your computer and use it in GitHub Desktop.
Code Golf October 2016

October 2016 - Sum Mixed Array

Task

Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.

Return the answer as a number, not a string.

Examples:

([9, 3, '7', '3']) => 22
(['5', '0', 9, 3, 2, 1, '9', 6, 7]) => 42
(['3', 6, 6, 0, '5', 8, 5, '6', 2,'0']) => 41

*^You can assume that you will always recieved valid input

About Code Golf Scotland

@ciaranmcnulty
Copy link

ciaranmcnulty commented Oct 9, 2016

Language: PHP

Length: 37 (or 0, because it just calls a builtin function)

Solution:

function x($a){return array_sum($a);}

@ciaranmcnulty
Copy link

Language: Hack

Length: 19 (or 0, because it just calls a builtin function)

Solution:

$a==>array_sum($a);

@Kolin
Copy link

Kolin commented Oct 9, 2016

Language: PHP
Length: 29
use function array_sum as x;

@Kolin
Copy link

Kolin commented Oct 9, 2016

Language: PHP
Length: 18
$x = 'array_sum';

@joaquinferrero
Copy link

joaquinferrero commented Oct 9, 2016

Language: Perl 6 (subroutine)
Length: 17 13
Solution:

sub Σ{@_.sum}

Demo:

perl6 -e 'my @x = "3", 6, 6, 0, "5", 8, 5, "6", 2,"0"; say Σ(@x); sub Σ{@_.sum}'
41

Language: Perl 6 (builtin)
Length: 0
Demo:

perl6 -e 'my @x = "3", 6, 6, 0, "5", 8, 5, "6", 2,"0"; say @x.sum; say [+] @x;'
41
41

@ciaranmcnulty
Copy link

ciaranmcnulty commented Oct 9, 2016

@Kolin - excellent work. Iterating on it...

Language: PHP

Length: 14

Solution:

$x=@array_sum;

Copy link

ghost commented Oct 10, 2016

Language: Python
Length: 26
Solution:

x=lambda a:sum(map(int,a))

@unfunco
Copy link

unfunco commented Oct 20, 2016

Language: Ruby
Length: 26
Solution:

$*.map(&:to_i).inject(&:+)

@unfunco
Copy link

unfunco commented Oct 23, 2016

Language: Bash
Length: 23
Solution:
Save this to a file, make it executable with chmod + <file>, then pass it some arguments and query the exit code with echo $?.

exit $(IFS=+;bc<<<"$*")

The above is limited to a maximum sum of 255 because it uses exit, but it can be shortened, and allow for higher sum values, but the above is the safest method since you don't particularly want to be modifying IFS.

Language: Bash
Length: 15
Solution:
Save this to a file, make it executable with chmod +x <file>, and then pass it some arguments.

IFS=+;bc<<<"$*"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment