【发布时间】:2011-02-20 12:36:48
【问题描述】:
我不确定这是否是正确的去处,也许是其他一些 stackexchange,告诉我我会在其他地方发布。
这是我的问题,我在朋友家发现了一个老游戏,应该是一个智力游戏:9张小方块卡,你必须把它们放在一起,让它们全部融合在一起,这是一张图片:
在游戏前几个小时后,我发现没有真正简单公平的方式来完成游戏,所以我采用了编程方式。
这是我遇到困难的地方,虽然我可以使用一些随机函数,一个大循环,然后完成它。但是有类似 (4*9)^9 的解决方案,所以看起来并不容易。
这是我写的代码,暂时没用: 每次我进入循环时,我都会洗牌,随机旋转我的卡片并检查拼图是否正确,浪费了很多循环,但我不知道从哪里开始让它更有效率。
编辑: 固定代码,我得到了一些 8 张牌的牌组,但没有 9 牌牌组,如果有人对我的代码进行了修复,或者没有解决方案?
require 'json'
class Array
def rotate n
a =dup
n.times do a << a.shift end
a
end
end
@grid = [[{"type"=>"p", "head" => 1},{"type"=>"c", "head" => 1},{"type"=>"a", "head" => 2},{"type"=>"o", "head" => 2}],
[{"type"=>"o", "head" => 1},{"type"=>"a", "head" => 2},{"type"=>"c", "head" => 2},{"type"=>"p", "head" => 1}],
[{"type"=>"c", "head" => 1},{"type"=>"p", "head" => 2},{"type"=>"o", "head" => 2},{"type"=>"a", "head" => 1}],
[{"type"=>"p", "head" => 1},{"type"=>"c", "head" => 2},{"type"=>"o", "head" => 2},{"type"=>"a", "head" => 1}],
[{"type"=>"p", "head" => 2},{"type"=>"c", "head" => 2},{"type"=>"a", "head" => 1},{"type"=>"c", "head" => 1}],
[{"type"=>"a", "head" => 1},{"type"=>"p", "head" => 2},{"type"=>"o", "head" => 2},{"type"=>"p", "head" => 1}],
[{"type"=>"a", "head" => 1},{"type"=>"o", "head" => 1},{"type"=>"a", "head" => 2},{"type"=>"c", "head" => 2}],
[{"type"=>"o", "head" => 1},{"type"=>"a", "head" => 2},{"type"=>"c", "head" => 2},{"type"=>"p", "head" => 1}],
[{"type"=>"p", "head" => 1},{"type"=>"c", "head" => 2},{"type"=>"o", "head" => 2},{"type"=>"a", "head" => 1}]]
@new_grid = [nil, nil, nil,nil, nil, nil,nil, nil, nil]
@used = [false, false, false,false, false, false,false, false, false]
def check_validity(card, position, orientation)
# since I'm adding from top left to bottom, I only need to check top and left
try_card = @grid[card].rotate orientation
valid = true
# top
if (@new_grid[position-3])
if (try_card[0]["type"] != @new_grid[position-3][2]["type"] || try_card[0]["head"] == @new_grid[position-3][2]["head"])
valid = false
end
end
# left
if (@new_grid[position-1] && (position % 3) != 0)
if (try_card[3]["type"] != @new_grid[position-1][1]["type"] || try_card[3]["head"] == @new_grid[position-1][1]["head"])
valid = false
end
end
return valid
end
def solve_puzzle(position)
(0..8).each do |card|
unless (@used[card])
(0..3).each do |orientation|
if (check_validity(card, position, orientation))
@used[card] = true
@new_grid[position] = @grid[card].rotate orientation
if position == 7
puts @new_grid.to_json
end
if (position < 8)
solve_puzzle(position + 1)
else
puts "I WON"
puts @new_grid.to_json
end
@new_grid[position] = nil
@used[card] = false
end
end
end
end
end
solve_puzzle(0)
【问题讨论】:
-
没有解决办法。我总是以遗漏卡片 3 或卡片 8 结束。他们要么需要先红后下(顺时针)、绿/蓝上加红底、绿/蓝上加黄底、红底后红顶或绿/蓝底后红底。
-
好吧,所有这些想法都是为了一个没有解决方案的游戏,真可惜;)至少我学到了很多!谢谢