• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Icy.warrior
博客园    首页    新随笔    联系   管理    订阅  订阅
【第五天打卡。

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) {
        Bag<Double> numbers = new Bag<Double>();
        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);
 
    }
}
View Code

FIFO Queues

Sample queue client

public static int[] readInts (String name) {
    In in = new In(name);
    Queue<Integer> q = new Queue<Integer>();
    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;
}
View Code

LIFO Stacks

Sample stack client

public class Reverse {
    public static void main (String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        while(!StdIn.isEmpty()) 
            stack.push(StdIn.readIn());
        for(int i : stack)
            StdOut.println(i);
    }
}
View Code

Dijkstra's Two-Stack Algorithm for Expression Evaluation

public class evaluate {
    public static void main(String[] args) {
        Stack<String> ops = new Stack<String>();
        Stack<Double> vals = new Stack<Double>();
        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());
    }    
}
View Code

 

posted on 2017-08-09 16:33  Icy.warrior  阅读(107)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3