Bag Sample
Compute the average and simple standard deviation of the double values on standard input
public class Stats { public static void main (String[] args) { Bagnumbers = new Bag (); while(!StdIn.isEmpty) numbers.add(StdIn.readDouble()); int N = numbers.size(); double sum = 0.0; for (double x : numbers) sum += x; double mean = sum/N; sum = 0.0; for (double x : numbers) sum += (x-mean)*(x-mean); double std = Math.sqrt(sum/(N-1)); StdOut.printf("Mean: %.2f\n", mean); StdOut.printf("Std dev: %.2f\n", std); }}
FIFO Queues
Sample queue client
public static int[] readInts (String name) { In in = new In(name); Queueq = new Queue (); while(!in.isEmpty()) q.enqueue(in.readInt()); int N = q.size(); int[] a = new int[N]; for(int i = 0; i < N; i++) a[i] = q.dequeue(); return a;}
LIFO Stacks
Sample stack client
public class Reverse { public static void main (String[] args) { Stackstack = new Stack (); while(!StdIn.isEmpty()) stack.push(StdIn.readIn()); for(int i : stack) StdOut.println(i); }}
Dijkstra's Two-Stack Algorithm for Expression Evaluation
public class evaluate { public static void main(String[] args) { Stackops = new Stack (); Stack vals = new Stack (); while (!StdIn.isEmpty){ String s = StdIn.readString(); if (s.equals("(")); else if (s.equals("+")) ops.push(s); else if (s.equals("-")) ops.push(s); else if (s.equals("*")) ops.push(s); else if (s.equals("/")) ops.push(s); else if (s.equals(")")) ops.push(s); else if (s.equals("sqrt")) ops.push(s); else if (s.equals(")")) { String op = ops.pop(); Double v = vals.pop(); if (op.equals("+")) v = vals.pop() + v; else if (op.equals("-")) v = vals.pop() - v; else if (op.equals("*")) v = vals.pop() * v; else if (op.equals("/")) v = vals.pop() / v; else if (op.equals("sqrt")) v = Math.sqrt(v); vals.push(v); } else vals.push(Double.parseDouble(s)); } StdOut.println(vals.pop()); } }