Created
February 9, 2014 12:13
-
-
Save abinoam/8898249 to your computer and use it in GitHub Desktop.
In response to https://www.ruby-forum.com/topic/4422661
This file contains hidden or 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
#!/usr/bin/env ruby | |
#coding: utf-8 | |
def del_first_three_original_1(a) | |
num_to_del = a.find { |e| a.count(e) >= 3 } | |
return a if num_to_del.nil? | |
3.times do | |
ind = a.index { |e| e == num_to_del } | |
a.delete_at(ind) | |
end | |
a | |
end | |
def del_first_three_original_2(a) | |
num_to_del = a.find { |e| a.count(e) >= 3 } | |
return a if num_to_del.nil? | |
3.times do | |
ind = a.index { |e| e == num_to_del } | |
a.tap { |ob| ob.delete_at(ind) } | |
end | |
end | |
def del_first_three_refactored(ary) | |
el_indices = Hash.new { |hash, key| hash[key] = Array.new } | |
ary.each_with_index do |el, ix| | |
el_indices[el].push ix | |
if el_indices[el].size >= 3 | |
el_indices[el].each_with_index do |del_ix, offset| | |
ary.delete_at(del_ix - offset) | |
end | |
break ary | |
end | |
end | |
end | |
ary = Array.new | |
3.times { ary.push 0 } | |
(1..100_000_000).each { |n| ary.push n } | |
ary_original_1 = ary.dup | |
ary_original_2 = ary.dup | |
ary_refactored = ary.dup | |
t1 = Time.now | |
del_first_three_original_1(ary_original_1) | |
t2 = Time.now | |
puts "Original (1) lasted #{t2-t1} seconds" | |
t1 = Time.now | |
del_first_three_original_2(ary_original_2) | |
t2 = Time.now | |
puts "Original (2) lasted #{t2-t1} seconds" | |
t1 = Time.now | |
del_first_three_refactored(ary_refactored) | |
t2 = Time.now | |
puts "Refactored lasted #{t2-t1} seconds" | |
puts "Results are correct" if ary_original_1 == ary_original_2 and ary_original_2 == ary_refactored | |
puts RUBY_DESCRIPTION |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment