Skip to content

Instantly share code, notes, and snippets.

@gabrieljoelc
Last active August 20, 2017 04:22
Show Gist options
  • Save gabrieljoelc/836bdaa34d3e3dd61a72e02bde46d841 to your computer and use it in GitHub Desktop.
Save gabrieljoelc/836bdaa34d3e3dd61a72e02bde46d841 to your computer and use it in GitHub Desktop.
class Array
def first
self[0]
end
def last
self[self.size - 1]
end
def distinct
source = self
target = []
dups = Set.new
source.each do |source_elem|
target.push(source_elem) unless dups.add?(source_elem).nil?
end
target
end
end
class DistinctifierTest
attr_reader :sample, :actual, :method
def initialize(sample, method = :distinct)
@sample = sample
@method = method
end
def act
@actual = sample.send(method)
end
def assert
actual == sample.uniq
end
def run
act
if assert
puts 'Assert success!'
else
puts "Assert failed. Sample: #{sample}. Actual: #{actual}"
end
self
end
end
require 'benchmark'
class DistinctifierTestRunner
attr_reader :method
def initialize(method = :distinct)
@method = method
end
def run(*samples)
samples.each do |sample|
DistinctifierTest.new(sample, method).run
end
end
def run_with_benchmark(*samples)
Benchmark.bm(7) do |benchmark|
samples.each do |sample|
benchmark.report do
DistinctifierTest.new(sample, method).run
end
end
end
end
def self.run(*samples)
new.run(*samples)
end
end
#DistinctifierTestRunner.run(%w[a b c], %w[b a c c e d d])
require 'faker'
class EmailSampleGenerator
attr_reader :count, :rand_range, :email_factory, :emails, :half_count
def initialize(count: 4, rand_range: 1..2, email_factory: Faker::Internet)
@count = count
@rand_range = rand_range
@email_factory = email_factory
@emails = []
@half_count = (count.to_f / 2).to_i
end
def gen
@emails = []
half_count.times do
emails.push email_factory.email
end
half_count.times do
emails.insert(rand_array_location, emails[rand_array_location])
end
emails
end
private
def duplicate_count
rand(rand_range)
end
def rand_array_location
loc = rand(0...emails.size)
return 0 if loc.nil?
loc
end
end
email_source = EmailSampleGenerator.new.gen
puts "\nsource:"
print email_source
puts "\nactual:"
print email_source.distinct
puts "\n"
#DistinctifierTestRunner.run(email_source)
DistinctifierTestRunner.new(:uniq).run_with_benchmark(EmailSampleGenerator.new(count: 10000).gen)
#DistinctifierTestRunner.new(:distinct3).run_with_benchmark(EmailSampleGenerator.new(count: 10000).gen)
DistinctifierTestRunner.new(:distinct4).run_with_benchmark(EmailSampleGenerator.new(count: 10000).gen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment