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 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 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 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!");
}
}
原字符串的逆序
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 BinarySearch class provides a static method for binary
* searching for an integer in a sorted array of integers.
*
* The rank operations takes logarithmic time in the worst case.
*
* For additional documentation, see Section 1.1 of
* Algorithms, 4th Edition 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 a if present; -1 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 rank
* 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 a if present; -1 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 not 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.
******************************************************************************/
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 + "]");
}
}
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
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() + "]");
}
}
Transaction.java
directlypackage 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 other; 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());
}
}