Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package crossnum;
- import java.util.List;
- import java.util.stream.Collectors;
- /**
- * Represents a square grid with each cell containing a digit or blank.
- *
- * @author dub_nerd
- *
- */
- public class Board {
- /**
- * Each grid entry is represented as a 'Variable'. We store them in a flat
- * list -- see the get(row,col) method to see how they are accessed as a
- * grid.
- */
- private final List<Variable> variables;
- /**
- * Length of a side of the grid, i.e. the square root of the number of
- * entries.
- */
- private final int side;
- /**
- * Constructor for the Board class. For convenience of representation, it is
- * initialised from a character String representing the cells of the grid in
- * order. The string must have a perfect square number of characters.
- *
- * @param s
- * input String.
- */
- Board(String s) {
- // Ensure grid is square
- side = (int) Math.sqrt(s.length());
- if (s.length() != (side * side)) {
- throw new RuntimeException("Board not square");
- }
- /*
- * Map the input characters to Variables. Each Variable gets the
- * character's digit value, or zero if blank.
- */
- variables = s.chars()
- .mapToObj(c -> new Variable(c == ' ' ? 0 : c - '0'))
- .collect(Collectors.toList());
- }
- /**
- * Get the Variable at the specified row and column.
- * @param row the row
- * @param col the column
- * @return the Variable at the specified row and column.
- */
- Variable get(int row, int col) {
- int index = row * getSide() + col;
- return variables.get(index);
- }
- /**
- * Get the length of the board's side, i.e the square root of the
- * number of cells.
- * @return length of side.
- */
- public int getSide() {
- return side;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement