📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
12
返回列表 发新帖
楼主: hurricane_e
跳转到指定楼层
上一主题 下一主题
收起左侧

[CS61B_Spring 2015] HW2

🔗
Casualet 2015-7-18 22:21:58 | 只看该作者
全局:
CalculatorTest.java
/*
刚开始没想法,跳过了;后来自己写加法的的时候想到了用正数和负数测试,解决。
*/
public class CalculatorTest {
    /* Do not change this to be private. For silly testing reasons it is public. */
    public Calculator tester;

    /**
     * setUp() performs setup work for your Calculator.  In short, we
     * initialize the appropriate Calculator for you to work with.
     * By default, we have set up the Staff Calculator for you to test your
     * tests.  To use your unit tests for your own implementation, comment
     * out the StaffCalculator() line and uncomment the Calculator() line.
     **/
    @Before
    public void setUp() {
//        tester = new StaffCalculator(); // Comment me out to test your Calculator
         tester = new Calculator();   // Un-comment me to test your Calculator
    }

    // TASK 1: WRITE JUNIT TESTS
    // YOUR CODE HERE
    @Test
    public void testAdd(){
       int value;
       value=tester.add(5,7);
       assertEquals(12,value);

       value=tester.add(-5,7);
       assertEquals(2,value);
   
       value=tester.add(5,-7);
       assertEquals(-2,value);
  
       value=tester.add(-5,-7);
       assertEquals(-12,value);

       value= tester.add(value,-10);              
       assertEquals(-22,value);

       value=tester.add(10000,10000);
       assertEquals(20000,value);

    }
    @Test
    public void testMul(){
       int value;
       value=tester.multiply(2,2);
       assertEquals(4,value);
       value=tester.multiply(-2,-2);
       assertEquals(4,value);
       value=tester.multiply(2,-2);
       assertEquals(-4,value);
       value=tester.multiply(2,-2);
       assertEquals(-4,value);     

    }

    /* Run the unit tests in this file. */
    public static void main(String... args) {
        jh61b.junit.textui.runClasses(CalculatorTest.class);
    }      
}

Calculator.java
/*
想到了用真值表来实现,其他部分为链表的操作。
*/

import list.EquationList;//this is how to import !!!
public class Calculator {
    // YOU MAY WISH TO ADD SOME FIELDS
    EquationList historyHead;   
   
    public Calculator(){
        this.historyHead=new EquationList(null,-1,null);

    }

    public class record{
      public EquationList cur;
      public record pre;
    }



    /**
     * TASK 2: ADDING WITH BIT OPERATIONS
     * add() is a method which computes the sum of two integers x and y using
     * only bitwise operators.
     * @param x is an integer which is one of two addends
     * @param y is an integer which is the other of the two addends
     * @return the sum of x and y
     **/
    public int add(int x, int y) {
        // YOUR CODE HERE
        int result=0;
        int add=0;
        int xBit,yBit,curBit;
        for(int i=0;i<=31;i++){
           xBit=this.getBit(x,i);
           yBit=this.getBit(y,i);
        //   if(xBit==-1||yBit==-1) System.out.println(".......");
  
           curBit=this.truth(xBit,yBit,add);
        //   if(curBit==-1) System.out.println("error");               

           add=curBit>>1;
           curBit=curBit&1;

           result=result|(curBit<<i);
        }
        return result;
    }
    int n=0;
    public int truth(int a1,int a2,int add){
      n++;
//      System.out.println(""+n+"a1: "+a1+" a2: "+a2+" add: "+add);
      if(a1==0&&a2==0&&add==0)
          return 0;
      if(a1==0&&a2==0&&add==1)
          return 1;
      if(a1==0&&a2==1&&add==0)
          return 1;
      if(a1==0&&a2==1&&add==1)
          return 2;
      if(a1==1&&a2==0&&add==0)
          return 1;
      if(a1==1&&a2==0&&add==1)
          return 2;
      if(a1==1&&a2==1&&add==0)
          return 2;
      if(a1==1&&a2==1&&add==1)
          return 3;

      return -1;//this is helpful, java ensures that the method do has a return value
    }

    public int getBit(int x, int index){
          int i=1;
          return (x&(i<<index))>>>index;//a single bit and an int num are not identical!!!
    }




    /**
     * TASK 3: MULTIPLYING WITH BIT OPERATIONS
     * multiply() is a method which computes the product of two integers x and
     * y using only bitwise operators.
     * @param x is an integer which is one of the two numbers to multiply
     * @param y is an integer which is the other of the two numbers to multiply
     * @return the product of x and y
     **/
    public int multiply(int x, int y) {
        // YOUR CODE HERE
        int result=0;
        int modifier;
        if(x==0||y==0) return 0;

        if(x<0&&y<0){
             x=-x;
             y=-y;//is this operation allowed?
             modifier=0;
         }else if(x<0&&y>0){
            x=-x;
            modifier=1;
         }else if(x>0&&y<0){
           y=-y;
           modifier=1;
         }else{
           modifier=0;
         }         
         int t;   
        for(int i=0;i<=31;i++){
            t=(y>>i)&1;
            if(t==0) continue;  
            result=this.add(x<<i,result);
        }

        return modifier==0?result:-result;
    }

    /**
     * TASK 5A: CALCULATOR HISTORY - IMPLEMENTING THE HISTORY DATA STRUCTURE
     * saveEquation() updates calculator history by storing the equation and
     * the corresponding result.
     * Note: You only need to save equations, not other commands.  See spec for
     * details.
     * @param equation is a String representation of the equation, ex. "1 + 2"
     * @param result is an integer corresponding to the result of the equation
     **/
    public void saveEquation(String equation, int result) {
        // YOUR CODE HERE
        EquationList tempHis=this.historyHead;
        while(historyHead.next!=null){
             historyHead=historyHead.next;
        }
        EquationList temp=new EquationList(equation,result,null);
        historyHead.next=temp;
        this.historyHead=tempHis;
        //System.out.println(this.historyHead.equation)  
//        printList();
    }
   
    public void printList(){

        System.out.println("now its time to print out the equation list");
        EquationList pr=this.historyHead;
        while(pr.next!=null){
            System.out.println(pr.equation);
            pr=pr.next;
        }

    }
//when traversing a list, remember to add xx=xx.next. or you will have
//infinite loop

    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     * printAllHistory() prints each equation (and its corresponding result),
     * most recent equation first with one equation per line.  Please print in
     * the following format:
     * Ex   "1 + 2 = 3"
     **/
    public void printAllHistory() {
        // YOUR CODE HERE
        int count=0;
        EquationList temp=this.historyHead;
        while(temp.next!=null){
           count++;
           temp=temp.next;
        }
        printHistory(count);
      
    }
// how to write printAllHistory in an recursive way??
    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     * printHistory() prints each equation (and its corresponding result),
     * most recent equation first with one equation per line.  A maximum of n
     * equations should be printed out.  Please print in the following format:
     * Ex   "1 + 2 = 3"
     **/
    public void printHistory(int n) {//how to reversely print items in a single linked list?
        // YOUR CODE HERE
        EquationList temp=this.historyHead;
        record re;
        record rTemp=new record();
        record rrTemp;
        rTemp.pre=null;
        rTemp.cur=this.historyHead;
        while(historyHead.next!=null){                 
             historyHead=historyHead.next;
             rrTemp=new record();
             rrTemp.pre=rTemp;
             rrTemp.cur=historyHead;
             rTemp=rrTemp;
        }
      
       // System.out.println(historyHead.equation+'='+historyHead.result);
        int count=0;
        while(rTemp.pre!=null&&count<n){
             historyHead=rTemp.cur;
             System.out.println(historyHead.equation+'='+historyHead.result);
             rTemp=rTemp.pre;
             count++;
        }  
        this.historyHead=temp;
    }   

    /**
     * TASK 6: CLEAR AND UNDO
     * undoEquation() removes the most recent equation we saved to our history.
    **/
    public void undoEquation() {
        // YOUR CODE HERE
       EquationList temp=this.historyHead;
       while(temp.next.next!=null){
           temp=temp.next;
        }
        temp.next=null;

    }

    /**
     * TASK 6: CLEAR AND UNDO
     * clearHistory() removes all entries in our history.
     **/
    public void clearHistory() {
        // YOUR CODE HERE
        this.historyHead=new EquationList(null,-1,null);
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeSum() computes the sum over the result of each equation in our
     * history.
     * @return the sum of all of the results in history
     **/
    public int cumulativeSum() {
        // YOUR CODE HERE
        EquationList temp=this.historyHead.next;
        int result=0;
        while(temp!=null){
            result+=temp.result;
            temp=temp.next;
        }

        return result;
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeProduct() computes the product over the result of each equation
     * in history.
     * @return the product of all of the results in history
     **/
    public int cumulativeProduct() {
        // YOUR CODE HERE
        EquationList temp=this.historyHead.next;
        int result=1;
        while(temp!=null){//remember to differeciate between temp!=null and
                          //temp.next!=null, when used as test condition
          result*=temp.result;
          temp=temp.next;
        }
        return result;
    }
}
Calculator.java
public class CalculatorUI{
   public static void main(String[] args){
         String first;
         Calculator tester=new Calculator();
         while(true){
           System.out.println(">");
           first=StdIn.readString();
        switch(first){
        case "quit": break;
        case "history":{
              int n=StdIn.readInt();
              tester. printHistory(n);                        
              break;
          }
        case "dump":{
             tester.printAllHistory();
             break;
         }
        case "undo":{
            tester.undoEquation();
            break;
        }
        case "clear":{
            tester.clearHistory();
            break;
       }
        case "sum":{
            int re=tester.cumulativeSum();
            System.out.println(re);
            break;
        }
        case "product":{
            int re=tester.cumulativeProduct();
            System.out.println(re);
            break;//always remember to break;
        }
        default:{
           int n1=Integer.parseInt(first);
           int result;
           String operation=StdIn.readString();//not char
           int n2=StdIn.readInt();
           if(operation.equals("+")){
              result=tester.add(n1,n2);
              tester.saveEquation(n1+" + "+n2,result);
           }
          else if(operation.equals("*")){
              result=tester.multiply(n1,n2);
              tester.saveEquation(n1+" * "+n2,result);
           }else{

              result=-7;

           }
           System.out.println(result);
        }
        }
      }
   }
}

/*
工作空隙时间写了好久。。。如果这是基础入门课,那我肯定挂科了=_=
*/
回复

使用道具 举报

🔗
HNAKXR 2016-1-30 17:23:40 | 只看该作者
全局:
位运算来写加法和乘法不容易,加法还好,乘法涉及负数有时出错,找不出问题,没办法只能先当成正数算再考虑符号。






最后一个task传不上图了(只能5张):
***-MacBook-Pro:hw2 ***$ java StaffCalculatorUI
> 1 + -5
-4
> 3 * -7
-21
> 5 + 8
13
> -4 * 16
-64
> sum
-76
> product
-69888
>
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表