4×4の魔方陣を全部リストする
http://livedoor.blogimg.jp/booq/imgs/d/c/dcdc7126.png
流石に(1..16).to_a.permutationでは無理だった
計算量について考えるのに良い問題かも
% wget -q -O - https://scrapbox.io/api/code/prog-exercises/4×4の魔方陣を全部リストする/mahou.rb | ruby
code:mahou.rb
all = (1..16).to_a
all.combination(4){ |a1|
next if a10+a11+a12+a13 != 34
(all - a1).combination(4){ |a2|
next if a20+a21+a22+a23 != 34
(all - a1 - a2).combination(4){ |a3|
next if a30+a31+a32+a33 != 34
a4 = all - a1 - a2 - a3
a1.permutation { |b1|
a2.permutation { |b2|
a3.permutation { |b3|
a4.permutation { |b4|
next if b10+b20+b30+b40 != 34
next if b11+b21+b31+b41 != 34
next if b12+b22+b32+b42 != 34
puts b1.join(' ')
puts b2.join(' ')
puts b3.join(' ')
puts b4.join(' ')
puts "---------------"
}
}
}
}
}
}
}
#パズル #魔方陣