Created
May 15, 2014 20:45
-
-
Save cheeyeo/5b730317822e04ec350f to your computer and use it in GitHub Desktop.
Array equi in ruby
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
| def equi(arr) | |
| return 0 if arr.empty? | |
| left, right = 0, arr.inject{|sum, n| sum + n} | |
| equi_indices=[] | |
| arr.each_with_index do |val,i| | |
| left += val | |
| equi_indices << i if right == left | |
| right -= val | |
| end | |
| return -1 if equi_indices.empty? | |
| equi_indices | |
| end | |
| indices = [ | |
| [-7, 1, 5, 2,-4, 3, 0], | |
| [2, 4, 6], | |
| [2, 9, 2], | |
| [1,-1, 1,-1, 1,-1, 1], | |
| [] | |
| ] | |
| indices.each do |x| | |
| puts "%p => %p" % [x, equi(x)] | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment