小町算

30分プログラム、その118。小町算をevalのあるRubyでリベンジ。

やっぱりevalがあると楽ですね。

使い方

$ ruby komachi.rb
12.0+34.0+5.0*6.0+7.0+8.0+9.0
1.0+23.0-4.0+56.0+7.0+8.0+9.0
1.0/2.0/3.0*456.0+7.0+8.0+9.0
1.0*2.0+34.0+5.0+6.0*7.0+8.0+9.0
12.0+34.0-5.0+6.0*7.0+8.0+9.0
1.0-2.0-3.0+45.0+6.0*7.0+8.0+9.0
1.0+2.0*3.0+4.0+5.0+67.0+8.0+9.0
12.0+3.0-4.0+5.0+67.0+8.0+9.0
1.0-2.0+3.0*4.0+5.0+67.0+8.0+9.0
1.0-2.0-3.0+4.0*5.0+67.0+8.0+9.0

でも、

$ ruby komachi.rb | bc | grep -v 100.0
24.0
79.0
99.0
83.0

となる不思議。

ソースコード

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# komachi.rb -
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki <hiroki1124@gmail.com> 
# http://mzp.sakura.ne.jp/
#
# Timestamp: 2007/08/28 20:36:41
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Ruby itself.
#

def make_exp(x,*xs)
  if xs.empty? then
    x.to_f.to_s
  else
    make_exp(*xs).map{|y|
      ["#{x}.0+#{y}",
       "#{x}.0-#{y}",
       "#{x}.0*#{y}",
       "#{x}.0/#{y}",
       "#{x}#{y}"]
    }.flatten
  end
end

make_exp(*(1..9).to_a).map{|xs|
  if eval(xs) == 100 then
    puts xs
  end
}

参考