1.2 数据抽象(Part 1 -- Exercises)

State: Done!


Tips

  1. IDEA中Program arguments 一栏添入的是所需要的命令行参数,以第一题为例,需要参数100,则在该栏中直接输入100,然后Apply->OK即可,运行时IDE会直接导入。
  2. You can get lib algs.jar for 《Algorithm_4e》from the official website.

第一题

package com.chenswe;

/**
 * Created by chen_swe on 3/9/16.
 */

import edu.princeton.cs.algs4.*;
import java.util.Vector;

public class practice {

    public static void drawPoint(double x,double y){
        for(int i = 0; i < 26; i+=5){
            StdDraw.circle(x,y,i*1e-4);
        }
    }

    public static void main(String[] args){

        String str = args[0].toString();

        int num = Integer.valueOf(str);
        Vector<Point2D> vector = new Vector<>();

        for(int i = 0; i < num; ++i){
            double x = StdRandom.uniform();
            double y = StdRandom.uniform();

            drawPoint(x,y);

            Point2D point = new Point2D(x,y);
            vector.add(point);
        }

        if(vector.size() > 1){
            double minDistance = Double.MAX_VALUE;
            Point2D point1 = null;
            Point2D point2 = null;

            for(int i = 0; i < vector.size(); ++i){
                for(int j = i+1; j < vector.size(); ++j){
                    double tmpDistance = vector.elementAt(i).distanceTo(vector.elementAt(j));
                    if(minDistance > tmpDistance){
                        minDistance = tmpDistance;
                        point1 = vector.elementAt(i);
                        point2 = vector.elementAt(j);
                    }
                }
            }

            System.out.printf("The shortest distance is %.4f %nbetween (%.4f, %.4f) and  (%.4f, %.4f)%n",
                            minDistance,point1.x(),point1.y(),point2.x(),point2.y());
        }
        else{
            System.out.println("The point number is less than 2!");
        }
    }
}

第二题

package com.chenswe;

/**
 * Created by chen_swe on 3/10/16.
 */

import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.StdRandom;
import java.io.*;
import java.util.Vector;

public class practice {
    public static final int MAXN = 10;

    public static void main(String[] args) throws IOException{

        try(DataOutputStream out = new DataOutputStream(
                new FileOutputStream("Data.txt"))){

            for (int i = 0; i < MAXN; ++i) {
                double tmp= StdRandom.uniform(1.0,10.0);
                out.writeDouble(tmp);
            }

        }catch (FileNotFoundException x){
            System.err.println("%s not found!" + x);
        }

       Vector<Interval1D> vector = new Vector<>();

        try (DataInputStream in = new DataInputStream(
               new FileInputStream("Data.txt"))){

           int num = Integer.valueOf(args[0].toString());

           for (int i = 0; i < num + 1; ++i) {
               double temp1 = in.readDouble();
               double temp2 = in.readDouble();
               double left = temp1 > temp2 ? temp2 : temp1;
               double right = temp1 + temp2 - left;
               Interval1D interval = new Interval1D(left, right);
               vector.add(interval);
           }

        }catch (EOFException x) {
           if (vector.size() < 2) {
               System.err.println("The number of interval is less than 2!");
           } else {
               for (int i = 0; i < vector.size(); ++i) {
                   Interval1D interval1 = vector.elementAt(i);
                   for (int j = i + 1; j < vector.size(); ++j) {
                       Interval1D interval2 = vector.elementAt(j);
                       if (interval1.intersects(interval2)) {
                           System.out.printf(
                                   "[%.4f,%.4f] and [%.4f,%.4f] " +
                                           "have a intersects part!%n",
                                   interval1.left(), interval1.right(),
                                   interval2.left(), interval2.right());
                       }
                   }
               }
           }
       }
    }
}

第三题

package com.chenswe;

/**
 * Created by chen_swe on 3/10/16.
 */

import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.Interval2D;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdRandom;
import java.io.*;
import java.util.Vector;

public class practice {

    /**
     * Function: 处理Interval2D的toString()返回的字符串中获取浮点数
     * Parameter(String str): Interval2D实例所生成的字符串  
     * Return(String[]): 得到4个以字符串表示的双精度浮点数
     */
    public static String[] handle(String str){
        String[] result = new String[4];
        int index1 = str.indexOf("[") + 1;
        int index2 = str.indexOf(",");
        result[0] = str.substring(index1,index2);

        index1 = index2 + 1; index2 = str.indexOf("]");
        result[1] = str.substring(index1,index2);

        index1 = str.lastIndexOf("[") + 1; index2 = str.lastIndexOf(",");
        result[2] = str.substring(index1,index2);

        index1 = index2 + 1; index2 = str.lastIndexOf("]");
        result[3] = str.substring(index1,index2);

        return result;
    }

    /**
     * Function: 判断两个Interval2D实例是否有包含关系
     * Parameter: 两个Interval2D实例 
     * Return: true - 如果有包含关系;false - 如果没有。
     */
    public static boolean isContain(Interval2D first, Interval2D second){
        String[] strFirst = handle(first.toString());
        String[] strSecond = handle(second.toString());

        Point2D firstVertex1 = new Point2D(Double.parseDouble(strFirst[0]),Double.parseDouble(strFirst[2]));
        Point2D firstVertex2 = new Point2D(Double.parseDouble(strFirst[1]),Double.parseDouble(strFirst[3]));

        Point2D secondVertex1 = new Point2D(Double.parseDouble(strSecond[0]),Double.parseDouble(strSecond[2]));
        Point2D secondVertex2 = new Point2D(Double.parseDouble(strSecond[1]),Double.parseDouble(strSecond[3]));

        if(first.contains(secondVertex1) && first.contains(secondVertex2))      return true;
        else if(second.contains(firstVertex1) && second.contains(firstVertex2)) return true;
        else                                                                    return false;
    }

    public static void main(String[] args){

        double num = Double.valueOf(args[0]);
        double min = Double.valueOf(args[1]);
        double max = Double.valueOf(args[2]);
        Vector<Interval2D> vector = new Vector<>();
        for (int i = 0; i < num; ++i) {
            double[] temp = new double[4];
            Interval1D[] intervals = new Interval1D[2];

            for(int j = 0; j < 4; ++j)
                temp[j] = StdRandom.uniform(min,max);
            for(int k = 0; k < 2; ++k){
                double left = temp[k*2] > temp[k*2+1] ? temp[k*2+1] : temp[k*2];
                double right = temp[k*2] + temp[k*2+1] - left;
                intervals[k] = new Interval1D(left, right);
            }

            Interval2D interval2D = new Interval2D(intervals[0],intervals[1]);
            interval2D.draw();

            vector.add(interval2D);
        }

        int numInterval = 0;
        int numContain = 0;
        for(int i = 0; i < num; ++i){
            Interval2D first = vector.elementAt(i);
            for(int j = i+1; j < num; ++j){
                Interval2D second = vector.elementAt(j);
                if(first.intersects(second))
                    ++numInterval;
                if(isContain(first,second)){
                    ++numContain;
                }
            }
        }

        System.out.println("numInterval = [" + numInterval + "]");
        System.out.println("numContain = [" + numContain + "]");
    }
}

第四题

world
hello

第六题

package com.chenswe;

/**
 * Created by chen_swe on 3/10/16.
 */

public class practice {
    public static void main(String[] args){
        String str1 = args[0];
        String str2 = args[1];

        int index = -1;
        while((index = str2.indexOf(str1.charAt(0),index + 1)) != -1) {
            String tmp = str2.substring(index) + str2.substring(0, index);
            if (str1.equals(tmp)) {
                System.out.println("[" + str1 + "] is [" + str2 + "]'s circular rotation!");
                return;
            }
        }
        System.out.println("[" + str1 + "] is't [" + str2 + "]'s circular rotation!");
    }
}

第七题

原字符串的逆序

第九题

Tips:这道题可能是我想的太简单了,参考须谨慎!

BinarySearch.java

package com.chenswe;

/**
 * Created by chen_swe on 3/10/16.
 */

/******************************************************************************
 *  Compilation:  javac BinarySearch.java
 *  Execution:    java BinarySearch whitelist.txt < input.txt
 *  Dependencies: In.java StdIn.java StdOut.java
 *  Data files:   http://algs4.cs.princeton.edu/11model/tinyW.txt
 *                http://algs4.cs.princeton.edu/11model/tinyT.txt
 *                http://algs4.cs.princeton.edu/11model/largeW.txt
 *                http://algs4.cs.princeton.edu/11model/largeT.txt
 *
 *  % java BinarySearch tinyW.txt < tinyT.txt
 *  50
 *  99
 *  13
 *
 *  % java BinarySearch largeW.txt < largeT.txt | more
 *  499569
 *  984875
 *  295754
 *  207807
 *  140925
 *  161828
 *  [367,966 total values]
 *
 ******************************************************************************/

import edu.princeton.cs.algs4.Counter;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

import java.util.Arrays;

/**
 *  The <tt>BinarySearch</tt> class provides a static method for binary
 *  searching for an integer in a sorted array of integers.
 *  <p>
 *  The <em>rank</em> operations takes logarithmic time in the worst case.
 *  <p>
 *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/11model">Section 1.1</a> of
 *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public class BinarySearch {

    /**
     * This class should not be instantiated.
     */
    private BinarySearch() { }

    /**
     * Returns the index of the specified key in the specified array.
     *
     * @param  a the array of integers, must be sorted in ascending order
     * @param  key the search key
     * @return index of key in array <tt>a</tt> if present; <tt>-1</tt> otherwise
     */
    public static int indexOf(int[] a, int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if      (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }

    /**
     * Returns the index of the specified key in the specified array.
     * This function is poorly named because it does not give the <em>rank</em>
     * if the array has duplicate keys or if the key is not in the array.
     *
     * @param  key the search key
     * @param  a the array of integers, must be sorted in ascending order
     * @return index of key in array <tt>a</tt> if present; <tt>-1</tt> otherwise
     * @deprecated Replaced by {@link #indexOf(int[], int)}.
     */
    public static int rank(int key, int[] a, Counter counter) {
        counter.increment();
        return indexOf(a, key);
    }

    /**
     * Reads in a sequence of integers from the whitelist file, specified as
     * a command-line argument; reads in integers from standard input;
     * prints to standard output those integers that do <em>not</em> appear in the file.
     */
    public static void main(String[] args) {

        // read the integers from a file
        In in = new In(args[0]);
        int[] whitelist = in.readAllInts();

        // sort the array
        Arrays.sort(whitelist);

        // read integer key from standard input; print if not in whitelist
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (BinarySearch.indexOf(whitelist, key) == -1)
                StdOut.println(key);
        }
    }
}

/******************************************************************************
 *  Copyright 2002-2015, Robert Sedgewick and Kevin Wayne.
 *
 *  This file is part of algs4.jar, which accompanies the textbook
 *
 *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
 *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
 *      http://algs4.cs.princeton.edu
 *
 *
 *  algs4.jar is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  algs4.jar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.
 ******************************************************************************/

practice.java

package com.chenswe;

import edu.princeton.cs.algs4.Counter;

/**
 * Created by chen_swe on 3/10/16.
 */

public class practice {
    public static void main(String[] args){
        Counter counter = new Counter("Times");

        /**
         * ...BinarySearch.rank();多次调用
         */

        System.out.println("Total = [" + counter + "]");
    }
}

第十题

Tips:异常处理部分可能不够规范!

package com.chenswe;

/**
 * Created by chen_swe on 3/11/16.
 */

import edu.princeton.cs.algs4.StdDraw;

public class VisualCounter{
    private int count = 0;
    private int numOperate = 0;
    private final int MAX_NUM_OPE;
    private final int MAX_ABSOLUTE;

    /**
     *
     * @param maxNumOpe The maximum number of operations
     * @param maxAbsolute The maximum absolute value of the counter
     */
    public VisualCounter(int maxNumOpe,int maxAbsolute){
        MAX_NUM_OPE = maxNumOpe;
        MAX_ABSOLUTE = maxAbsolute;
    }

    /**
     * throw this Exception when
     * numOperate is bigger than MAX_NUM_OPE
     */
    class ExceedLimitedOperationTimesException extends Exception{}

    /**
     * throw this Exception when
     * the absolute value of count is bigger than MAN_ABSOLUTE
     */
    class IllegalValueOfCount extends Exception{}

    /**
     * increase the Counter
     *
     * @throws IllegalValueOfCount
     * @throws ExceedLimitedOperationTimesException
     */
    public void increment() throws IllegalValueOfCount,
            ExceedLimitedOperationTimesException{
        if(numOperate < MAX_NUM_OPE){
            ++count;
            ++numOperate;
            drawCounter();
        }else
            throw new ExceedLimitedOperationTimesException();
        if(Math.abs(count) > MAX_ABSOLUTE)
            throw new IllegalValueOfCount();
    }

    /**
     * decrease the Counter
     *
     * @throws IllegalValueOfCount
     * @throws ExceedLimitedOperationTimesException
     */
    public void decrease() throws IllegalValueOfCount,
            ExceedLimitedOperationTimesException{
        if(numOperate < MAX_NUM_OPE){
            --count;
            ++numOperate;
            drawCounter();
        }else{
            throw new ExceedLimitedOperationTimesException();
        }
        if(Math.abs(count) > MAX_ABSOLUTE)
            throw new IllegalValueOfCount();
    }

    /**
     * Draw this Counter in a Standard Draw Window
     */
    public void drawCounter(){
        double tmp = count;
        while(tmp >= 1){
            tmp /= 10;
        }
        StdDraw.clear();
        StdDraw.setPenColor(StdDraw.RED);
        StdDraw.setPenRadius(.05);
        StdDraw.line(.5,0,.5,tmp);
        StdDraw.text(.5,tmp + 0.05,String.valueOf(count));
    }

    public static void main(String[] args) throws IllegalValueOfCount,
            ExceedLimitedOperationTimesException{

        int maxNumOpe = Integer.parseInt(args[0]);
        int maxAbsolute = Integer.parseInt(args[1]);

        VisualCounter counter = new VisualCounter(maxNumOpe,maxAbsolute);
        for(int i = 0; i < 20; ++i)
            counter.increment();
        for(int i = 0; i < 20; ++i)
            counter.decrease();
    }
}

第十一题

官网提供的库中Date类可满足要求,不需要重新实现SmartDate

第十二题

Tips: I’m not sure what Sedgewick wants, so I took advantage of API Documents to implement the method dayOfTheWeek()

package com.chenswe;

import edu.princeton.cs.algs4.Date;
import java.time.LocalDate;

/**
 * Created by chen_swe on 3/11/16.
 */
public class SmartDate extends Date {
    public SmartDate(int month, int day, int year){
        super(month,day,year);
    }

    /**
     * 
     * @return a string of dayOfTheWeek
     *         For example, FRIDAY,SUNDAY...
     */
    public static String dayOfTheWeek(){
        return LocalDate.now().getDayOfWeek() + "";
    }

    public static void main(String[] args) {
        System.out.println("dayofTheWeek = [" + dayOfTheWeek() + "]");
    }

}

第十三 & 十四题

Tips:You can refer to the Transaction.java directly

package com.chenswe;

import edu.princeton.cs.algs4.Date;

/**
 * Created by chen_swe on 3/11/16.
 */
public class Transaction {
    private final String name;
    private final Date date;
    private final double amount;

    public Transaction(String name,Date date, double amount)
            throws IllegalArgumentException{

        this.name = name;
        this.date = date;
        this.amount = amount;
        if(Double.isNaN(amount) || Double.isInfinite(amount))
            throw new IllegalArgumentException(amount + " is NaN or is infinite!");
    }

    /**
     * Returns the name of the customer involved in this transaction.
     *
     * @return the name of the customer involved in this transaction.
     */
    public String who(){return name;}

    /**
     * Returns the date of this transaction.
     *
     * @return the date of this transaction
     */
    public Date when(){return date;}

    /**
     * Returns the amount of this transaction.
     *
     * @return the amount of this transaction
     */
    public double amount() {return amount;}

    /**
     * Returns a string representation of this transaction.
     *
     * @return a string representation of this transaction
     */
    public String toString(){
        String str = "[" + name + "] had an [$" + amount + "]'s transaction " +
                "at [" + date + "]";
        return str;
    }

    /**
     * Compares this transaction to the specified object.
     *
     * @param  other the other transaction
     * @return true if this transaction is equal to <tt>other</tt>; false otherwise
     */
    public boolean equals(Object other){
        if(this == other)   return true;
        if(other == null)   return false;
        if(this.getClass() != other.getClass())     return false;

        Transaction that = (Transaction)other;
        if(!this.date.equals(that.date))            return false;
        if(this.name != that.name)                  return false;
        if(Math.abs(this.amount - that.amount) > 1e-5)
            return false;
        return true;
    }
    public static void main(String[] args) {
        Transaction transaction = new Transaction("Stefen",new Date(3,11,2016),100);
        System.out.println(transaction.toString());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值