Skip to content

Instantly share code, notes, and snippets.

@nalabjp
Last active December 23, 2016 11:20
Show Gist options
  • Save nalabjp/4ef9a6313e122a2dfd6a631b3b9a62b2 to your computer and use it in GitHub Desktop.
Save nalabjp/4ef9a6313e122a2dfd6a631b3b9a62b2 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
module Cond
OPS = ['*',''].freeze
RANGE = (1000..10000).freeze
end
class Proc0
def self.run(num, ops, ret)
# @note Synonymous with the following implementation, but maybe slow
# `return if ops.join.length.zero?`
return if ops[0].empty? && ops[1].empty? && ops[2].empty?
n = num.to_s
# @note Synonymous with the following implementation, but maybe slow
# `exp = n.chars.reverse.zip(ops).join`
exp = "#{n[3]}#{ops[0]}#{n[2]}#{ops[1]}#{n[1]}#{ops[2]}#{n[0]}"
return if exp =~ /0\d/
res = eval(exp)
ret << n.reverse if num == res
end
end
class Case1
def self.run
Array(Cond::RANGE).product(*Array.new(3, Cond::OPS)).each.with_object([]) do |(num, *ops), ret|
Proc0.run(num, ops, ret)
end
end
end
class Case2
def self.run
ops_combi = Cond::OPS.repeated_combination(3).to_a
Cond::RANGE.each.with_object([]) do |num, ret|
ops_combi.each do |ops|
Proc0.run(num, ops, ret)
end
end
end
end
# run debug
if ARGV.first
r1 = Case1.run
r2 = Case2.run
puts "Case1: #{r1.inspect}"
puts "Case2: #{r2.inspect}"
if r1 == r2
puts 'Valid'
else
raise 'Invalid'
end
end
puts 'Run benchmark'
Benchmark.ips do |x|
x.config(time: 60)
x.report('Case1') { Case1.run }
x.report('Case2') { Case2.run }
x.compare!
end
@nalabjp
Copy link
Author

nalabjp commented Dec 23, 2016

revision1

 ruby q2.rb
Run benchmark
Warming up --------------------------------------
               Case1     1.000  i/100ms
               Case2     1.000  i/100ms
Calculating -------------------------------------
               Case1      0.102  (± 0.0%) i/s -      7.000  in  68.752711s
               Case2      0.438  (± 0.0%) i/s -     27.000  in  61.974265s

Comparison:
               Case2:        0.4 i/s
               Case1:        0.1 i/s - 4.29x  slower

@nalabjp
Copy link
Author

nalabjp commented Dec 23, 2016

問題をちゃんと読んでからやってみると、どうも四則演算は全てやる必要がなさそうなことに気づく。
まぁ答えを知ってしまっているからかもしれないが。

ってことで、revision2の結果がこれ。

 ruby q2.rb
Run benchmark
Warming up --------------------------------------
               Case1     1.000  i/100ms
               Case2     1.000  i/100ms
Calculating -------------------------------------
               Case1      2.266  (± 0.0%) i/s -    136.000  in  60.152929s
               Case2      5.720  (± 0.0%) i/s -    342.000  in  60.039457s

Comparison:
               Case2:        5.7 i/s
               Case1:        2.3 i/s - 2.52x  slower

まぁそれでも2.5倍ぐらい差があるのか。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment