user1022241
user1022241

Reputation:

Determine if there are conflicts in set

I have a Java HashMap containing 5 entries. Mapped to each entry is an object containing:

Think of the game battleship with a 10 x 10 board. The x / y coordinates in each entry corresponds to the top left corner of a ship on the board, and the length and orientation correspond, as one would expect, to the ships length and orientation from that point.

I'm trying to think of a way to rip through the 5 ships and check if there are any "overlapping ships", known as conflicts, on the board. I can't figure out how to do this. Any help would be much appreciated.

Upvotes: 0

Views: 80

Answers (1)

hvgotcodes
hvgotcodes

Reputation: 120268

One way to do it is:

1) assign each cell in your board a number, 1-100 (or 0-99).

2) Add a method to the things in your hashmap that returns a List of the unique cell ids that are covered. So if x == 1, y==1, length == 3, orientation == horizontal, you would return the three 1-100 values that represent the cell over which your submarine resides.

You will be able to calculate the first unique id by doing something like rowNumber*10 + columnNumber. You might have to tweak it depending on if you are 0 or 1 based, and or if your range is likewise 0 or 1 based..From there, if horizontal you just add 1 for each unit of length. Or you add 10 for each unique id if your piece is vertical.

3) Now you can have a collision detector class with a static method, that takes two pieces. It can call the method you created in step 2, get the two lists, and if there are any overlaps, you would find the same number in both lists.

I don't know if this is the best way to do it, but it is one way.

Upvotes: 1

Related Questions