Advertisement
Guest User

Board.java

a guest
Jul 30th, 2014
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. package crossnum;
  2.  
  3. import java.util.List;
  4. import java.util.stream.Collectors;
  5.  
  6. /**
  7.  * Represents a square grid with each cell containing a digit or blank.
  8.  *
  9.  * @author dub_nerd
  10.  *
  11.  */
  12. public class Board {
  13.  
  14.     /**
  15.      * Each grid entry is represented as a 'Variable'. We store them in a flat
  16.      * list -- see the get(row,col) method to see how they are accessed as a
  17.      * grid.
  18.      */
  19.     private final List<Variable> variables;
  20.    
  21.  
  22.     /**
  23.      * Length of a side of the grid, i.e. the square root of the number of
  24.      * entries.
  25.      */
  26.     private final int side;
  27.  
  28.    
  29.     /**
  30.      * Constructor for the Board class. For convenience of representation, it is
  31.      * initialised from a character String representing the cells of the grid in
  32.      * order. The string must have a perfect square number of characters.
  33.      *
  34.      * @param s
  35.      *            input String.
  36.      */
  37.     Board(String s) {
  38.        
  39.         // Ensure grid is square
  40.         side = (int) Math.sqrt(s.length());
  41.         if (s.length() != (side * side)) {
  42.             throw new RuntimeException("Board not square");
  43.         }
  44.        
  45.         /*
  46.          * Map the input characters to Variables. Each Variable gets the
  47.          * character's digit value, or zero if blank.
  48.          */
  49.         variables = s.chars()
  50.                 .mapToObj(c -> new Variable(c == ' ' ? 0 : c - '0'))
  51.                 .collect(Collectors.toList());
  52.        
  53.     }
  54.  
  55.  
  56.     /**
  57.      * Get the Variable at the specified row and column.
  58.      * @param row the row
  59.      * @param col the column
  60.      * @return the Variable at the specified row and column.
  61.      */
  62.     Variable get(int row, int col) {
  63.         int index = row * getSide() + col;
  64.         return variables.get(index);
  65.     }
  66.  
  67.    
  68.     /**
  69.      * Get the length of the board's side, i.e the square root of the
  70.      * number of cells.
  71.      * @return length of side.
  72.      */
  73.     public int getSide() {
  74.         return side;
  75.     }
  76.  
  77.    
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement