ruby - How to find duplicates in array without using `uniq` method -
i doing challenge make method finds duplicate values in array, , prints out new array without duplicates. ruby has built in uniq
method; however, not allowed use it.
in mind, should work:
def uniques(array) temppos = 0 arraypos = 0 duplicate = true result = [] # array result "pushed" arraypos in 0..array.length temppos in 0..array.length # if values @ indexes same. indexes not same. # have duplicate if array[arraypos] == array[temppos] && arraypos != temppos duplicate = true else duplicate = false end if duplicate == false result[arraypos] = array[arraypos] end end puts duplicate end puts result.inspect end
output:
uniq *this short hand user input run method* false false false false false false [1, 2, 1, 4, 5, nil]
i must doing wrong.
your logic works fine altough mentioned above set
work better. sort elements, , find adjacent pairs same value wouldn't work set
, have better run-time current solution:
to polish have:
def uniques(array) result = [] # array result "pushed" arraypos in 0...array.length duplicate = false temppos in 0...result.length # if values @ indexes same... indexes not same... # have duplicate duplicate ||= (array[arraypos] == result[temppos]) end if !duplicate result << array[arraypos] end end puts result end
an better approach (altought still poor performance):
def uniques(array) result = [] # array result "pushed" arraypos in 0...array.length duplicate = result.include?(array[arraypos]) if !duplicate result << array[arraypos] end end puts result end
although solution ok learning assignment, should note complexity of o(n^2)
(n-squared). means array of size n
(for example n=10
), doing n-squared (100) iterations.
it gets exponentially worse. if have array of length 1,000,000, doing 1,000,000,000,000 iterations. why using set
important, it's average run-time lower.
Comments
Post a Comment