Created
February 16, 2022 22:59
-
-
Save rlogwood/09b85ae40a1c32876504f27dd54db394 to your computer and use it in GitHub Desktop.
Find the odd int (see https://www.codewars.com/kata/54da5a58ea159efa38000836/solutions/ruby)
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
module BenchIt | |
require 'benchmark' | |
ITERATIONS = 100_000 | |
def self.run_benchmark_multi(methods, arg_arrays, iterations=ITERATIONS, verbose=false) | |
methods.each do |method| | |
puts "\n#{method} iterations:#{iterations}:\n" | |
Benchmark.bm do |x| | |
x.report do | |
iterations.times do |i| | |
arg_arrays.each do |args| | |
puts "Sending #{method.to_s}(#{args.to_s})" if verbose && i == 0 | |
send(method, *args) | |
end | |
end | |
end | |
end | |
end | |
end | |
end |
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
alt1 iterations:100000: | |
user system total real | |
5.470899 0.000000 5.470899 ( 5.471308) | |
alt2 iterations:100000: | |
user system total real | |
2.774857 0.000000 2.774857 ( 2.775203) | |
alt3 iterations:100000: | |
user system total real | |
2.761941 0.000000 2.761941 ( 2.762190) |
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
require 'securerandom' | |
require_relative './bench_it' | |
def solution(array_of_ints) | |
counts = {} | |
array_of_ints.each do |i| | |
counts[i] = counts.fetch(i, 0) + 1 | |
end | |
counts.each_pair { |k,v| return k if v.odd? } | |
nil | |
end | |
def alt1(seq) | |
seq.reduce(:^) | |
end | |
def alt2(seq) | |
seq.detect { |n| seq.count(n).odd? } | |
end | |
def alt3(seq) | |
seq.find{|c| seq.count(c).odd? } | |
end | |
def random_int_ara(size, max) | |
ara = [] | |
(1..size).each do | |
ara << SecureRandom.rand(max) | |
end | |
ara | |
end | |
test_data = [[[7]], [[0]] , [[1,1,2]], [[0,1,0,1,0]], [[1,2,2,3,3,3,4,3,3,3,2,2,1]]] | |
def basic_test | |
data.each do |ara| | |
puts "ara:#{ara} solution:#{solution(*ara)}" | |
puts "ara:#{ara} alt1:#{alt1(*ara)}" | |
end | |
end | |
benchmark_data = [ | |
[random_int_ara(1000, 100)], | |
[random_int_ara(1000, 100)], | |
[random_int_ara(1000, 100)] | |
] | |
BenchIt.run_benchmark_multi(%i[alt1 alt2 alt3], benchmark_data, 100_000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting !