rubikscube

college code for finding optimal rubiks cube solutions in java

git clone https://9o.is/git/rubikscube.git

PatternTable.java

(2160B)


      1 import java.io.*;
      2 
      3 /**
      4  * Stores a mapping of a key to a value in a file.
      5  * Stores in the format: key:value
      6  */
      7 public class PatternTable {
      8 
      9     /** The file that contains the pattern table. */
     10     private String file;
     11 
     12     /**
     13      * Creates a pattern table in a specified file.
     14      * @param file The file to save the pattern table.
     15      */
     16     public PatternTable(String file) {
     17         this.file = file;
     18     }
     19 
     20     /**
     21      * Updates the pattern table with a new key and value.
     22      * @param state The hashed state.
     23      * @param heuristic Heuristic of state.
     24      */
     25     public void updateTable(int state, byte heuristic) {
     26         try {
     27             BufferedWriter out =
     28                     new BufferedWriter(new FileWriter(file,true));
     29             out.write(state+":"+
     30                     Short.toString(heuristic)+"\n");
     31             out.close();
     32         } catch (IOException e) {
     33             System.err.println("Error: " + e.getMessage());
     34             e.printStackTrace();
     35         }
     36     }
     37 
     38     /**
     39      * Reads the pattern table.
     40      * @returns Byte array of byte[key] = value.
     41      */
     42     public byte[] readTable() {
     43         // 88mil is the max for corner states in rubik's cube
     44         byte[] result = new byte[88179840];
     45 
     46         try {
     47             BufferedReader in =
     48                     new BufferedReader(new FileReader(file));
     49             String str;
     50             while ((str = in.readLine()) != null) {
     51                 String[] parts = str.trim().split(":");
     52                 result[Integer.valueOf(parts[0])] = Byte.valueOf(parts[1]);
     53             }
     54             in.close();
     55         } catch (IOException e) {
     56             System.err.println("Error: " + e.getMessage());
     57             e.printStackTrace();
     58         }
     59         return result;
     60     }
     61 
     62     /**
     63      * Clears or empties the entire target file.
     64      */
     65     public void clearTable() {
     66         try {
     67             BufferedWriter out =
     68                     new BufferedWriter(new FileWriter(file));
     69             out.write("");
     70             out.close();
     71         } catch (IOException e) {
     72             System.err.println("Error: " + e.getMessage());
     73             e.printStackTrace();
     74         }
     75     }
     76 
     77 
     78 }