Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created May 9, 2018 04:22
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 earlonrails/5fc0788e31e339899733a6016c8dbebe to your computer and use it in GitHub Desktop.
Save earlonrails/5fc0788e31e339899733a6016c8dbebe to your computer and use it in GitHub Desktop.
Given an array of integers greater than zero, find if it is possible to split it in two (without reordering the elements), such that the sum of the two resulting arrays is the same. Print the resulting arrays. https://www.careercup.com/question?id=5716403849003008
#!/usr/bin/env ruby
test_cases = [
[1,2,3,4,5,6,21],
[1,90, 50, 30, 5, 3, 2, 1 ],
[1, 50, 900, 1000]
]
def array_sums(arr)
sum_one = 0
sum_two = arr.reduce(:+)
arr.each_index do |i|
sum_two -= arr[i]
sum_one += arr[i]
if sum_one == sum_two
mid = i + 1
return [
arr[0..i],
arr[mid..-1]
]
end
end
false
end
test_cases.each do |t|
arr = array_sums(t)
puts arr.inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment