Implementation question about classic n-Queens in Java
This is a homework question. I am writing a solution for classic n-Queens
problem in Java. My program l开发者_JS百科ooks 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 ?
There exist several standard classes that implement the Set
interface. You could use a TreeSet
and provide your own comparator.
Why not Set<List<Integer>>
?
I can write a wrapper class QueensPlacements, which holds an array and overrides hashCode with Arrays.deepHashCode, and return Set. However it seems verbose and inelegant.
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).
精彩评论