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
*/publicclassBinarySearch {/**
* This class should not be instantiated.
*/privateBinarySearch() { }
/**
* 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
*/publicstaticintindexOf(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;
elseif (key > a[mid]) lo = mid + 1;
elsereturn 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)}.
*/publicstaticintrank(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.
*/publicstaticvoidmain(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 whitelistwhile (!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.
*/publicclasspractice {publicstaticvoidmain(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;
publicclassVisualCounter{privateint count = 0;
privateint numOperate = 0;
privatefinalint MAX_NUM_OPE;
privatefinalint MAX_ABSOLUTE;
/**
*
* @param maxNumOpe The maximum number of operations
* @param maxAbsolute The maximum absolute value of the counter
*/publicVisualCounter(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
*/publicvoidincrement() throws IllegalValueOfCount,
ExceedLimitedOperationTimesException{
if(numOperate < MAX_NUM_OPE){
++count;
++numOperate;
drawCounter();
}elsethrownew ExceedLimitedOperationTimesException();
if(Math.abs(count) > MAX_ABSOLUTE)
thrownew IllegalValueOfCount();
}
/**
* decrease the Counter
*
* @throws IllegalValueOfCount
* @throws ExceedLimitedOperationTimesException
*/publicvoiddecrease() throws IllegalValueOfCount,
ExceedLimitedOperationTimesException{
if(numOperate < MAX_NUM_OPE){
--count;
++numOperate;
drawCounter();
}else{
thrownew ExceedLimitedOperationTimesException();
}
if(Math.abs(count) > MAX_ABSOLUTE)
thrownew IllegalValueOfCount();
}
/**
* Draw this Counter in a Standard Draw Window
*/publicvoiddrawCounter(){
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));
}
publicstaticvoidmain(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.
*/publicclassSmartDateextendsDate {publicSmartDate(int month, int day, int year){
super(month,day,year);
}
/**
*
* @return a string of dayOfTheWeek
* For example, FRIDAY,SUNDAY...
*/publicstatic String dayOfTheWeek(){
return LocalDate.now().getDayOfWeek() + "";
}
publicstaticvoidmain(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.
*/publicclassTransaction {privatefinal String name;
privatefinal Date date;
privatefinaldouble amount;
publicTransaction(String name,Date date, double amount)
throws IllegalArgumentException{
this.name = name;
this.date = date;
this.amount = amount;
if(Double.isNaN(amount) || Double.isInfinite(amount))
thrownew 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
*/publicdoubleamount() {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
*/publicbooleanequals(Object other){
if(this == other) returntrue;
if(other == null) returnfalse;
if(this.getClass() != other.getClass()) returnfalse;
Transaction that = (Transaction)other;
if(!this.date.equals(that.date)) returnfalse;
if(this.name != that.name) returnfalse;
if(Math.abs(this.amount - that.amount) > 1e-5)
returnfalse;
returntrue;
}
publicstaticvoidmain(String[] args) {
Transaction transaction = new Transaction("Stefen",new Date(3,11,2016),100);
System.out.println(transaction.toString());
}
}