LoginSignup
1
1

More than 5 years have passed since last update.

ある整数の各桁ごとに四則演算した結果を全パターン求める

Posted at
class Integer
    def operations
        os = operators_series
        ns = self.to_s.each_char.map{|i| i.to_f}
        os.inject([]) {|r, e| r << ns.zip(e).flatten.compact.join}
    end

    private
    def operators_series
        length = self.to_s.length
        return self if length < 2
        operators = %w(+ - * /)
        length = self.to_s.length
        (length - 2).times
            .inject(operators) {|r, i| r.product(operators)}
            .flatten(length - 2)
            .each_slice(length - 1)
            .to_a
    end
end

# 小町算
20140112.operations.
    reject{|e| eval(e).infinite? || eval(e).nan?}.
    select{|e| eval(e) == 10.0}.
    each{|e| p e + " = " + eval(e).to_s}

# =>
"2.0+0.0+1.0+4.0+0.0+1.0+1.0*2.0 = 10.0"
"2.0+0.0+1.0+4.0+0.0+1.0*1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0+0.0+1.0/1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0+0.0*1.0+1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0+0.0/1.0+1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0-0.0+1.0+1.0*2.0 = 10.0"
"2.0+0.0+1.0+4.0-0.0+1.0*1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0-0.0+1.0/1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0-0.0*1.0+1.0+2.0 = 10.0"
"2.0+0.0+1.0+4.0-0.0/1.0+1.0+2.0 = 10.0"
"2.0+0.0+1.0*4.0+0.0+1.0+1.0+2.0 = 10.0"
"2.0+0.0+1.0*4.0-0.0+1.0+1.0+2.0 = 10.0"
"2.0+0.0*1.0+4.0+0.0+1.0+1.0+2.0 = 10.0"
"2.0+0.0*1.0+4.0-0.0+1.0+1.0+2.0 = 10.0"
"2.0+0.0/1.0+4.0+0.0+1.0+1.0+2.0 = 10.0"
"2.0+0.0/1.0+4.0-0.0+1.0+1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0+0.0+1.0+1.0*2.0 = 10.0"
"2.0-0.0+1.0+4.0+0.0+1.0*1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0+0.0+1.0/1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0+0.0*1.0+1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0+0.0/1.0+1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0-0.0+1.0+1.0*2.0 = 10.0"
"2.0-0.0+1.0+4.0-0.0+1.0*1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0-0.0+1.0/1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0-0.0*1.0+1.0+2.0 = 10.0"
"2.0-0.0+1.0+4.0-0.0/1.0+1.0+2.0 = 10.0"
"2.0-0.0+1.0*4.0+0.0+1.0+1.0+2.0 = 10.0"
"2.0-0.0+1.0*4.0-0.0+1.0+1.0+2.0 = 10.0"
"2.0-0.0*1.0+4.0+0.0+1.0+1.0+2.0 = 10.0"
"2.0-0.0*1.0+4.0-0.0+1.0+1.0+2.0 = 10.0"
"2.0-0.0/1.0+4.0+0.0+1.0+1.0+2.0 = 10.0"
"2.0-0.0/1.0+4.0-0.0+1.0+1.0+2.0 = 10.0"


1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1