如何在代码中以编程方式创建有效的 15 谜题
我已经用 JS 构建了 15 个谜题,但我的随机谜题生成正在创建无法解决的谜题的实例。这可能是因为我不是计算机科学的负责人,但我不确定如何计算代码中排列中的反转数量之类的问题。我想知道如何编写我的代码,以便我可以测试我的谜题的任何给定开始状态是否都是可解决的。我在已发布的应用程序中看到了其他 15 个无法解决的谜题,所以看来我并不是唯一一个遇到这个问题的人。
我已经看过这篇文章,但它仅限于 CS 级别,我正在寻找一个代码实现来帮助我更好地理解这一点: 15 Puzzle Heuristic
我正在使用 JS,但无论哪种语言的任何帮助和解释都会有很大帮助。
I've built a 15 puzzle in JS but my random puzzle generation is creating instances of an unsolvable puzzle. This could be because I'm not a Computer Science head, but I'm not sure how to work out things like calculate the number of inversions in a permutation in code. I'm wondering how to write my code so that I can test that any given start state of my puzzle is solvable. I've seen other 15 puzzles in published apps out there that are unsolvable, so it seems I'm not the only one out there with my problem.
I've seen this post, but it stops at the CS level and I'm looking for a code implementation that would help me understand this a little better:
15 Puzzle Heuristic
I'm using JS, but any help and explanation from whichever language would be a great help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可解性算法基于反演奇偶校验,并在15 Puzzle - Wolfram Math World中进行了解释转换成代码应该不会太困难。 IIRC 在不可解的起点上交换两个相邻的方块使其可解,但您需要确认这一点。
请注意,这是确定谜题是否可以解决的精确算法,而不是用于指导解决方案中的步骤顺序的启发式算法。
The algorithm for solvability is based on the parity of inversion and explained in 15 Puzzle - Wolfram Math World It should not be too difficult to convert into code. IIRC swapping two adjacent squares on a non-solvable starting point makes it solvable, but you will need to confirm that.
Note that this is an exact algorithm determining whether or not a puzzle can be solved, not a heuristic for guiding the sequence of steps in the solution.
我在评论中回避的内容,但不确定这是否是正确的方法:
因为你从一个有效的棋盘开始,然后应用一组强制的错误方向,所以你总是会得到一个完全合法的开始游戏。
What I was eluding to in a comment, but wasn't sure if it the right approach:
Since you're starting with a valid board, then applying a set of forced mis-directions, you'll always end up a completely legitimate start game.