Skip to content

Instantly share code, notes, and snippets.

@mikehoward
Created August 2, 2012 04:20
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 mikehoward/3233464 to your computer and use it in GitHub Desktop.
Save mikehoward/3233464 to your computer and use it in GitHub Desktop.
Response to Array Iteration Interview Prob
def add1(arr, val, n)
return arr.map { |x| x == val ? x + 1 : x } if n == 0
lim = arr.length
if n > 0
return arr.map { |x| x == val ? x + 1 : x } if n >= lim
idx = 0
while idx < lim do
if arr[idx] == val
arr[idx] += 1
n -= 1
return arr if n <= 0
end
idx += 1
end
else
return arr.map { |x| x == val ? x + 1 : x } if -n >= lim
idx = lim - 1
while idx >= 0 do
if arr[idx] == val
arr[idx] += 1
n += 1
return arr if n >= 0
end
idx -= 1
end
end
return arr
end
[
[[1,4,1,5,1], 1, 0, [2,4,2,5,2]],
[[1,4,1,5,1], 1, 2, [2,4,2,5,1]],
[[1,4,1,5,1], 1, -2, [1,4,2,5,2]],
].each do |tmp|
arr, val, n, ans = tmp
result = add1 arr, val, n
puts "arr1(#{arr}) == #{result}: #{ans == result ? "OK" : "NG"}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment