-
-
Save jhsu/3244473 to your computer and use it in GitHub Desktop.
array iteration problem
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 add1(arr, val, n) | |
# how many times are we going to increment | |
increment_count = n == 0 ? arr.length : n.abs | |
# are we going up or down the array | |
indices = n < 0 ? (-1..-arr.length) : (0...arr.length) | |
# iterate and update the array in place | |
indices.each do |index| | |
arr[index] = arr[index] + 1 if val == arr[index] | |
break if (increment_count -= 1) == 0 | |
end | |
arr | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment