It is Friday and Friday posts are allowed to be short. In this one, I just want to post a quick solution to the following problem: Given two arrays of non-negative integers, one of which is formed by shuffling the first array and removing one element, find the element that has been removed.
With Ruby, it is possible to use a zip method.
arr1 = [1, 2, 3, 5, 65, 21, 34, 22, 87, 0, 3]
shuffled = [22, 87, 34, 0, 1, 3, 2, 5, 65, 21]
def find_missing(arr1, arr2)
arr1.sort!
arr2.sort!
arr1.zip(arr2).each do |i, j|
return i if i != j
end
end
print find_missing(arr1, shuffled) #=> 3
No comments :
Post a Comment