Created
May 15, 2014 21:46
-
-
Save DiegoSalazar/a274ed6fc9f9f0d90695 to your computer and use it in GitHub Desktop.
ESAAS HW0 Part 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # I iterate over ints using inject and pass in an accumulator | |
| # which for the purposes of summing will have to be 0 | |
| # each number is added to the accumulator and the final result | |
| # is returned | |
| def sum(ints) | |
| ints.inject(0) { |sum, i| sum += i } | |
| end | |
| # this was fun, I sort and mutate the ints array to maintain its | |
| # newly sorted state, pop off the last value which will now be | |
| # the max int or default to 0 if nil, then I pop another one off | |
| # defaulting to 0, and add the two values together | |
| def max_2_sum(ints) | |
| (ints.sort!.pop || 0) + (ints.pop || 0) | |
| end | |
| # this question was weird, _any_ two elements? | |
| # well ok, at first I reused the max_2_sum method thinking | |
| # if it can be any 2 i'll pick those since i already have | |
| # that method handy, so I originally wrote the method as a | |
| # one liner like this: | |
| # ints.size > 1 && max_2_sum(ints.uniq) == n | |
| # but the test failed after I uploaded, so I realized I have | |
| # to check every int to see if any of them do equal n. So I, | |
| # iterate over ints by creating an enumerator and mapping over it | |
| # getting the index of another int, adding to current int, doing the | |
| # equality checking to build up an array of answers, then finally | |
| # checking if the result array contained a true value | |
| def sum_to_n?(ints, n) | |
| return false if ints.size < 2 | |
| ints.each_with_index.map do |i, x| | |
| other_index = x + 1 | |
| other_int = ints[other_index == ints.size ? 0 : other_index] | |
| i + other_int == n | |
| end.any? | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment