Buffer
package com.duoduo.args.homework;
import java.util.NoSuchElementException;
import com.duoduo.args.Stack;
import com.duoduo.std.StdOut;
/***
* 文本编辑器缓冲区 光标在left栈的栈顶
* ***/
public class Buffer {
private Stack<Character> left;
private Stack<Character> right;
public Buffer() {
left = new Stack<Character>();
right = new Stack<Character>();
}
/***
* 光标位置插入字符c
* ***/
public void insert(char c) {
left.push(c);
}
/***
* 删除并返回光标位置的字符
*
* pop left的一个元素
* ***/
public char delete() {
if (!left.isEmpty()) {
return left.pop();
}
throw new NoSuchElementException("光标已经达到文本开始位置");
}
/***
* 将光标向左移动k个位置
*
* 将left栈里的元素pop k个给right栈, 如果left的元素小于k,将left全部pop给right
* ***/
public void left(int k) {
// 光标移动的范围大于left中的元素
if (k > left.size()) {
while (!left.isEmpty()) {
right.push(left.pop());
}
} else {
for (int i = 0; i < k; i++) {
right.push(left.pop());
}
}
}
/***
* 将光标向右移动k个位置
*
* 将right栈里的元素pop k个给left栈 如果right的元素小于k,将right全部pop给left
* ***/
public void right(int k) {
// 光标移动的范围大于right中的元素
if (k > right.size()) {
while (!right.isEmpty()) {
left.push(right.pop());
}
} else {
for (int i = 0; i < k; i++) {
left.push(right.pop());
}
}
}
public void show() {
int rightSize = right.size();
Character ch;
// 将left元素放到right中,因为right的pop顺序才是输入顺序
while (!left.isEmpty()) {
right.push(left.pop());
}
while (!right.isEmpty()) {
ch = right.pop();
StdOut.print(ch);
left.push(ch);
}
// 还原栈
for (int i = 0; i < rightSize; i++) {
right.push(left.pop());
}
}
/***
* 缓冲区的字符数量
* ***/
public int size() {
return left.size() + right.size();
}
public static void main(String args[]) {
Buffer buffer = new Buffer();
for (char ch = 'a'; ch <= 'e'; ch++) {
buffer.insert(ch);
}
buffer.show();
StdOut.println();
buffer.left(2);
for (char ch = '1'; ch <= '5'; ch++) {
buffer.insert(ch);
}
buffer.show();
StdOut.println();
buffer.left(100);
for (char ch = 'A'; ch <= 'D'; ch++) {
buffer.insert(ch);
}
buffer.show();
StdOut.println();
buffer.right(100);
for (char ch = 'a'; ch <= 'e'; ch++) {
buffer.insert(ch);
}
buffer.show();
StdOut.println();
}
}
Card
package com.duoduo.args.homework;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import com.duoduo.args.RandomQueue;
import com.duoduo.std.StdOut;
public class Card implements Comparable<Card> {
public static final char HEART = 0;
public static final char SQUARE = 1;
public static final char SPADE = 2;
public static final char CLUB = 3;
public static final int TOTAL_CARDS_NUM = 54;
public static final int TYPE_CARDS_NUM = 13;
public static final int TYPE_NUM = 4;
private int num;
private char type;
public Card() {
num = 1;
type = HEART;
}
public Card(char type, int num) {
this.type = type;
this.num = num;
}
public static Card[][] genarate() {
Card[][] cards = new Card[TYPE_NUM][TYPE_CARDS_NUM];
for (char type = HEART; type <= CLUB; type++) {
for (int i = 1; i <= TYPE_CARDS_NUM; i++) {
cards[type][i - 1] = new Card(type, i);
}
}
return cards;
}
public int compareTo(Card o) {
return num - o.num;
}
public String toString() {
String r;
if (type == HEART) {
r = "红桃";
} else if (type == SQUARE) {
r = "方片";
} else if (type == SPADE) {
r = "黑桃";
} else {
r = "梅花";
}
return r + num;
}
public static void main(String args[]) {
Card[][] cards = Card.genarate();
RandomQueue<Card> cardQueue = new RandomQueue<Card>();
for (Card[] cs : cards) {
for (Card c : cs) {
cardQueue.enqueue(c);
}
}
for (Card card : cardQueue) {
StdOut.print(card + " ");
}
StdOut.println();
Card[][] game = new Card[4][13];
for (int i = 0; i < game.length; i++) {
for (int j = 0; j < game[i].length; j++) {
game[i][j] = cardQueue.dequeue();
}
}
for (Card[] cs : game) {
Arrays.sort(cs);
for (Card c : cs) {
StdOut.print(c + " ");
}
StdOut.println();
}
}
}
FileListShow
package com.duoduo.args.homework;
import java.io.File;
import com.duoduo.args.Queue;
import com.duoduo.std.StdOut;
import com.duoduo.util.RedirectionOut;
public class FileListShow {
private static final int LEVEL_BLANK_NUM = 2;
public static void showFileList(String directoryPath) {
File f = new File(directoryPath);
if (!f.isDirectory()) {
throw new IllegalArgumentException("请输入合法的文件夹地址:" + directoryPath);
}
Queue<File> directoryQueue = new Queue<File>();
directoryQueue.enqueue(f);
recursion(directoryQueue, 0);
}
private static void recursion(Queue<File> directoryQueue,
int directoryBlankNum) {
File directory;
while (!directoryQueue.isEmpty()) {
directory = directoryQueue.dequeue();
for (File file : directory.listFiles()) {
showFile(file, directoryBlankNum);
if (file.isDirectory()) {
directoryQueue.enqueue(file);
try {
recursion(directoryQueue, directoryBlankNum + 2);
} catch (java.lang.NullPointerException e) {
}
}
}
}
}
private static void showFile(File file, int directoryBlankNum) {
print(directoryBlankNum, "-", file.toString());
StdOut.println();
}
private static void print(int blank, String splitCharacter, String fileName) {
StringBuffer buffer = new StringBuffer("|");
for (int i = 0; i < blank; i++) {
buffer.append(" ");
}
buffer.append(splitCharacter);
buffer.append(" ");
buffer.append(fileName);
StdOut.print(buffer.toString());
}
public static void main(String args[]) {
showFileList("d:\\");
// RedirectionOut.StdOutToFile("data/out.txt");
// showFileList("d:\\");
// RedirectionOut.close();
}
}
Josephus
package com.duoduo.args.homework;
import com.duoduo.args.Queue;
import com.duoduo.std.StdIn;
import com.duoduo.std.StdOut;
/***
* Josephus问题(猴子选大王):在这个古老的问题中: N个身陷绝境的人一致同意通过以下方式减少生存人数。
* 他们围坐成一圈(位置为0~N-1)并从第一个人开始报数, 报到M的人将会被杀死,直到最后一个人留下来。 传说中Josephus找到了不会被杀死位置。
*
* 编写一个Queue的用例,从命令行接受N,M,并打印出人们被杀死的顺序 (这也将显示Josephus在圈中的位置)。
*
* 思路,排队向前走,如果不死,重新跑到队尾,死了就减少一个人,直到剩下一个人。
* ***/
public class Josephus {
public static void josephus() {
int N = StdIn.readInt();
int M = StdIn.readInt();
Queue<Integer> queue = new Queue<Integer>();
// 围成一圈
for (int i = 0; i < N; i++) {
queue.enqueue(i);
}
int pos;
int killNumber = 0;
// 开始报数
while (!queue.isEmpty()) {
pos = queue.dequeue();
// 很遗憾,这个位置的人死掉了
if (++killNumber == M) {
StdOut.print(pos + " ");
killNumber = 0;
} else {
// 你以为能活下来么,重新来排队吧骚年
queue.enqueue(pos);
}
}
// return queue.dequeue();
}
public static void main(String args[]) {
Josephus.josephus();
}
}
Lottery
package com.duoduo.args.homework;
import com.duoduo.std.StdOut;
import com.duoduo.std.StdRandom;
public class Lottery {
public static void main(String args[]) {
int N = 35;
int[] a = new int[N];
for (int i = 0; i < N; i++) {
a[i] = i + 1;
}
int BITS = 7;
StdRandom.shuffle(a);
for (int i = 0; i < BITS; i++) {
StdOut.print(a[i] + " ");
}
StdOut.println();
// while (true) {
// StdRandom.shuffle(a);
// for (int i = 0; i < BITS; i++) {
// StdOut.print(a[i] + " ");
// }
// StdOut.println();
// }
}
}
Parenthess
package com.duoduo.args.homework;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import com.duoduo.args.Stack;
import com.duoduo.std.StdIn;
import com.duoduo.std.StdOut;
import com.duoduo.util.RedirectionIn;
public class Parenthess {
private char[] parenthess;
public final char[] LEFT = { '[', '(', '{' };
public static Map<Character, Character> map;
private Stack<Character> stack;
public Parenthess(String path) {
RedirectionIn.fileToStdIn(path);
}
public void init() {
map = new HashMap<Character, Character>();
map.put(']', '[');
map.put(')', '(');
map.put('}', '{');
stack = new Stack<Character>();
parenthess = StdIn.readAllChars();
}
public boolean isCorrect() {
for (Character ch : parenthess) {
if (!map.containsKey(ch)) {
stack.push(ch);
} else {
try {
if (!stack.pop().equals(map.get(ch))) {
return false;
}
} catch (NoSuchElementException e) {
return false;
}
}
}
return true;
}
public static void main(String args[]) {
Parenthess pt = new Parenthess("data/parentheses.txt");
pt.init();
StdOut.println(pt.isCorrect());
}
}
ShortestPairPoint
package com.duoduo.args.homework;
import java.util.Arrays;
import com.duoduo.std.StdArrayIO;
import com.duoduo.std.StdOut;
import com.duoduo.util.Pair;
public class ShortestPairPoint {
private double[] a;
private DoubleWarp[] dw;
private class DoubleWarp implements Comparable<DoubleWarp> {
private double real;
private double positive;
public DoubleWarp(double d) {
real = d;
positive = Math.abs(real);
}
public int compareTo(DoubleWarp o) {
double b = positive - o.positive;
if (b > 0) {
return 1;
}
if (b < 0) {
return -1;
}
return 0;
}
public String toString() {
return real + "";
}
}
public ShortestPairPoint() {
}
public void setArray(double[] a) {
dw = new DoubleWarp[a.length];
for (int i = 0; i < a.length; i++) {
dw[i] = new DoubleWarp(a[i]);
}
Arrays.sort(dw);
StdArrayIO.print(this.dw);
}
public ShortestPairPoint(double[] a) {
this.a = Arrays.copyOf(a, a.length);
Arrays.sort(this.a);
StdArrayIO.print(this.a);
}
public Pair<Double> shortest() {
return cal2(this.a, 0, a.length);
// return cal(this.a, 0, a.length);
}
public Pair<Double> shortestAbs() {
return cal2(this.dw, 0, dw.length);
}
/***
* 排序后的a,两两比较 [fromIndex,toIndex)
* ***/
private Pair<Double> cal2(DoubleWarp[] a, int fromIndex, int toIndex) {
Pair<Double> pair = new Pair<Double>();
double shortest = Double.MAX_VALUE;
double temp;
for (int i = fromIndex; i < toIndex - 1; i++) {
temp = getDistance(a[i + 1].real, a[i].real);
if (temp < shortest) {
shortest = temp;
pair.x = a[i].real;
pair.y = a[i + 1].real;
}
}
return pair;
}
/***
* 排序后的a,两两比较 [fromIndex,toIndex)
* ***/
private Pair<Double> cal2(double[] a, int fromIndex, int toIndex) {
Pair<Double> pair = new Pair<Double>();
double shortest = Double.MAX_VALUE;
double temp;
for (int i = fromIndex; i < toIndex - 1; i++) {
temp = getDistance(a[i + 1], a[i]);
if (temp < shortest) {
shortest = temp;
pair.x = a[i];
pair.y = a[i + 1];
}
}
return pair;
}
/***
* 分治,多此一举 [fromIndex,toIndex)
* ***/
private Pair<Double> cal(double[] a, int fromIndex, int toIndex) {
// StdOut.println(fromIndex + " - " + toIndex);
if (toIndex - fromIndex <= 1) {
throw new RuntimeException("计算时的数组划分的元素应该大于1");
}
// 2个直接返回
if (toIndex - fromIndex == 2) {
// StdOut.println("second:" + a[fromIndex] + " - " + a[fromIndex +
// 1]);
return new Pair<Double>(a[fromIndex], a[fromIndex + 1]);
}// 3个以内直接算出来
if (toIndex - fromIndex == 3) {
// StdOut.println("thrid:" + a[fromIndex] + " - " + a[fromIndex + 1]
// + " - " + a[fromIndex + 2]);
Pair<Double> thirdA = new Pair<Double>(a[fromIndex],
a[fromIndex + 1]);
Pair<Double> thirdB = new Pair<Double>(a[fromIndex + 1],
a[fromIndex + 2]);
return (getDistance(thirdA) <= getDistance(thirdB) ? thirdA
: thirdB);
}// 大于3个,分治
else {
// 左边最小
Pair<Double> left = cal(a, fromIndex, fromIndex
+ (toIndex - fromIndex) / 2);
// StdOut.println("left:" + left);
// 右边最小
Pair<Double> right = cal(a, fromIndex + (toIndex - fromIndex) / 2,
toIndex);
// StdOut.println("right:" + right);
// 中间
Pair<Double> mid = new Pair<Double>(a[fromIndex
+ (toIndex - fromIndex) / 2 - 1], a[fromIndex
+ (toIndex - fromIndex) / 2]);
// StdOut.println("mid:" + mid);
Pair<Double> shortestPair = (getDistance(left) <= getDistance(right) ? left
: right);
shortestPair = (getDistance(shortestPair) <= getDistance(mid) ? shortestPair
: mid);
return shortestPair;
}
}
private double getDistance(Pair<Double> pair) {
return Math.abs((Math.abs(pair.y) - Math.abs(pair.x)));
// return pair.y - pair.x;
}
private double getDistance(double a, double b) {
return Math.abs((Math.abs(a) - Math.abs(b)));
}
public static void main(String args[]) {
double[] a = { 111, 201, 124, 2000, 187, 1, 455555, -154687, 20, -8888,
587, 123, 124, -111, -100, -78 };
// ShortestPairPoint shortestPairPoint = new ShortestPairPoint(a);
ShortestPairPoint shortestPairPoint = new ShortestPairPoint();
shortestPairPoint.setArray(a);
Pair<Double> pair = shortestPairPoint.shortestAbs();
StdOut.println(pair);
}
}
TwoSumFaster
package com.duoduo.args.homework;
import java.awt.Color;
import java.util.Arrays;
import com.duoduo.std.StdArrayIO;
import com.duoduo.std.StdDraw;
import com.duoduo.std.StdIn;
import com.duoduo.std.StdOut;
import com.duoduo.std.StdRandom;
import com.duoduo.std.StopWatch;
import com.duoduo.util.RedirectionIn;
public class TwoSumFaster {
private int[] a;
public TwoSumFaster(int[] a) {
this.a = Arrays.copyOf(a, a.length);
Arrays.sort(this.a);
}
public int count() {
int front = 0;
int tail = a.length - 1;
int count = 0;
// a[front] < a[tail],
// 如果a[front] > 0, 则都为正数
// 如果a[tail] < 0,则都为负数
while (front < tail && a[front] <= 0 && a[tail] >= 0) {
if (a[front] == -a[tail]) {
count++;
front++;
} else if (-a[front] > a[tail]) {
front++;
} else {
tail--;
}
}
return count;
}
public int countBinary() {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (Arrays.binarySearch(a, 0, a.length, -a[i]) > i) {
count++;
}
}
return count;
}
public static void drawPoint(double xpoint, double ypoint, Color color) {
StdDraw.setPenColor(color);
StdDraw.point(xpoint, ypoint);
}
public static void drawInit(double xscale, double yscale) {
StdDraw.setPenRadius(.03);
StdDraw.setXscale(0, xscale + 10);
StdDraw.setYscale(0, yscale);
}
public static void main(String args[]) {
int loopN = 40;
int gap = 100000;
drawInit(loopN, .5);
for (int k = 0; k < loopN; k++) {
int N = gap + gap * k;
int[] a = new int[N];
int f = -1;
for (int i = 0; i < N; i++) {
f *= -1;
a[i] = StdRandom.uniform(1, N / 2) * f;
}
TwoSumFaster twf = new TwoSumFaster(a);
int count1;
int count2;
StopWatch watch1 = new StopWatch();
count1 = twf.count();
double time1 = watch1.elapsedTime();
StopWatch watch2 = new StopWatch();
count2 = twf.countBinary();
double time2 = watch2.elapsedTime();
StdOut.println(watch1 + ":" + count1 + " - " + watch2 + ":"
+ count2 + " - " + (count1 == count2));
drawPoint(k, time1, StdDraw.BLACK);
drawPoint(k, time2, StdDraw.RED);
}
}
}