Thursday, February 6, 2014

More Code Puzzles for Ruby...


(from Interview cake)

Given and array of Numbers 1 to n (1..n) . Assume all the numbers in the array are unique, except for one number which occurs twice. Write a method to return the non-unique number.





        We start this one off by declaring a method which takes and array as an argument. The first step in our method is to declare an empty hash. My strategy here is assign each number from our array as a key in the hash and store the number of times our number occurs in the array as the corresponding value. We'll then check the values in the hash and if any value is greater than 1, we'll know that corresponding key occurred more than once in our array and should be returned as our non-unique number. Viola! If you've got an alternative solution, please post it bellow! 

    No comments:

    Post a Comment