Last active
August 29, 2015 13:57
-
-
Save justuseapen/9392105 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
#CHALLENGE: | |
#Please write a paragraph explaining what it does and how it works. Then, rewrite it so that it's | |
#beautiful and elegant and the intent is clear. Feel free to use any references or tools you would | |
#normally use. | |
def function(a) | |
a.inject({}){ |a,b| a[b] = a[b].to_i + 1; a}.reject{ |a,b| b == 1 }.keys | |
end | |
puts "Original method:" | |
puts function([0, 1, 1, 2, 2, 3]) | |
#Upon second look (and a nudge in the right direction from Robert) | |
#the code appears to return any elements that appear more than once. | |
#The inject block returns a hash with each element and the corresponding | |
#number of times that the element appears in the array. | |
#The reject block returns any element that has a value of more than one | |
#This is how I would do it: | |
def duplicated_elements_in(array) | |
array.select{ |element| array.count(element) > 1 }.uniq | |
end | |
#Despite the increased expressiveness, this method is shorter | |
puts"New method:" | |
puts duplicated_elements_in([4,8,8,15,23,42,42,42]) | |
puts "Let's benchmark the methods for performance:" | |
array = [0, 1, 1, 2, 2, 3] | |
Benchmark.bmbm(7) do |bm| | |
bm.report('old method') do | |
function(array) | |
end | |
bm.report('new method') do | |
duplicated_elements_in(array) | |
end | |
end | |
#And my version is (slightly) faster. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment