Last active
August 29, 2015 14:24
-
-
Save rtacconi/e463fbc9afa7f0665cf9 to your computer and use it in GitHub Desktop.
TapeEquilibrium
This file contains 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
Initial solution, test passing, 0% scores: | |
(1..a.size-2).each {|i| p (a.slice(i,a.size).inject(:+) - a.slice(0, i).inject(:+)) }.min | |
I found this on internet, 100% scores, very long: | |
puts "tape_equilibrium: " | |
return 0 if a.empty? | |
# Example data: N=5, P(1-4), A[3,1,2,4,3] | |
# P1: | |
# [3] - [1,2,4,3] | |
# [3,1] - [2,4,3] | |
# [3,1,2] - [4,3] | |
# [3,1,2,4] - [3] | |
sum = a.inject(:+) | |
left = a[0] | |
right = sum - left | |
min_diff = (right - left).abs | |
for i in 1..(a.size-2) # -2 because the last iteration is the same as the first. | |
left+= a[i] | |
right-= a[i] | |
diff = (right - left).abs | |
min_diff = [min_diff, diff].min | |
end | |
min_diff | |
Last solution, 100%: | |
def solution(a) | |
return if a.empty? | |
tail = a.inject(:+) - a[0] | |
head = a[0] | |
min_dif = (head - tail).abs | |
(1..a.size-2).each do |i| | |
head += a[i]; | |
tail -= a[i]; | |
min_dif = (head-tail).abs if (head-tail).abs < min_dif | |
end | |
min_dif | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment