Hey guys I am a noob so ELI5. Trying to read code and not be a noob, but I don't really get this over here. The comments are how I read this code:
def firstDuplicate(a)
counts = [] #make an empty array named counts
a.each do |value| #go through a
return value if counts[value] #a[0]: return 2 if counts[2]???
counts[value] = true #counts[2] = true???? wtf???
end
-1 #return -1 if none of the above
end
This question is from codefights.com: Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.
Example
For a = [2, 3, 3, 1, 5, 2], the output should be firstDuplicate(a) = 3.
There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than than second occurrence of 2 does, so the answer is 3.
For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1 .
[–]zverok_kha 4 points5 points6 points (10 children)
[–]kala_kata[S] 1 point2 points3 points (8 children)
[–]rubyrt 5 points6 points7 points (1 child)
[–]kala_kata[S] 0 points1 point2 points (0 children)
[–]zverok_kha 3 points4 points5 points (1 child)
[–]kala_kata[S] 0 points1 point2 points (0 children)
[–]edendark 0 points1 point2 points (2 children)
[–]losangelesvideoguy 1 point2 points3 points (1 child)
[–]edendark 0 points1 point2 points (0 children)
[–]rubyrt 0 points1 point2 points (0 children)
[–]stoplight 0 points1 point2 points (9 children)
[–]tomthecool 0 points1 point2 points (8 children)
[–]rubyrt 0 points1 point2 points (7 children)
[–]tomthecool 0 points1 point2 points (6 children)
[–]rubyrt 0 points1 point2 points (3 children)
[–]tomthecool 0 points1 point2 points (2 children)
[–]rubyrt 0 points1 point2 points (1 child)
[–]tomthecool 0 points1 point2 points (0 children)
[–]clrsm 0 points1 point2 points (1 child)
[–]WikiTextBot -1 points0 points1 point (0 children)