Last active
December 23, 2016 11:20
-
-
Save nalabjp/4ef9a6313e122a2dfd6a631b3b9a62b2 to your computer and use it in GitHub Desktop.
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 '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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
問題をちゃんと読んでからやってみると、どうも四則演算は全てやる必要がなさそうなことに気づく。
まぁ答えを知ってしまっているからかもしれないが。
ってことで、revision2の結果がこれ。
まぁそれでも2.5倍ぐらい差があるのか。