Ejemplo n.º 1
1
 public static void main(String[] args) {
   int T = Integer.valueOf(args[0]);
   Counter heads = new Counter("heads");
   Counter tails = new Counter("tails");
   for (int i = 0; i < T; i++) {
     if (StdRandom.bernoulli(0.5)) {
       heads.increment();
     } else {
       tails.increment();
     }
   }
   StdOut.println(heads);
   StdOut.println(tails);
   int d = heads.tally() - tails.tally();
   StdOut.println("delta:" + java.lang.Math.abs(d));
 }
  public PercolationStats(int N, int T) { // perform T independent experiments on an N-by-N grid
    if (N <= 0) {
      throw new IllegalArgumentException("The grid size must be bigger than zero");
    }
    if (T <= 0) {
      throw new IllegalArgumentException("The number of experiments must be bigger than zero");
    }

    double[] percolationThresholds = new double[T];
    for (int i = 0; i < T; i++) {
      Percolation percolation = new Percolation(N);

      int runs = 0;
      while (!percolation.percolates()) {
        int column;
        int row;

        do {
          column = 1 + StdRandom.uniform(N);
          row = 1 + StdRandom.uniform(N);
        } while (percolation.isOpen(row, column));

        percolation.open(row, column);
        runs++;
      }

      percolationThresholds[i] = runs / (double) (N * N);
    }

    mean = StdStats.mean(percolationThresholds);
    stddev = StdStats.stddev(percolationThresholds);
    double confidenceFraction = (1.96 * stddev()) / Math.sqrt(T);
    confidenceLo = mean - confidenceFraction;
    confidenceHi = mean + confidenceFraction;
  }
Ejemplo n.º 3
0
  /** Perform T independent experiments on an N sized percolation systme. */
  public PercolationStats(int N, int T) {
    if ((N <= 0) || (T <= 0)) {
      throw new IllegalArgumentException();
    }

    percolationThresholds = new double[T];

    for (int i = 0; i < T; i++) {
      Percolation p = new Percolation(N);
      int numOpenSites = 0;

      // Open sites at random until the system percolates.
      while (!p.percolates()) {
        int x = StdRandom.uniform(1, N + 1);
        int y = StdRandom.uniform(1, N + 1);

        if (!p.isOpen(x, y)) {
          p.open(x, y);
          numOpenSites++;
        }
      }

      percolationThresholds[i] = (double) numOpenSites / (N * N);
    }
  }
Ejemplo n.º 4
0
  public PercolationStats(int N, int T) {
    // perform T independent experiments on an N-by-N grid
    if (N <= 0 || T <= 0) {
      throw new IllegalArgumentException("N & T should be > 0");
    }
    arrayMean = new double[T];
    testNum = T;
    while (T-- > 0) {
      openCount = 0;

      Percolation gridObj = new Percolation(N);
      while (!gridObj.percolates()) {

        firstRand = StdRandom.uniform(N + 1);
        while (firstRand == 0) firstRand = StdRandom.uniform(N + 1);

        secondRand = StdRandom.uniform(N + 1);
        while (secondRand == 0) secondRand = StdRandom.uniform(N + 1);

        //  System.out.print(firstRand+" "+secondRand + "\n");

        if (!gridObj.isOpen(firstRand, secondRand)) {
          gridObj.open(firstRand, secondRand);
          openCount++;
        }
      }
      arrayMean[index++] = openCount / (double) (N * N);
    }
  }
Ejemplo n.º 5
0
  public static void main(String[] args) // test client (optional)
      {
    final int num_tests = 1000;
    final int grid_size = 20;

    StdOut.println("Begin Generating Random Sites...");

    int row, col, count;
    double sum = 0.0;

    for (int i = 0; i < num_tests; i++) {
      count = 0;
      Percolation p = new Percolation(grid_size);
      while (!p.percolates()) {
        // choose site at random
        row = StdRandom.uniform(1, grid_size + 1);
        col = StdRandom.uniform(1, grid_size + 1);

        if (!p.isOpen(row, col)) {
          p.open(row, col);
          count++;
        }
      }
      sum += count;
    }

    StdOut.println("Average number of sites opened: " + sum / num_tests);
  }
Ejemplo n.º 6
0
  /*perform T independent experiments on an N-by-N grid*/
  public PercolationStats(int N, int T) {
    if (N > 0 && T > 0) {
      simResTab = new double[T];
      repeatCnt = T;
      int elemCnt = N * N;

      for (int i = 0; i < T; i++) {
        Percolation perc = new Percolation(N);

        int cntr = 0;
        int row, col;

        do {
          do {
            row = StdRandom.uniform(1, N + 1);
            col = StdRandom.uniform(1, N + 1);
          } while (perc.isOpen(row, col));

          perc.open(row, col);
          cntr++;
        } while (!perc.percolates());

        simResTab[i] = (double) cntr / elemCnt;
        perc = null;
      }
    } else {
      throw new java.lang.IllegalArgumentException();
    }
  }
Ejemplo n.º 7
0
  // perform T independent experiments on an N-by-N grid
  public PercolationStats(int N, int T) {
    if (N <= 0 || T <= 0) {
      throw new IllegalArgumentException("Given number is not positive");
    }

    threshold = new double[T];

    time = T; // for we have to use times later on

    // for each experiment--create a new Percolation object and do open sites until we get
    // percolates
    for (int i = 0; i < T; i++) {
      int count = 0; // used to count the number of opened sites

      Percolation p = new Percolation(N);
      while (!p.percolates()) {
        int row = StdRandom.uniform(N) + 1;
        int cln = StdRandom.uniform(N) + 1;

        if (!p.isOpen(row, cln)) {
          p.open(row, cln);
          count++;
        }
      }

      // calculate the threshold ratio after finished
      threshold[i] = (double) count / (N * N);
    }
  }
Ejemplo n.º 8
0
  // perform T independent experiments on an N-by-N grid
  public PercolationStats(int N, int T) {
    if (N <= 0 || T <= 0)
      throw new IllegalArgumentException("Neither 'N' or 'T' cannot be equals or less than zero.");

    n = N;
    t = T;

    Percolation p;
    thresholds = new double[T];
    int i, j, x;

    for (int z = 0; z < T; z++) {
      x = 0;
      p = new Percolation(n);

      while (!p.percolates()) {
        i = StdRandom.uniform(1, n + 1);
        j = StdRandom.uniform(1, n + 1);

        if (!p.isOpen(i, j)) {
          p.open(i, j);
          x++;
        }
      }

      thresholds[z] = x / (double) (n * n);
      /*StdOut.println("Threshold " + String.valueOf(z + 1) + ": " +
      thresholds[z]);*/
    }
  }
Ejemplo n.º 9
0
 /** Initializes a random 4-by-4 board, by rolling the Hasbro dice. */
 public BoggleBoard() {
   M = 4;
   N = 4;
   StdRandom.shuffle(BOGGLE_1992);
   board = new char[M][N];
   for (int i = 0; i < M; i++) {
     for (int j = 0; j < N; j++) {
       String letters = BOGGLE_1992[N * i + j];
       int r = StdRandom.uniform(letters.length());
       board[i][j] = letters.charAt(r);
     }
   }
 }
Ejemplo n.º 10
0
 public static double TrialQuickUnionUF(int N) {
   Stopwatch watch = new Stopwatch();
   QuickUnionUF uf = new QuickUnionUF(N);
   for (int i = 0; i < N; i++) {
     int p = StdRandom.uniform(N);
     int q = StdRandom.uniform(N);
     if (!uf.connected(p, q)) {
       uf.union(p, q);
     }
   }
   double time = watch.elapsedTime();
   // printTree(uf);
   return time;
 }
Ejemplo n.º 11
0
 /** return (but do not remove) a random item */
 public Item sample() {
   if (isEmpty()) {
     throw new java.util.NoSuchElementException();
   }
   int index = StdRandom.uniform(this.size);
   return this.a[index];
 }
Ejemplo n.º 12
0
 public RandomizedQueueIterator() {
   seq = new int[RandomizedQueue.this.size];
   for (int i = 0; i < seq.length; i++) {
     seq[i] = i;
   }
   StdRandom.shuffle(seq);
 }
Ejemplo n.º 13
0
 public ReverseQueueIterator() {
     shuffledIndexArr = new int[size];
     for (int j = 0; j < size; j++) {
         shuffledIndexArr[j] = j;
     }
     StdRandom.shuffle(shuffledIndexArr);
     i = 0;
 }
Ejemplo n.º 14
0
 public Item sample() {
   // return (but do not remove) a random item
   if (isEmpty()) {
     throw new NoSuchElementException();
   }
   int randomnumber = StdRandom.uniform(size);
   return arr[randomnumber];
 }
Ejemplo n.º 15
0
 QueueIterator() {
   i = 0;
   perms = new int[N];
   for (int j = 0; j < N; j++) {
     perms[j] = j;
   }
   StdRandom.shuffle(perms);
 }
Ejemplo n.º 16
0
 public static void main(String[] args) {
   int n = 10;
   StdDraw.setCanvasSize(160, 640);
   StdDraw.setXscale(-1, n + 1);
   StdDraw.setPenRadius(0.006);
   double[] a = new double[n];
   for (int i = 0; i < n; i++) a[i] = StdRandom.uniform(0.0, 1.0);
   sort(a);
 }
Ejemplo n.º 17
0
 // Test Client
 public static void main(String[] args) {
   int N = StdIn.readInt();
   Double[] input = new Double[N];
   for (int i = 0; i < N; i++) {
     input[i] = StdRandom.uniform();
   }
   QuickSort.sort3Way(input);
   display(input);
 }
  public PercolationStats(int n, int t) {
    if (n < 1 || t < 1) throw new IndexOutOfBoundsException("Illegal parameter value.");

    int row, col;
    experimentsCount = t;
    count = new double[experimentsCount];
    for (int i = 0; i < experimentsCount; i++) {
      perc = new Percolation(n);
      while (!perc.percolates()) {
        row = StdRandom.uniform(n) + 1;
        col = StdRandom.uniform(n) + 1;
        if (!perc.isOpen(row, col)) {
          perc.open(row, col);
          count[i]++;
        }
      }
      count[i] = count[i] / (n * n);
    }
  }
Ejemplo n.º 19
0
 public RandomizedQueueIterator() {
   itemTemp = (Item[]) new Object[size];
   for (int i = 0; i < size; i++) {
     itemTemp[i] = arr[i];
   }
   if (size > 0) {
     StdRandom.shuffle(itemTemp, 0, size - 1);
   }
   count = size;
 }
 public PercolationStats(int N, int T) {
   if (N <= 0 || T <= 0) throw new java.lang.IllegalArgumentException();
   double[] results = new double[T];
   for (int i = 0; i < T; i++) {
     Percolation percolation = new Percolation(N);
     int count = 0;
     while (!percolation.percolates()) {
       int p = StdRandom.uniform(N) + 1;
       int q = StdRandom.uniform(N) + 1;
       if (!percolation.isOpen(p, q)) {
         count++;
         percolation.open(p, q);
       }
     }
     results[i] = (double) count / (N * N);
   }
   mean = StdStats.mean(results);
   stdDev = StdStats.stddev(results);
   sampleSize = T;
 }
Ejemplo n.º 21
0
 public static Comparable select(Comparable[] a, int k) {
   StdRandom.shuffle(a);
   int lo = 0;
   int hi = a.length - 1;
   while (hi > lo) {
     int pivotIdx = partition(a, lo, hi);
     if (pivotIdx > k) hi = pivotIdx - 1;
     else if (pivotIdx < k) lo = pivotIdx + 1;
     else break;
   }
   return a[k];
 }
Ejemplo n.º 22
0
  private void shuffle() {
    Item temp;
    int randi;

    for (int i = 0; i < N; i++) {
      randi = StdRandom.uniform(N);

      temp = a[i];
      a[i] = a[randi];
      a[randi] = temp;
    }
  }
Ejemplo n.º 23
0
 public Item dequeue() {
   if (size == 0) throw new java.util.NoSuchElementException();
   // StdRandom.shuffle(arr, 0, size- 1);
   int randomN = StdRandom.uniform(size);
   assert (size > 0);
   Item item = arr[randomN];
   swap(randomN, size - 1);
   arr[size - 1] = null;
   size--;
   if (size > 0 && size == arr.length / 4) {
     resize((arr.length) / 2);
   }
   return item;
 }
Ejemplo n.º 24
0
    /**
     * Remove and return a random item
     * @return the removed item
     */ 
    public Item dequeue() {
        if (isEmpty())
            throw new NoSuchElementException("Queue underflow");

        int index = StdRandom.uniform(size);
        Item item = a[index];

        a[index] = a[size - 1];
        a[size - 1] = null;
        size--;
        // shrink size of array if neccessary
        if (size > 0 && size == a.length/4) resize(a.length / 2);
        return item;
    }
Ejemplo n.º 25
0
 /** remove and return a random item */
 public Item dequeue() {
   if (isEmpty()) {
     throw new java.util.NoSuchElementException();
   }
   int index = StdRandom.uniform(this.size);
   this.size--;
   exchange(index, this.size);
   Item item = this.a[this.size];
   this.a[this.size] = null;
   if (this.size > 0 && this.size == this.a.length / 4) {
     resize(this.a.length / 2);
   }
   return item;
 }
Ejemplo n.º 26
0
  /**
   * Remove and return a random item
   *
   * @return the random item
   */
  public Item dequeue() {
    if (N == 0) throw new java.util.NoSuchElementException();

    int i = StdRandom.uniform(N);

    exch(i, N - 1);

    Item item = a[N - 1];
    a[N - 1] = null; // don't loiter
    N--;

    if (N > 0 && N == a.length / 4) resize(a.length / 2);

    return item;
  }
Ejemplo n.º 27
0
 /**
  * Initializes a random M-by-N board, according to the frequency of letters in the English
  * language.
  *
  * @param M the number of rows
  * @param N the number of columns
  */
 public BoggleBoard(int M, int N) {
   this.M = M;
   this.N = N;
   if (M <= 0) {
     throw new IllegalArgumentException("number of rows must be a positive integer");
   }
   if (N <= 0) {
     throw new IllegalArgumentException("number of columns must be a positive integer");
   }
   board = new char[M][N];
   for (int i = 0; i < M; i++) {
     for (int j = 0; j < N; j++) {
       int r = StdRandom.discrete(FREQUENCIES);
       board[i][j] = ALPHABET.charAt(r);
     }
   }
 }
Ejemplo n.º 28
0
  /**
   * Item dequeue() 删除并随机返回一个元素(取样且不放回) 删除一个元素时,随机交换某个元素(索引在0和N-1之间)和末位元素(索引为N-1)的位置,然后像
   * ResizingArrayStack 一样删除并返回末位元素。
   *
   * @return
   */
  public Item dequeue() {
    if (isEmpty()) {
      return null;
    } else {
      int randi = StdRandom.uniform(N); // 0 - N

      Item item = a[randi];
      a[randi] = a[N - 1]; // exchange randi last
      a[N - 1] = null; // 防止对象游离

      N--;
      if (N == a.length / 4) {
        resize(a.length / 2);
      }
      return item;
    }
  }
Ejemplo n.º 29
0
  public static void drawRandConn(int N, double p) {
    StdDraw.setCanvasSize(512, 512);
    StdDraw.setScale(-1.0, 1.0);
    StdDraw.setPenRadius(.025);

    double[][] d = new double[N][2];
    for (int i = 0; i < N; i++) {
      d[i][0] = Math.cos(2 * Math.PI * i / N);
      d[i][1] = Math.sin(2 * Math.PI * i / N);
      StdDraw.point(d[i][0], d[i][1]);
    }

    StdDraw.setPenRadius();
    StdDraw.setPenColor(StdDraw.GRAY);

    for (int i = 0; i < N - 1; i++)
      for (int j = i + 1; j < N; j++)
        if (StdRandom.bernoulli(p)) StdDraw.line(d[i][0], d[i][1], d[j][0], d[j][1]);
  }
Ejemplo n.º 30
0
 public PercolationStats(int N, int T) { // perform T independent experiments on an N-by-N grid
   if (N <= 0 || T <= 0) throw new IllegalArgumentException();
   t = T;
   a = new double[T];
   for (int i = 0; i < T; i++) {
     Percolation percolation = new Percolation(N);
     int cnt = 0;
     while (!percolation.percolates()) {
       int x, y;
       do {
         int rand = StdRandom.uniform(N * N);
         x = rand / N + 1;
         y = rand % N + 1;
       } while (percolation.isOpen(x, y));
       cnt += 1;
       percolation.open(x, y);
     }
     a[i] = 1.0 * cnt / (N * N);
   }
 }