1.2CREATIVE PROBLEMS

1.2.15 File input. Develop a possible implementation of the static readInts() method from In (which we use for various test clients, such as binary search on page 47) that is based on the split() method in String.
import edu.princeton.cs.algs4.In;

public class E1215 {
    public static int[] readInts(String name) {
        In in = new In(name);
        String input = in.readAll();
        String[] words = input.split("\\s+");//空格分隔
        int[] ints = new int[words.length];
        for(int i = 0; i < words.length;i++)
            ints[i] = Integer.parseInt(words[i]);
        return ints;
    }
    public static void main(String[] args) {
        int[] ints;
        ints = readInts("test.txt");
        for(int i = 0; i < ints.length;i++)
            System.out.println(ints[i]);
    }
}
1.2.16 Rational numbers. Implement an immutable data type Rational for rational numbers that supports addition, subtraction, multiplication, and division.
1.2.17 Robust implementation of rational numbers. Use assertions to develop an implementation of Rational (see Exercise 1.2.16) that is immune to overflow.
public class E1216_17 {
    public static class Rational{
        private int numerator;//分子
        private int denominator;//分母
        public Rational(int numerator,int denominator){
            if(denominator == 0)
                throw new ArithmeticException("denominator is zero");
            this.numerator = numerator;
            this.denominator = denominator;
        }

        public Rational plus(Rational that) {
            assert isPlusOverflow(this.numerator * that.denominator , this.denominator * that.numerator):"plus overflow";
            assert isTimesOverflow(this.denominator , that.denominator):"times overflow";
            int newNumerator = this.numerator * that.denominator + this.denominator * that.numerator;
            int newDenominator = this.denominator * that.denominator;
            int gcdNum = gcd(newNumerator, newDenominator);
            if (gcdNum != 1)
            {
                newNumerator /= gcdNum;
                newDenominator /= gcdNum;
            }
            return new Rational(newNumerator, newDenominator);
        }
        public Rational minus(Rational that) {
            Rational newthat = new Rational(-that.numerator, that.denominator);
            return this.plus(newthat);
        }
        public Rational times(Rational that) {
            assert isTimesOverflow(this.denominator, that.denominator):"times overflow";
            assert isTimesOverflow(this.numerator, that.numerator):"times overflow";
            int newNumerator = this.numerator * that.numerator;
            int newDenominator = this.denominator * that.denominator;
            int gcdNum = gcd(newNumerator, newDenominator);
            if (gcdNum != 1)
            {
                newNumerator /= gcdNum;
                newDenominator /= gcdNum;
            }
            return new Rational(newNumerator, newDenominator);
        }
        public Rational divides(Rational that) {
            Rational newthat = new Rational(that.denominator, that.numerator);
            return this.times(newthat);
        }

        public boolean equals(Rational that) {
            return (this.numerator == that.numerator && this.denominator == that.denominator);
        }

        public String toString(){
            if (this.denominator == 1)  return this.numerator + "";
            return this.numerator + "/" + this.denominator;
        }
        //欧几里得算法确保输入的分子、分母互质
        private static int gcd(int numerator,int denominator) {
            if (denominator == 0) return numerator;
            int r = numerator % denominator;
            return gcd(denominator, r);
        }
        //加法溢出
        private boolean isPlusOverflow(int a,int b)
        {
            if(a > 0 && b > 0)  return !(a + b < 0);
            if(a < 0 && b < 0)  return !(a + b > 0);
            return true;
        }
        //乘法溢出
        private boolean isTimesOverflow(int a,int b) {
            if (a < 0)  a = -a;
            if (b < 0)  b = -b;
            if(a == 0 || b == 0)    return true;
            return !(a * b < 0);
        }
    }
    public static void main(String[] args) {
        Rational a = new Rational(1,1);
        Rational b = new Rational(3,-4);
        //a与b之和
        System.out.println(a.plus(b));
        //a与b之差
        System.out.println(a.minus(b));
        //a与b之积
        System.out.println(a.times(b));
        //a与b之商
        System.out.println(a.divides(b));
        //a与b是否相等
        System.out.println(a.equals(b));
        //对象的字符串表示
        System.out.println(a);
    }
}
1.2.18 Variance for accumulator. Validate that the following code, which adds the methods var() and stddev() to Accumulator, computes both the mean and variance of the numbers presented as arguments to addDataValue().
public class E1218 {
    public static class Accumulator{
        private double m;
        private double s;
        private int N;
        public void addDataValue(double x) {
            N++;
            s = s + 1.0 * (N-1) / N * (x - m);
            m = m + (x - m) / N;
        }
        public double mean() {
            return m;
        }
        public double var() {
            return s / (N - 1);
        }
        public double stddev() {
            return Math.sqrt(this.var());
        }
        @Override
        public String toString() {
            return "Mean (" + N + " values ):"
                    + String.format("%7.5f",mean())
                    + " var : " + var()
                    + " stddev :" + stddev();
        }
    }
    public static void main(String[] args) {
        Accumulator X = new Accumulator();
        X.addDataValue(1);
        System.out.println(X);
        X.addDataValue(2);
        System.out.println(X);
        X.addDataValue(3);
        System.out.println(X);
    }
}
1.2.19 Parsing. Develop the parse constructors for your Date and Transaction implementations of Exercise 1.2.13 that take a single String argument to specify the initialization values.
import edu.princeton.cs.algs4.Date;

public class E1213and1214 {
    public static class Transaction {
        private String who;
        private Date when;
        private double amount;
        public Transaction(String who,Date when,double amount)
        {
            this.who = who;
            this.when = when;
            this.amount = amount;
        }
        public Transaction(String information){
            String[] info = information.split("\\s");
            this.who = info[0];
            this.when = new Date(info[1]);
            this.amount = Double.parseDouble(info[2]);
        }
        
        public String getwho() {
            return this.who;
        }

        public Date getwhen() {
            return this.when;
        }

        public double getamount() {
            return this.amount;
        }
        @Override
        public String toString() {
            return this.who + " " + this.when + " " + this.amount;
        }
        //1.2.14
        @Override
        public boolean equals(Object other) {
            if (other == this) return true;
            if (other == null) return false;
            if (other.getClass() != this.getClass()) return false;
            Transaction that = (Transaction) other;
            return (this.who == that.who) && (this.when == that.when) && (this.amount == that.amount);
        }
    }
    public static void main(String[] args) {
        Date date = new Date(8,8,2021);
        Transaction transaction1 = new Transaction("张三",date,11.12);
        Transaction transaction2 = new Transaction("李四",date ,11.12);
        if (transaction2.equals(transaction1)) System.out.println("true");
        else System.out.println("false");
        Transaction transaction3 = new Transaction("Turing 5/22/1939 11.99");
        System.out.println(transaction3);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值