这是一个家庭作业问题。我正在用 Java 编写经典 n-Queens
问题的解决方案。我的程序看起来像 this 但它返回所有合法的集合皇后位置而不是打印出来。我将皇后放置表示为 int[]
并使用 HashSet
返回 Set
作为其实现。 (Set
在这里是合适的,因为放置的顺序并不重要)。
问题是 Java 数组不会覆盖 hashCode
并且具有相同值的不同数组实例具有不同的哈希码。
我可以编写一个包装类 QueensPlacements
,它保存一个数组并使用 Arrays.deepHashCode
覆盖 hashCode
,并返回 Set;
。但它看起来冗长且不优雅。有人能建议更好的解决方案吗?
This is a homework question. I am writing a solution for classic n-Queens
problem in Java. My program looks like this but it returns a collection of all legal queens placements instead of printing them out. I represent queens placement as int[]
and return Set<int[]>
using HashSet<int[]>
as it's implementation. (Set
is appropriate here since the order of the placements is not important).
The problem is that Java arrays do not override hashCode
and different array instances with the same values have the different hash codes.
I can write a wrapper class QueensPlacements
, which holds an array and overrides hashCode
with Arrays.deepHashCode
, and return Set<QueensPlacement>
. However it seems verbose and inelegant. Can anybody suggest any better solution ?
发布评论
评论(3)
存在多个实现 Set 接口的标准类。您可以使用
TreeSet
< /a> 并提供您自己的比较器。There exist several standard classes that implement the
Set
interface. You could use aTreeSet
and provide your own comparator.为什么不
Set
?>
Why not
Set<List<Integer>>
?创建自定义类可能不是一个坏主意。听起来您担心您只是创建一个包装类来传递数据,但是您确定它没有其他方法可以提供以使其成为解决方案域的成熟部分吗?接收放置集的代码用它做什么?放置是否可以提供一些方法来促进接收代码的工作?一个不错的 toString() 方法至少可以用于调试?
*编辑:*
还要考虑 QueensPlacement 可以提供一个 Comparator 来实现展示位置之间的一致排序,这对于概念问题来说并不是绝对必要的(对计算机来说无关紧要),但是可能会使 UI 更好一些(例如,如果以相同的顺序显示等效的展示位置集,对用户来说不是更好吗)。
Creating a custom class may not be a bad idea. Its sounds like you fear you are simply creating a wrapper class to just pass data, but are you sure there aren't other methods it could provide to make it a full-fledged part of the solution domain? What does the code receiving the placement set do with it? Are there methods that placement could provide to facilitate things for that receiving code? A nice toString() method for at least debugging?
*Edit: *
Consider too that QueensPlacement could provide a
Comparator<QueensPlacement>
for consistent ordering among placements, which isn't strictly necessary for the conceptual problem (it doesn't matter to the computer), but might make the UI a little nicer (e.g. wouldn't it be nicer for the user if equivalent sets of placements were displayed in the same order).