, !
, @stefan, , @BroiSatse, , .
class Array
def common_prefix_with(other)
other_size = other.size
take_while.with_index {|v,i| other_size > i && v == other[i] }
end
end
class Cars
def self.stefan(a1,a2)
a1[0...a2.size].zip(a2).take_while { |x, y| x == y }.map(&:first)
end
def self.broiSatse1(a1,a2)
a1.take_while.with_index {|v,i| a2.size > i && v == a2[i] }
end
def self.broiSatse2(a1,a2)
a1.common_prefix_with(a2)
end
def self.cary1(a,b)
a[0,b.size].take_while.with_index { |e,i| e == b[i] }
end
def self.cary2(a,b)
any, arr = a.zip(b).chunk { |e,f| e==f }.first
any ? arr.map(&:first) : []
end
def self.cary3(a,b)
a[0,(0..[a.size, b.size].min).max_by { |n| (a[0,n]==b[0,n]) ? n : -1 }]
end
end
, @6ftDan ( 5 'Dan 7' Dan), .
random_arrays(n) . n - . n+1.
def random_arrays(n)
m = rand(n)
a = Array.new(m,0)
b = Array.new(m,0)
if m < n
a << 0
b << 1
(n-m-1).times { a << rand(2); b << rand(2) } if m < n - 1
end
(rand(2) == 0) ? a << 0 : b << 0
[a,b]
end
N = 10000
methods = Cars.methods(false)
20.times do |i|
test = case i
when 0 then [[0,1],[1,1]]
when 1 then [[0],[]]
when 1 then [[0,0,0],[0,0]]
else
random_arrays(N)
end
soln = Cars.send(methods.first, *test)
methods[1..-1].each do |m|
unless soln == Cars.send(m, *test)
puts "#{m} has incorrect solution for #{test}"
exit
end
end
end
puts "All methods yield the same answers\n"
require 'benchmark'
I = 1000
@arr = I.times.with_object([]) { |_,a| a << random_arrays(N) }
def testit(m)
I.times { |i| Cars.send(m, *@arr[i]) }
end
Benchmark.bm(12) { |bm| methods.each { |m| bm.report(m) { testit(m) } } end
All methods yield the same answers
user system total real
stefan 11.260000 0.050000 11.310000 ( 11.351626)
broiSatse1 0.860000 0.000000 0.860000 ( 0.872256)
broiSatse2 0.720000 0.010000 0.730000 ( 0.717797)
cary1 0.680000 0.000000 0.680000 ( 0.684847)
cary2 13.130000 0.040000 13.170000 ( 13.215581)
cary3 51.840000 0.120000 51.960000 ( 52.188477)