Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Iterator;
- import java.io.*;
- public class Kenken implements Iterable<Cell []>
- {
- private final int SIZE;
- private Cell [][] puzzle;
- private Constraint [] constraints;
- /** Puzzle File Format:
- *
- * ASCII text file with following data in each line:
- * 4 8 // size and number of constraints
- * // constraints
- * 4 + 2 0 0 0 1
- * 2 / 2 0 2 0 3
- * 1 - 2 1 0 1 1
- * 3 - 2 1 2 1 3
- * 5 + 2 2 0 3 0
- * 6 * 2 2 1 2 2
- * 2 / 2 3 1 3 2
- * 2 - 2 2 3 3 3
- * // solution
- * 3 1 4 2
- * 2 3 1 4
- * 4 2 3 1
- * 1 4 2 3
- *
- */
- public Kenken(Scanner file)
- {
- // read puzzle to be solved from a file Scanner
- Scanner line = new Scanner(file.nextLine()); // get size - first token on line 1
- SIZE = line.nextInt();
- puzzle = new Cell [SIZE][SIZE]; // setup puzzle based on the SIZE
- for (int i = 0; i < puzzle.length; i++)
- for (int j = 0; j < puzzle.length; j++)
- puzzle[i][j] = new Cell();
- constraints = new Constraint[line.nextInt()]; // get number of constraints - second token on line 1
- file.nextLine(); // get rid of comment line in file format
- int index = 0;
- for (int i = 0; i < constraints.length; i++) // process each constraint in the file
- {
- String s = file.nextLine();
- Scanner constraint = new Scanner(s); // one constraint per line
- int value = constraint.nextInt(); // the value
- char op = constraint.next().charAt(0); // the operator
- if (op == 's') // space substitution char is 's'
- op = ' ';
- int cells = constraint.nextInt(); // the number of Cells in the cage
- Cell [] cage = new Cell[cells];
- for (int j = 0; j < cells; j++) { // the pairs of ints for the Cell indices in puzzle
- int a = constraint.nextInt();
- int b = constraint.nextInt();
- cage[j] = puzzle[a][b];
- }
- constraints[index++] = new Constraint(value, op, cage); // create the constraint from input data
- }
- // fill in puzzle array with solution to be tested
- file.nextLine(); // get rid of comment line in file format
- for (int i = 0; i < puzzle.length; i++) {
- for (int j = 0; j < puzzle.length; j++) {
- puzzle[i][j].setValue(file.nextInt());
- }
- }
- }
- public String toString()
- {
- String s = "";
- for (int i = 0; i < puzzle.length; i++)
- for (int j = 0; j < puzzle.length; j++)
- s += puzzle[i][j] + ((j != puzzle.length - 1) ? ", " : "\n");
- return s;
- }
- public class KenkenIterator implements Iterator<Cell []>
- {
- private Cell [][] puzzle;
- private int cursor;
- private int cursorConstraint;
- public KenkenIterator()
- {
- cursor = cursorConstraint = 0;
- }
- public boolean hasNext()
- {
- return cursor < puzzle.length;
- }
- public Cell[] next()
- {
- Cell [] value = puzzle[cursor];
- cursor ++;
- return value;
- }
- public void remove()
- {
- }
- }
- public KenkenIterator iterator()
- {
- KenkenIterator temp;
- return temp;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement