class TateYoko attr_reader :count def initialize(num = 3) @num = num @matrix = Array.new(num+1){Array.new(num+1)} @all_nums = (1..num).to_a @count = 0 end def calc(depth = 0) line = depth / @num + 1 column = depth % @num + 1 return if line > @num used_nums = @matrix[line][0, column] + @matrix.transpose[column][0, line] nums = @all_nums - used_nums nums.each do |n| @matrix[line][column] = n calc(depth + 1) if depth == @num**2 - 1 @count += 1 show_matrix end end end def show_matrix @matrix[1..-1].each {|line| puts line[1..-1].join } puts end end tate_yoko = TateYoko.new(3) tate_yoko.calc print 'total = ', tate_yoko.count