I’m trying to write a little ship battle game in java.
It is 100% academic, I made it to practice recursion, so… I want to use it instead of iteration, even if it’s simpler and more efficient in most some cases.
Let’s get down to business. These are the rules:
- Ships are 1, 2 or 3 cells wide and are placed horizontally only.
- Water is represented with 0, non-hit ship cells are 1, hit ship cells are 2 and sunken ships have all it’s cells in 3.
With those rules set, I’m using the following array for testing:
int[][] board = new int[][]
{
{0, 1, 2, 0, 1, 0},
{0, 0, 1, 1, 1, 0},
{0, 3, 0, 0, 0, 0},
{0, 0, 2, 1, 2, 0},
{0, 0, 0, 1, 1, 1},
};
It works pretty good so far, and to make it more user-friendly I would like to add a couple of reports. these are the methods I need for them:
- Given the matrix, return the amount of ships in it.
- Same as a), but separating them by state (amount of non-hit ships, hit and sunken ones).
I will need a hand with those reports, and I would like to get some ideas.
Remember it must be done using recursion, I want to understand this, and the only way to go is practice!
Thanks a lot for your time and patience :).
It’s not possible, unless you specify that ships must be separated by a
0. Otherwise,1,1could be a ship of length 2, or two ships of length 1.Given that restraint, both of your reports could/should be done as a single process which turns a map into a list of ships.
I don’t terribly feel like writing out the recursive wrappers (I assume you know how to do “iterate” over an array using a recursive function), so I’m skipping that part.
It may or may not be better to use a single function that isn’t hard-coded, but that seems a tad more difficult, and with only three options, hardcoding isn’t too much code-overhead (since all three do work somewhat differently).
Alternatively, you could use an entirely separate method, where by you iterate across the map counting “rising edges” of ships. This is a much lighter-weigh solution, but doesn’t afford you anywhere near as much flexibility in what you can do with the resulting data.
… By lighter weight, I mean “could be done using regex”