java - Recursion - Ship Battle -
i'm trying write little ship battle game in java.
it 100% academic, made practice recursion, so... want use instead of iteration, if it's simpler , more efficient in most cases.
let's down business. these rules:
- ships 1, 2 or 3 cells wide , placed horizontally only.
- water represented 0, non-hit ship cells 1, hit ship cells 2 , sunken ships have it's cells in 3.
with rules set, i'm using following array 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 far, , make more user-friendly add couple of reports. these methods need them:
- given matrix, return amount of ships in it.
- same a), separating them state (amount of non-hit ships, hit , sunken ones).
i need hand reports, , ideas.
remember must done using recursion, want understand this, , way go practice!
thanks lot time , patience :).
it's not possible, unless specify ships must separated 0. otherwise, 1,1 ship of length 2, or 2 ships of length 1.
given restraint, both of reports could/should done single process turns map list of ships.
i don't terribly feel writing out recursive wrappers (i assume know how "iterate" on array using recursive function), i'm skipping part.
- loop on rows, because ships cannot span rows, can treated independently.
- for each state-class ship data can in (no ship, ship, sunk ship), have function
- this function checks if next element
- doesn't exist
- is same current 1 (can hardcoded different functions)
- is different current 1 (go right one).
- as traverse array, assemble list of ships.
- you have list of ships, can count length of, or more complicated reports on
it may or may not better use single function isn't hard-coded, seems tad more difficult, , 3 options, hardcoding isn't code-overhead (since 3 work differently).
alternatively, use entirely separate method, iterate across map counting "rising edges" of ships. lighter-weigh solution, doesn't afford anywhere near flexibility in can resulting data.
... lighter weight, mean "could done using regex"
Comments
Post a Comment