Ejemplo n.º 1
0
  /** Unit tests the <tt>com.akieus.algos.coursera.lib.TopologicalX</tt> data type. */
  public static void main(String[] args) {

    // create random DAG with V vertices and E edges; then add F random edges
    int V = Integer.parseInt(args[0]);
    int E = Integer.parseInt(args[1]);
    int F = Integer.parseInt(args[2]);
    Digraph G = DigraphGenerator.dag(V, E);

    // add F extra edges
    for (int i = 0; i < F; i++) {
      int v = StdRandom.uniform(V);
      int w = StdRandom.uniform(V);
      G.addEdge(v, w);
    }

    StdOut.println(G);

    // find a directed cycle
    TopologicalX topological = new TopologicalX(G);
    if (!topological.hasOrder()) {
      StdOut.println("Not a DAG");
    }

    // or give topologial sort
    else {
      StdOut.print("com.akieus.algos.coursera.lib.Topological order: ");
      for (int v : topological.order()) {
        StdOut.print(v + " ");
      }
      StdOut.println();
    }
  }
Ejemplo n.º 2
0
 private void search() {
   Point[] aux = new Point[size];
   for (int i = 0; i < size; i++) aux[i] = p[i];
   for (int i = 0; i < size; i++) {
     Arrays.sort(aux);
     Arrays.sort(aux, p[i].SLOPE_ORDER);
     int start = 1;
     int end = 1;
     for (int j = 2; j < size + 1; j++) {
       if (j != size && p[i].slopeTo(aux[j]) == p[i].slopeTo(aux[j - 1])) {
         end++;
       } else {
         if (end > start + 1) {
           int k;
           for (k = start; k <= end; k++) {
             if (p[i].compareTo(aux[k]) >= 0) {
               break;
             }
           }
           if (k == end + 1) {
             p[i].drawTo(aux[end]);
             StdOut.print(p[i].toString());
             for (int m = start; m <= end; m++) {
               StdOut.print(" -> " + aux[m].toString());
             }
             StdOut.println();
           }
         }
         start = j;
         end = j;
       }
     }
   }
 }
Ejemplo n.º 3
0
 /** Print an array of booleans to standard output. */
 public static void print(boolean[] a) {
   int N = a.length;
   StdOut.println(N);
   for (int i = 0; i < N; i++) {
     if (a[i]) StdOut.print("1 ");
     else StdOut.print("0 ");
   }
   StdOut.println();
 }
Ejemplo n.º 4
0
 /** Print the M-by-N array of booleans to standard output. */
 public static void print(boolean[][] a) {
   int M = a.length;
   int N = a[0].length;
   StdOut.println(M + " " + N);
   for (int i = 0; i < M; i++) {
     for (int j = 0; j < N; j++) {
       if (a[i][j]) StdOut.print("1 ");
       else StdOut.print("0 ");
     }
     StdOut.println();
   }
 }
Ejemplo n.º 5
0
 public static void main(String[] args) {
   BaseballElimination division = new BaseballElimination(args[0]);
   for (String team : division.teams()) {
     if (division.isEliminated(team)) {
       StdOut.print(team + " is eliminated by the subset R = { ");
       for (String t : division.certificateOfElimination(team)) StdOut.print(t + " ");
       StdOut.println("}");
     } else {
       StdOut.println(team + " is not eliminated");
     }
   }
 }
Ejemplo n.º 6
0
  public static void main(String[] args) {

    // rescale coordinates and turn on animation mode
    StdDraw.setXscale(0, 32768);
    StdDraw.setYscale(0, 32768);
    StdDraw.show(0);
    StdDraw.setPenColor(StdDraw.BLUE);
    // read in the input
    String filename = args[0];
    In in = new In(filename);
    int N = in.readInt();
    Point[] points = new Point[N];
    for (int i = 0; i < N; i++) {
      int x = in.readInt();
      int y = in.readInt();
      points[i] = new Point(x, y);
      points[i].draw();
    }
    Quick.sort(points);
    boolean[] flags = new boolean[N];
    for (int i = 0; i < N; i++) {
      Point[] pfs = new Point[N];
      for (int m = 0; m < N; m++) pfs[m] = points[m];
      Arrays.sort(pfs, points[i].SLOPE_ORDER);
      for (int j = 0; j < N; ) {
        double t1 = points[i].slopeTo(pfs[j]);
        int idx = j;
        int count = 0;
        while (idx < N && points[i].slopeTo(pfs[idx]) == t1 && points[i].compareTo(pfs[idx]) < 0) {
          idx++;
          count++;
        }
        if (count >= 3) {
          int result = 0;
          for (int k = j; k < idx; k++) if (flags[i]) result++;
          if (result == count) {
            j = idx;
            continue;
          }
          StdOut.print(points[i] + " -> ");
          for (int k = j; k < idx; k++) {
            if (k == idx - 1) StdOut.print(pfs[k] + "\n");
            else StdOut.print(pfs[k] + " -> ");
            flags[k] = true;
            points[i].drawTo(pfs[k]);
          }
          j = idx;
        } else j++;
      }
    }
    StdDraw.show(0);
  }
Ejemplo n.º 7
0
  public static void main(String[] args) {
    MyBST<String, Integer> bst = new MyBST<String, Integer>();
    In in = new In("binaryTree.txt");
    int N = in.readInt();
    for (int i = 0; i < N; ++i) {
      String s = in.readString();
      int v = in.readInt();
      bst.put(s, v);
    }
    bst.print();
    /*        StdOut.println("max= " + bst.max() + ":" + bst.get(bst.max()));
    StdOut.println("min= " + bst.min() + ":" + bst.get(bst.min()));
    bst.deleteMax();
    bst.deleteMin();
    StdOut.println("max= " + bst.max() + ":" + bst.get(bst.max()));
    StdOut.println("min= " + bst.min() + ":" + bst.get(bst.min()));
    bst.delete("g");
    bst.print();
    for(String s : bst.keys("a", "f"))
        StdOut.print(s + " ");
    StdOut.println();
    StdOut.println(bst.rank("k"));
    StdOut.println(bst.select(3)); */
    StdOut.println(bst.height());
    StdOut.println(bst.avgCompares());
    StdOut.println(bst.randomKey());
    StdOut.println(bst.get("d"));
    StdOut.println(bst.get("d"));
    bst.put("l", 11);
    StdOut.println(bst.get("l"));
    StdOut.println(bst.isBinaryTree());
    StdOut.println(bst.isOrdered());
    StdOut.println(bst.hasNoDuplicates());
    StdOut.println(bst.checkRankSelect());
    StdOut.println(bst.checkSelectRank());
    bst.levelOrderPrint();

    bst.deleteMax();
    bst.deleteMin();
    bst.delete("j");

    for (String s : bst.keysNew()) StdOut.print(s + " ");
    StdOut.println();

    for (String s : bst.keysNewReverse()) StdOut.print(s + " ");
    StdOut.println();

    bst.draw();
  }
Ejemplo n.º 8
0
  /** Unit tests the <tt>DirectedCycle</tt> data type. */
  public static void main(String[] args) {
    In in = new In(args[0]);
    Digraph G = new Digraph(in);

    DirectedCycle finder = new DirectedCycle(G);
    if (finder.hasCycle()) {
      StdOut.print("Cycle: ");
      for (int v : finder.cycle()) {
        StdOut.print(v + " ");
      }
      StdOut.println();
    } else {
      StdOut.println("No cycle");
    }
  }
Ejemplo n.º 9
0
  public static void main(String[] args) {
    String alg1 = args[0];
    String alg2 = args[1];
    int N = Integer.parseInt(args[2]);
    int T = Integer.parseInt(args[3]);

    double t1 = timeRandomInput(alg1, N, T);
    double t2 = timeRandomInput(alg2, N, T);
    StdOut.print(alg1 + " ");
    StdOut.println(t1);
    StdOut.print(alg2 + " ");
    StdOut.println(t2);
    StdOut.printf("For %d random Double\n  %s is", N, alg1);
    StdOut.printf(" %.1f time sfaster than %s\n", t2 / t1, alg2);
  }
Ejemplo n.º 10
0
 public static void main(String[] args) { // unit tests (not graded)
   In in = new In(args[0]); // input file
   int N = in.readInt();
   int[][] blocks = new int[N][N];
   for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) blocks[i][j] = in.readInt();
   Board bd = new Board(blocks);
   StdOut.println("dimension: " + bd.dimension());
   StdOut.println("hamming: " + bd.hamming());
   StdOut.println("Manhattan distances: " + bd.manhattan());
   StdOut.println("is goal: " + bd.isGoal());
   StdOut.print(bd);
   StdOut.print("twin: " + bd.twin());
   StdOut.println("twin equal: " + bd.equals(bd.twin()));
   StdOut.println("twin twin equal: " + bd.equals(bd.twin().twin()));
   for (Board it : bd.neighbors()) StdOut.print(it);
 }
Ejemplo n.º 11
0
 public static void main(String[] args) {
   StdOut.print("Input the size of the array: ");
   int N = StdIn.readInt();
   Double[] a = new Double[N];
   for (int i = 0; i < N; i++) a[i] = StdRandom.uniform();
   sort(a);
 }
Ejemplo n.º 12
0
  /** Unit tests the <tt>GabowSCC</tt> data type. */
  public static void main(String[] args) {
    In in = new In(args[0]);
    Digraph G = new Digraph(in);
    GabowSCC scc = new GabowSCC(G);

    // number of connected components
    int M = scc.count();
    StdOut.println(M + " components");

    // compute list of vertices in each strong component
    Queue<Integer>[] components = (Queue<Integer>[]) new Queue[M];
    for (int i = 0; i < M; i++) {
      components[i] = new Queue<Integer>();
    }
    for (int v = 0; v < G.V(); v++) {
      components[scc.id(v)].enqueue(v);
    }

    // print results
    for (int i = 0; i < M; i++) {
      for (int v : components[i]) {
        StdOut.print(v + " ");
      }
      StdOut.println();
    }
  }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    In in = new In("jobsPC1.txt");
    int N = in.readInt();
    in.readLine();
    EdgeWeightedDigraph G;
    G = new EdgeWeightedDigraph(2 * N + 2);
    int s = 2 * N, t = 2 * N + 1;
    for (int i = 0; i < N; ++i) {
      String[] a = in.readLine().split("\\s+");
      double duration = Double.parseDouble(a[0]);
      G.addEdge(new DirectedEdge(i, i + N, duration));
      G.addEdge(new DirectedEdge(s, i, 0.0));
      G.addEdge(new DirectedEdge(i + N, t, 0.0));
      for (int j = 1; j < a.length; ++j) {
        G.addEdge(new DirectedEdge(i + N, Integer.parseInt(a[j]), 0));
      }
    }
    StdOut.println(G);
    MyAcyclicLP lp = new MyAcyclicLP(G, s);

    StdOut.println("Start times: ");
    for (int i = 0; i < N; ++i) StdOut.printf("%4d: %5.1f\n", i, lp.distTo(i));
    StdOut.printf("%5.1f\n", lp.distTo(t));

    for (DirectedEdge e : lp.pathTo(t)) {
      StdOut.print(e + " ");
    }
    StdOut.println();
  }
Ejemplo n.º 14
0
  public static void main(String[] args) {
    Deque<Integer> ints = new Deque<Integer>();

    assert ints.size() == 0;
    assert ints.isEmpty();

    ints.addFirst(1);
    assert ints.size() == 1;
    assert !ints.isEmpty();

    int val = ints.removeFirst();
    assert val == 1;
    assert ints.size() == 0;
    assert ints.isEmpty();

    ints.addFirst(2);
    assert ints.size() == 1;
    assert !ints.isEmpty();

    val = ints.removeLast();
    assert val == 2;
    assert ints.size() == 0;
    assert ints.isEmpty();

    ints.addFirst(3);
    ints.addFirst(2);
    ints.addFirst(1);
    ints.addLast(4);
    ints.addLast(5);
    ints.addLast(6);

    assert ints.size() == 6;
    assert !ints.isEmpty();

    for (int value : ints) {
      StdOut.print(value + " ");
    }

    StdOut.println();

    while (!ints.isEmpty()) {
      StdOut.println(ints.removeLast());
    }

    assert ints.size() == 0;
    assert ints.isEmpty();

    for (int i = 0; i < 10; ++i) {
      ints.addFirst(i);
    }

    for (int i = 0; i < 10; ++i) {
      assert ints.size() == 10 - i;
      ints.removeLast();
    }

    assert ints.size() == 0;
  }
Ejemplo n.º 15
0
  public static void main(String[] args) {
    int BITS_PER_LINE = 16;
    if (args.length == 1) {
      BITS_PER_LINE = Integer.parseInt(args[0]);
    }

    int count;
    for (count = 0; !BinaryStdIn.isEmpty(); count++) {
      if (BITS_PER_LINE == 0) {
        BinaryStdIn.readBoolean();
        continue;
      } else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println();
      if (BinaryStdIn.readBoolean()) StdOut.print(1);
      else StdOut.print(0);
    }
    if (BITS_PER_LINE != 0) StdOut.println();
    StdOut.println("Liczba bitow: " + count);
  }
  public static void main(String[] args) {
    int max = Integer.parseInt(args[0]);
    ArrayStackOfStrings stack = new ArrayStackOfStrings(max);
    while (!StdIn.isEmpty()) {
      String item = StdIn.readString();
      if (!item.equals("-")) stack.push(item);
      else if (stack.isEmpty()) StdOut.println("BAD INPUT");
      else StdOut.print(stack.pop() + " ");
    }
    StdOut.println();

    // print what's left on the stack
    StdOut.print("Left on stack: ");
    for (String s : stack) {
      StdOut.print(s + " ");
    }
    StdOut.println();
  }
Ejemplo n.º 17
0
 /** Unit tests the <tt>Queue</tt> data type. */
 public static void main(String[] args) {
   Queue<String> q = new Queue<String>();
   while (!StdIn.isEmpty()) {
     String item = StdIn.readString();
     if (!item.equals("-")) q.enqueue(item);
     else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
   }
   StdOut.println("(" + q.size() + " left on queue)");
 }
Ejemplo n.º 18
0
 /** Unit tests the <tt>Stack</tt> data type. */
 public static void main(String[] args) {
   Stack<String> s = new Stack<String>();
   while (!StdIn.isEmpty()) {
     String item = StdIn.readString();
     if (!item.equals("-")) s.push(item);
     else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
   }
   StdOut.println("(" + s.size() + " left on stack)");
 }
Ejemplo n.º 19
0
 private static void printArray(int[] array) {
   if (array != null) {
     for (int i = 0; i < array.length; i++) {
       StdOut.print(array[i] + " ");
     }
     StdOut.println();
   } else {
     StdOut.println("Array not available");
   }
 }
Ejemplo n.º 20
0
  /** Unit tests the <tt>DepthFirstPaths</tt> data type. */
  public static void main(String[] args) {
    In in = new In(args[0]);
    Graph G = new Graph(in);
    int s = Integer.parseInt(args[1]);
    DepthFirstPaths dfs = new DepthFirstPaths(G, s);

    for (int v = 0; v < G.V(); v++) {
      if (dfs.hasPathTo(v)) {
        StdOut.printf("%d to %d:  ", s, v);
        for (int x : dfs.pathTo(v)) {
          if (x == s) StdOut.print(x);
          else StdOut.print("-" + x);
        }
        StdOut.println();
      } else {
        StdOut.printf("%d to %d:  not connected\n", s, v);
      }
    }
  }
Ejemplo n.º 21
0
  /** @param args */
  public static void main(String[] args) {

    try {
      int N = StdIn.readInt();

      indexArray = new int[N];
      for (int i = 0; i < N; i++) {
        indexArray[i] = i;
      }

      UF uf = new WeightedQuickUnionUF(N);
      while (!StdIn.isEmpty()) {
        int p = StdIn.readInt();

        if (p == -1) {

          p = StdIn.readInt();
          int q = StdIn.readInt();

          StdOut.print(p + " and " + q + " are");
          if (!uf.connected(p, q)) {
            StdOut.print(" not");
          }
          StdOut.println(" connected.");

        } else {

          int q = StdIn.readInt();
          if (!uf.connected(p, q)) {

            uf.union(p, q);
            StdOut.println("connecting " + p + " " + q);
          }
        }
        printArray(indexArray);
        printArray(uf.idArray());
        printArray(uf.sizeArray());
        StdOut.println();
      }
    } catch (InputMismatchException e) {
      System.exit(0);
    }
  }
Ejemplo n.º 22
0
 public static void main(String[] args) {
   // unit testing
   RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>();
   for (int i = 0; i < 10; i++) {
     rq.enqueue(i);
   }
   for (Integer s : rq) StdOut.println(s.intValue());
   StdOut.print("\n");
   for (int i = 0; i < 10; i++) {
     StdOut.println(rq.dequeue().intValue());
   }
 }
Ejemplo n.º 23
0
  public static void main(String[] args) {
    ResizingArrayStack<String> strStack = new ResizingArrayStack<String>();
    while (!StdIn.isEmpty()) {
      String item = StdIn.readString();
      if (!item.equals("-")) strStack.push(item);
      else if (!strStack.isEmpty()) StdOut.print(strStack.pop() + " ");
    }

    for (String s : strStack) StdOut.println(s);

    StdOut.println("(" + strStack.size() + " left on stack)");
  }
Ejemplo n.º 24
0
  /**
   * Unit tests the {@code DepthFirstOrder} data type.
   *
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
    In in = new In(args[0]);
    Digraph G = new Digraph(in);

    DepthFirstOrder dfs = new DepthFirstOrder(G);
    StdOut.println("   v  pre post");
    StdOut.println("--------------");
    for (int v = 0; v < G.V(); v++) {
      StdOut.printf("%4d %4d %4d\n", v, dfs.pre(v), dfs.post(v));
    }

    StdOut.print("Preorder:  ");
    for (int v : dfs.pre()) {
      StdOut.print(v + " ");
    }
    StdOut.println();

    StdOut.print("Postorder: ");
    for (int v : dfs.post()) {
      StdOut.print(v + " ");
    }
    StdOut.println();

    StdOut.print("Reverse postorder: ");
    for (int v : dfs.reversePost()) {
      StdOut.print(v + " ");
    }
    StdOut.println();
  }
  public static void main(String[] args) {
    FixedCapacityStackOfStrings strStack = new FixedCapacityStackOfStrings(10);

    while (!StdIn.isEmpty()) {
      String item = StdIn.readString();
      if (!item.equals("-")) strStack.push(item);
      else if (!strStack.isEmpty()) StdOut.print(strStack.pop() + " ");
    }

    for (String s : strStack) StdOut.println(s);

    StdOut.println("(" + strStack.size() + " left on stack)");
  }
Ejemplo n.º 26
0
  /** Interactive test of basic functionality. */
  public static void main(String[] args) {

    StdOut.print("Type a string: ");
    String s = StdIn.readString();
    StdOut.println("Your string was: " + s);
    StdOut.println();

    StdOut.print("Type an int: ");
    int a = StdIn.readInt();
    StdOut.println("Your int was: " + a);
    StdOut.println();

    StdOut.print("Type a boolean: ");
    boolean b = StdIn.readBoolean();
    StdOut.println("Your boolean was: " + b);
    StdOut.println();

    StdOut.print("Type a double: ");
    double c = StdIn.readDouble();
    StdOut.println("Your double was: " + c);
    StdOut.println();
  }
Ejemplo n.º 27
0
  // test client
  public static void main(String[] args) {
    String pat = args[0];
    String txt = args[1];
    char[] pattern = pat.toCharArray();
    char[] text = txt.toCharArray();

    BoyerMoore boyermoore1 = new BoyerMoore(pat);
    BoyerMoore boyermoore2 = new BoyerMoore(pattern, 256);
    int offset1 = boyermoore1.search(txt);
    int offset2 = boyermoore2.search(text);

    // print results
    StdOut.println("text:    " + txt);

    StdOut.print("pattern: ");
    for (int i = 0; i < offset1; i++) StdOut.print(" ");
    StdOut.println(pat);

    StdOut.print("pattern: ");
    for (int i = 0; i < offset2; i++) StdOut.print(" ");
    StdOut.println(pat);
  }
Ejemplo n.º 28
0
  // merge together the sorted input streams and write the sorted result to standard output
  private static void merge(In[] streams) {
    int N = streams.length;
    IndexMinPQ<String> pq = new IndexMinPQ<String>(N);
    for (int i = 0; i < N; i++) if (!streams[i].isEmpty()) pq.insert(i, streams[i].readString());

    // Extract and print min and read next from its stream.
    while (!pq.isEmpty()) {
      StdOut.print(pq.minKey() + " ");
      int i = pq.delMin();
      if (!streams[i].isEmpty()) pq.insert(i, streams[i].readString());
    }
    StdOut.println();
  }
Ejemplo n.º 29
0
  /** Unit test. */
  public static void main(String[] args) {
    int N = Integer.parseInt(args[0]);
    if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
    double[] t = {.5, .3, .1, .1};

    StdOut.println("seed = " + StdRandom.getSeed());
    for (int i = 0; i < N; i++) {
      StdOut.printf("%2d ", uniform(100));
      StdOut.printf("%8.5f ", uniform(10.0, 99.0));
      StdOut.printf("%5b ", bernoulli(.5));
      StdOut.printf("%7.5f ", gaussian(9.0, .2));
      StdOut.printf("%2d ", discrete(t));
      StdOut.println();
    }

    String[] a = "A B C D E F G".split(" ");
    for (String s : a) StdOut.print(s + " ");
    StdOut.println();
  }
Ejemplo n.º 30
0
  public static void main(String[] args) {
    In in = new In(args[0]);
    int s = Integer.parseInt(args[1]);
    EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);

    AcyclicLP lp = new AcyclicLP(G, s);

    for (int v = 0; v < G.V(); v++) {
      if (lp.hasPathTo(v)) {
        StdOut.printf("%d to %d (%.2f)  ", s, v, lp.distTo(v));
        for (DirectedEdge e : lp.pathTo(v)) {
          StdOut.print(e + "   ");
        }
        StdOut.println();
      } else {
        StdOut.printf("%d to %d         no path\n", s, v);
      }
    }
  }