LoginSignup
4
5

More than 5 years have passed since last update.

"これが解けたらIQ150"みたいな計算問題のruby実装

Last updated at Posted at 2015-11-23

ちょっと前に流行った"これが解けたらIQ150"みたいな計算問題

http://matome.naver.jp/odai/2137952246025001301
5 + 3 = 28
6 + 4 = 210

これらは、左辺の通常の足し算”+”の結果とは異なる処理結果が、右辺となる等式。

  • ↑の”通常「+」と異なる処理”という点は、演算子オーバーライドっぽい
  • ruby2.1のrefinementってどうやってかくんだっけ

という内容のメモを下記します。

引いたのと足したのを文字列結合するあれ

6 + 4 = 210
9 + 2 = 711
8 + 5 = 313
5 + 2 = 37
7 + 6 = 113

「+」演算子のオーバーライドをやるんだけど、なぜかしらんが、ruby2.1 からのrefinementsでないとできんかった。

minus_plus.rb
# ruby2.1 のrefinementsを使うFixnum拡張
module FixnumExtensions
  refine ::Fixnum do
    alias_method(:orig_plus, :+)
    def +(n)
      "#{self - n}#{self.orig_plus(n)}".to_i
    end
  end
end

[[6, 4],
 [9, 2],
 [8, 5],
 [5, 2],
 [7, 6]].each do |a, b|
  using FixnumExtensions
  puts "#{a} + #{b} = #{a + b}"
end

数字の○の数を数えるパターン

小学生向けの子供番組等で頻出すると思われるクイズ

8 + 8 = 4
1 + 0 = 1
5 + 5 = 0
66 + 99 = 4
333 + 222 = 0

数字の見た目に含まれる「丸」の数を数えるという仕様。

maru.rb
module FixnumExtensions
  def maru_count(num_str)
    case num_str
    when '8' then return 2
    when /^[069]$/ then return 1
    end
    0
  end

  module_function :maru_count

  refine ::Fixnum do
    alias :orig_plus :+

    def to_maru_count
      self.to_s.each_char.map{|n| FixnumExtensions.maru_count(n)}.inject(:+)
    end

    def +(other)
      self.to_maru_count.orig_plus(other.to_maru_count)
    end
  end
end

module Maru
  using FixnumExtensions

  module_function
  def process

    [
     [8, 8],
     [1, 0],
     [5, 5],
     [66, 99],
     [333, 222],
     [0, 0],
     [2, 3],
     [9, 9],
     [8, 36],
     [8, 0],
     [22, 347],
     [80, 123],
    ].each do |a, b|
      puts "#{a} + #{b} = #{a + b}"
    end

  end
end

if __FILE__ == $0
  Maru::process
end
4
5
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
4
5