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

@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