示例#1
0
  /** Main program. */
  public static void main(String[] args) throws Exception {
    // Parse command line arguments.
    if (args.length != 3) usage();
    C = Integer.parseInt(args[1]);
    S = Integer.parseInt(args[0]) - 1;
    A = ONE_THIRD;
    B = new BigRational("9/10");
    filename = new File(args[2]);

    // Allocate storage for old and new cell arrays. Initialize all cells to
    // 0, except center cell to 1.
    currCell = new BigRational[C];
    nextCell = new BigRational[C];
    for (int i = 0; i < C; ++i) {
      currCell[i] = new BigRational();
      nextCell[i] = new BigRational();
    }
    currCell[C / 2].assign(ONE);

    // Allocate storage for output image.
    matrix = new byte[S + 1][C];
    image = new PJGGrayImage(S + 1, C, matrix);
    image.setInterpretation(PJGGrayImage.ZERO_IS_WHITE);

    // Do S time steps.
    for (int s = 0; s < S; ++s) {
      // Calculate next state of each cell.
      for (int i = 0; i < C; ++i) {
        nextCell[i]
            .assign(currCell[i])
            .add(currCell[(i - 1 + C) % C])
            .add(currCell[(i + 1) % C])
            .mul(A)
            .add(B)
            .normalize()
            .fracPart();
      }

      // Write current CA state to image matrix.
      writeCurrCell(s);

      // Advance one time step -- swap old and new cell arrays.
      BigRational[] tmp = currCell;
      currCell = nextCell;
      nextCell = tmp;
    }

    // Write final CA state to image matrix.
    writeCurrCell(S);

    // Write output image to PJG file.
    PJGImage.Writer writer =
        image.prepareToWrite(new BufferedOutputStream(new FileOutputStream(filename)));
    writer.write();
    writer.close();

    // Read image from file into a different matrix.
    image2 = new PJGGrayImage();
    PJGImage.Reader reader =
        image2.prepareToRead(new BufferedInputStream(new FileInputStream(filename)));
    reader.read();
    reader.close();

    // Compare output matrix with input matrix.
    matrix2 = image2.getMatrix();
    for (int r = 0; r <= S; ++r) {
      byte[] matrix_r = matrix[r];
      byte[] matrix2_r = matrix2[r];
      for (int c = 0; c < C; ++c) {
        if (matrix_r[c] != matrix2_r[c]) {
          System.out.print("matrix[");
          System.out.print(r);
          System.out.print("][");
          System.out.print(c);
          System.out.print("] = ");
          System.out.print(Hex.toString(matrix_r[c]));
          System.out.print(", matrix2[");
          System.out.print(r);
          System.out.print("][");
          System.out.print(c);
          System.out.print("] = ");
          System.out.print(Hex.toString(matrix2_r[c]));
          System.out.println();
        }
      }
    }
  }
示例#2
0
 /**
  * Write the current cell array to the image file.
  *
  * @param s Step (image row) index.
  */
 private static void writeCurrCell(int s) throws IOException {
   for (int i = 0; i < C; ++i) {
     image.setPixel(s, i, currCell[i].floatValue());
   }
 }