diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..2f64d2b Binary files /dev/null and b/.DS_Store differ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..800a0d4 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,46 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - encap", + "request": "launch", + "mainClass": "encap", + "projectName": "ThinkJavaCode_bf076222" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Format", + "request": "launch", + "mainClass": "Format", + "projectName": "ThinkJavaCode_bf076222" + }, + { + "type": "java", + "name": "CodeLens (Launch) - ArrayExamples", + "request": "launch", + "mainClass": "ArrayExamples", + "projectName": "ThinkJavaCode_bf076222" + }, + { + "type": "java", + "name": "CodeLens (Launch) - math", + "request": "launch", + "mainClass": "math", + "projectName": "ThinkJavaCode_bf076222" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Exercise", + "request": "launch", + "mainClass": "Exercise", + "projectName": "ThinkJavaCode_bf076222" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Tables", + "request": "launch", + "mainClass": "Tables", + "projectName": "ThinkJavaCode_bf076222" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..2421e38 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "files.exclude": { + "**/.classpath": true, + "**/.project": true, + "**/.settings": true, + "**/.factorypath": true + } +} \ No newline at end of file diff --git a/ap02/.vscode/launch.json b/ap02/.vscode/launch.json new file mode 100644 index 0000000..8cfbe4c --- /dev/null +++ b/ap02/.vscode/launch.json @@ -0,0 +1,28 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Moire", + "request": "launch", + "mainClass": "Moire" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Mickey", + "request": "launch", + "mainClass": "Mickey" + }, + { + "type": "java", + "name": "CodeLens (Launch) - japan", + "request": "launch", + "mainClass": "japan" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Drawing", + "request": "launch", + "mainClass": "Drawing" + } + ] +} \ No newline at end of file diff --git a/ap02/Mickey.java b/ap02/Mickey.java index 6dfa3bc..1845c6e 100644 --- a/ap02/Mickey.java +++ b/ap02/Mickey.java @@ -30,13 +30,18 @@ public void mickey(Graphics g, Rectangle bb) { int dx = bb.width / 2; int dy = bb.height / 2; - Rectangle half = new Rectangle(bb.x, bb.y, dx, dy); + if (dx > 3) { + Rectangle half = new Rectangle(bb.x, bb.y, dx, dy); - half.translate(-dx / 2, -dy / 2); - boxOval(g, half); + half.translate(-dx / 2, -dy / 2); + mickey(g, half); - half.translate(dx * 2, 0); - boxOval(g, half); + half.translate(dx * 2, 0); + mickey(g, half); + + dx /= 2; + dy /= 2; + } } } diff --git a/ap02/Moire.java b/ap02/Moire.java index 8e7247f..c7cb713 100644 --- a/ap02/Moire.java +++ b/ap02/Moire.java @@ -16,11 +16,25 @@ public static void main(String[] args) { } public void paint(Graphics g) { - int i = 90; - while (i < getWidth()) { - g.drawOval(0, 0, i, i); - i = i + 3; + // int i = 90; + // while (i < getWidth()) { + // g.drawOval(getWidth() / 2 - i / 2, getHeight() / 2 - i / 2, i, i); + // i = i + 3; + // } + radial(g); + } + + public void radial(Graphics g) { + int i = 0; + int j = 0; + while (i <= getWidth() && j <= getHeight()) { + g.drawLine(i, 0, getWidth() - i, getHeight()); + g.drawLine(0, j, getWidth(), getHeight() - j); + i = i + 5; + j = j + 5; } + g.drawLine(0, getHeight(), getWidth(), 0); + } } diff --git a/ap02/japan.java b/ap02/japan.java new file mode 100644 index 0000000..0824b19 --- /dev/null +++ b/ap02/japan.java @@ -0,0 +1,22 @@ +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Graphics; +import javax.swing.JFrame; + + +public class japan extends Canvas { + + public static void main(String[] args) { + JFrame frame = new JFrame("Flag of Japan"); + Canvas japan = new japan(); + japan.setSize(600, 400); + frame.add(japan); + frame.pack(); + frame.setVisible(true); + } + + public void paint(Graphics g) { + g.setColor(Color.red); + g.fillOval(175, 75, 250, 250); + } +} \ No newline at end of file diff --git a/ch02/Date.java b/ch02/Date.java new file mode 100644 index 0000000..b36e740 --- /dev/null +++ b/ch02/Date.java @@ -0,0 +1,10 @@ +public class Date { + public static void main(String[] args) { + String day = "Wednesday"; + int date = 7; + String month = "August"; + int year = 2019; + System.out.println("American Format:"); + System.out.println(day+", " + month + " " + date + ", " + year); + } +} diff --git a/ch02/Time.java b/ch02/Time.java new file mode 100644 index 0000000..a38b729 --- /dev/null +++ b/ch02/Time.java @@ -0,0 +1,24 @@ +public class Time { + + public static void main(String[] args) { + int hour, minute, second; + hour = 13; + minute = 32; + second = 10; + int timeOfDay = (hour * 3600) + (minute * 60) + second; + System.out.println(timeOfDay); + int untilMidnight = (24 * 3600) - timeOfDay; + System.out.println(untilMidnight); + System.out.println(untilMidnight / (24.0 * 3600)); + int startHour = hour; + int startMinute = minute; + int startSecond = second; + hour = 13; + minute = 38; + second = 12; + System.out.print("Elapsed time is " + (hour - startHour)); + System.out.print(" hours, " + (minute - startMinute)); + System.out.print(" minutes, and " + (second - startSecond)); + System.out.println(" seconds."); + } +} \ No newline at end of file diff --git a/ch03/Convert.java b/ch03/Convert.java index d31fe77..d4d5f26 100644 --- a/ch03/Convert.java +++ b/ch03/Convert.java @@ -22,6 +22,7 @@ public static void main(String[] args) { remainder = inches % IN_PER_FOOT; System.out.printf("%.2f cm = %d ft, %d in\n", cm, feet, remainder); + in.close(); } } diff --git a/ch03/GuessStarter.java b/ch03/GuessStarter.java index 64984df..3c4043f 100644 --- a/ch03/GuessStarter.java +++ b/ch03/GuessStarter.java @@ -1,5 +1,7 @@ import java.util.Random; +import com.sun.java_cup.internal.runtime.Scanner; + /** * Starter code for the "Guess My Number" exercise. */ @@ -9,7 +11,22 @@ public static void main(String[] args) { // pick a random number Random random = new Random(); int number = random.nextInt(100) + 1; - System.out.println(number); + int guess; + + // Prompt user for a guess + System.out.println("I'm thinking of a number, can you guess it?"); + java.util.Scanner in = new java.util.Scanner(System.in); + guess = in.nextInt(); + System.out.printf("You guessed %d\n", guess); + System.out.printf("I was thinking of %d\n", number); + int difference; + if (guess < number) { + difference = number - guess; + } + else { + difference = guess - number; + } + System.out.printf("You were off by %d\n", difference); } } diff --git a/ch03/Temp.java b/ch03/Temp.java new file mode 100644 index 0000000..261b796 --- /dev/null +++ b/ch03/Temp.java @@ -0,0 +1,17 @@ +import java.util.Scanner; + +public class Temp { + public static void main(String[] args) { + double tempC, tempF; + final double C_TO_F_RATIO = 9.0 / 5.0; + final int C_TO_F_DIFFERENCE = 32; + Scanner in = new Scanner(System.in); + + System.out.println("How hot is it?"); + tempC = in.nextDouble(); + + tempF = (tempC * C_TO_F_RATIO) + C_TO_F_DIFFERENCE; + System.out.printf("In degrees of freedom, that's %.1f degrees\n", tempF); + in.close(); + } +} \ No newline at end of file diff --git a/ch05/checkFermat.java b/ch05/checkFermat.java new file mode 100644 index 0000000..cd9b4c5 --- /dev/null +++ b/ch05/checkFermat.java @@ -0,0 +1,15 @@ + + +public class CheckFermat { + public static void checkferm(int a, int b, int c, int n) { + if (n > 2 && Math.pow(a, n) + Math.pow(b, n) == Math.pow(c, n)) { + System.out.println("Holy Smokes, Fernat was wrong!"); + } else { + System.out.println("No, that doesn't work."); + } + } + + public static void main(String[] args) { + checkferm(1, 2, 3, 4); + } +} diff --git a/ch06/Multadd.java b/ch06/Multadd.java new file mode 100644 index 0000000..ffce68e --- /dev/null +++ b/ch06/Multadd.java @@ -0,0 +1,44 @@ +public class Multadd { + + public static double multadd(double a, double b, double c) { + return a * b + c; + } + + public static void main(String[] args) { + System.out.println(multadd(2, 4, 3)); + System.out.println(multadd(1, 2, 3)); + System.out.println(multadd(0.5, Math.cos(Math.PI / 4), Math.sin(Math.PI / 4))); + System.out.println(multadd(1, Math.log(10), Math.log(20))); + System.out.println(oddSum(5)); + } + + public static double expSum(double x) { + double exp = Math.exp(-x); + return multadd(x, exp, Math.sqrt(1 - exp)); + } + + public static int oddSum(int n) { + if (n % 2 == 0 || n <= 0) { + System.err.println("Input to oddSum must be an odd integer"); + return 0; + } + if (n == 1) { + return n; + } else { + return n + oddSum(n - 2); + } + } + + public static int ack(int m, int n) { + if (m == 0 && n >= 0) { + return n + 1; + } else if (m > 0 && n == 0) { + return ack(m - 1, 1); + } else if (m > 0 && n > 0) { + return ack(m - 1, ack(m, n - 1)); + } else { + System.err.println("Inputs to ack must be positive integers"); + return 0; + } + } +} \ No newline at end of file diff --git a/ch06/testing.java b/ch06/testing.java new file mode 100644 index 0000000..4209915 --- /dev/null +++ b/ch06/testing.java @@ -0,0 +1,26 @@ +public class testing { + public static void main(String[] args) { + Math.sqrt(9); + System.out.println(isDivisible(9, 10)); + System.out.println(isTriangle(3, 4, 5)); + + } + + public static boolean isDivisible(int n, int m) { + return n % m == 0; + } + + public static boolean isTriangle(int a, int b, int c) { + if (a + b < c) { + return false; + } else if (a + c < b) { + return false; + } else if (c + b < a) { + return false; + } else { + return true; + } + } + + +} \ No newline at end of file diff --git a/ch07/math.java b/ch07/math.java new file mode 100644 index 0000000..59b6234 --- /dev/null +++ b/ch07/math.java @@ -0,0 +1,61 @@ +public static class math { + + public static void main(String args[]) { + System.out.println(SquareRoot(16)); + System.out.println(power(3,0)); + System.out.println(factorial(0)); + check(1.0); + } + + public static double SquareRoot(double a) { + double x = a/2; + double y = a; + while (Math.abs(x - y) > 0.0001) { + y = x; + x = (x + a/x)/2; + } + return x; + } + + public static double power(double x, int n) { + double x0 = 1; + for (int i=0; i 0; i--) { + m = m * i; + } + return m; + } + + public static double myexp(double x, int n) { + double e = 1.0; + double j = 1.0; + for (int i=1; i a[max]) { + max = i; + } + } + return max; + } + + public static boolean[] sieve(int n) { // Program to employ the Sieve of Eratosthenes + boolean[] primes = new boolean[n]; + Arrays.fill(primes, true); + primes[0] = false; + primes[1] = false; + for (int i = 2; i < n; i++) { + if (!primes[i]) { + continue; + } + for (int j = i; j < n; j += i) { + if (j == i) { + continue; + } + if (primes[j]) { + primes[j] = false; + } + } + } + return primes; + } + + public static boolean areFactors(int n, int[] factors) { + for (int factor : factors) { + if (n % factor != 0) { + return false; + } + } + return true; + } + + public static boolean arePrimeFactors(int n, int[] factors) { + if (!areFactors(n, factors)) { + return false; + } + boolean[] primes = sieve(n); + for (int factor : factors) { + if (!primes[factor]) { + return false; + } + } + return true; + } + + public static int maxInRange(int[] a, int lowIndex, int highIndex) { + if (lowIndex == highIndex) { + return a[lowIndex]; + } + int mid = (highIndex - lowIndex) / 2; + return Math.max(maxInRange(a, lowIndex, lowIndex + mid), maxInRange(a, highIndex - mid, highIndex)); + } + + public static int max(int[] a) { + return maxInRange(a, 0, a.length - 1); + } +} \ No newline at end of file diff --git a/ch09/.vscode/launch.json b/ch09/.vscode/launch.json new file mode 100644 index 0000000..a9e0598 --- /dev/null +++ b/ch09/.vscode/launch.json @@ -0,0 +1,28 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Recurse", + "request": "launch", + "mainClass": "Recurse" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Test", + "request": "launch", + "mainClass": "Test" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Exercise", + "request": "launch", + "mainClass": "Exercise" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Format", + "request": "launch", + "mainClass": "Format" + } + ] +} \ No newline at end of file diff --git a/ch09/Exercise.java b/ch09/Exercise.java index d8a605d..9defea3 100644 --- a/ch09/Exercise.java +++ b/ch09/Exercise.java @@ -5,6 +5,13 @@ public class Exercise { public static void main(String[] args) { String s = "((3 + 7) * 2)"; + String t = "(() a v d"; + String u = "))(("; + System.out.println(parens(s)); + System.out.println(parens(u)); + } + + public static int parens(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { @@ -16,7 +23,7 @@ public static void main(String[] args) { } } - System.out.println(count); + return count; } } diff --git a/ch09/Recurse.java b/ch09/Recurse.java index c4ba2fb..7b63cb9 100644 --- a/ch09/Recurse.java +++ b/ch09/Recurse.java @@ -31,4 +31,76 @@ public static int length(String s) { return s.length(); } + public static void main(String[] args) { + String test = "a e i o u"; + System.out.println(first(test)); + System.out.println(rest(test)); + System.out.println(middle(test)); + System.out.println(length(test)); + printBackward(test); + System.out.println(reverseString("coffee")); + } + + public static void printString(String s) { + while (length(s) > 0) { + System.out.println(first(s)); + s = rest(s); + } + } + + public static void printBackward(String s) { + if (length(s) == 0) { + return; + } else { + printBackward(rest(s)); + System.out.println(first(s)); + } + } + + public static String reverseString(String s) { + if (length(s) == 1) { + return s; + } else { + return reverseString(rest(s)) + first(s); + } + } + + public static boolean isPalindrome(String s) { + String test = s.toLowerCase(); + if (length(test) == 1) { + return true; + } else if (length(test) == 2) { + return test.charAt(0) == test.charAt(1); + } else { + return (test.charAt(0) == test.charAt(test.length() - 1)) && isPalindrome(middle(s)); + } + } + + public static boolean isAbecedarian(String s) { + String test = s.toLowerCase(); + for (int i = 1; i < test.length(); i++) { + if (test.charAt(i) < test.charAt(i - 1)) { + return false; + } + } + return true; + } + + public static boolean isDoubloon(String s) { + int[] letterCount = new int[26]; + String test = s.toLowerCase(); + for (int i = 0; i < test.length(); i++) { + if (test.charAt(i) < 'a' || test.charAt(i) > 'z') { + continue; + } else { + letterCount[test.charAt(i) - 'a']++; + } + } + for (int count : letterCount) { + if (count != 0 && count != 2) { + return false; + } + } + return true; + } } diff --git a/ch09/Test.java b/ch09/Test.java new file mode 100644 index 0000000..715c3e4 --- /dev/null +++ b/ch09/Test.java @@ -0,0 +1,36 @@ +/** + * Test + */ +public class Test { + + public static void main(String[] args) { + System.out.println("hello" + '!'); + System.out.println('h' + "ello!"); + System.out.println('a' + 'b'); + // System.out.println(true + false); Booleans don't support + with anything + System.out.println('z' - 'a'); + System.out.println(('a' + 3.5)); + System.out.println(1 + 'a'); + System.out.println(1 + "hi"); + System.out.println(1.0 + 'a'); + System.out.println(1.0 + "hi"); + System.out.println("Hello" + 1); + System.out.println("Hello" + 1.0); + char x = (char) 97; + x++; + System.out.println("" + 'a'); + + } + + public static int[] letterHist(String s) { + sweep = s.toLowerCase(); + int[] hist = new int[26]; + for (char letter : sweep.toCharArray()) { + if (letter < 'a' || letter > 'z') { + continue; + } + hist[(int) letter - 'a']++; + } + return hist; + } +} \ No newline at end of file diff --git a/ch10/.vscode/launch.json b/ch10/.vscode/launch.json new file mode 100644 index 0000000..d5bba90 --- /dev/null +++ b/ch10/.vscode/launch.json @@ -0,0 +1,22 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Big", + "request": "launch", + "mainClass": "Big" + }, + { + "type": "java", + "name": "CodeLens (Launch) - PointRect", + "request": "launch", + "mainClass": "PointRect" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Riddle", + "request": "launch", + "mainClass": "Riddle" + } + ] +} \ No newline at end of file diff --git a/ch10/Big.java b/ch10/Big.java new file mode 100644 index 0000000..7f96e78 --- /dev/null +++ b/ch10/Big.java @@ -0,0 +1,22 @@ +import java.math.BigInteger; +/** + * Big + */ +public class Big { + + public static BigInteger factorial(int n) { + BigInteger m = BigInteger.valueOf(1); + for (int i = n; i > 0; i--) { + BigInteger next = BigInteger.valueOf(i); + m = m.multiply(next); + } + return m; + } + + public static void main(String[] args) { + for (int i = 0; i <= 30; i++) { + System.out.print(factorial(i) + " "); + } + System.out.println(); + } +} \ No newline at end of file diff --git a/ch10/Pow.java b/ch10/Pow.java index 9ba0952..4e37c4f 100644 --- a/ch10/Pow.java +++ b/ch10/Pow.java @@ -1,23 +1,25 @@ /** * BigInteger exercise. */ +import java.math.BigInteger; public class Pow { /** * Integer exponentiation. */ - public static int pow(int x, int n) { - if (n == 0) return 1; + public static BigInteger pow(int x, int n) { + if (n == 0) + return BigInteger.ONE; // find x to the n/2 recursively - int t = pow(x, n / 2); + BigInteger t = pow(x, n / 2); // if n is even, the result is t squared // if n is odd, the result is t squared times x if (n % 2 == 0) { - return t * t; + return t.multiply(t); } else { - return t * t * x; + return t.multiply(t).multiply(BigInteger.valueOf(x)); } } diff --git a/ch11/.vscode/launch.json b/ch11/.vscode/launch.json new file mode 100644 index 0000000..10fe67a --- /dev/null +++ b/ch11/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Rational", + "request": "launch", + "mainClass": "Rational" + }, + { + "type": "java", + "name": "CodeLens (Launch) - TimeClient", + "request": "launch", + "mainClass": "TimeClient" + } + ] +} \ No newline at end of file diff --git a/ch11/Date.java b/ch11/Date.java new file mode 100644 index 0000000..b618af9 --- /dev/null +++ b/ch11/Date.java @@ -0,0 +1,25 @@ +/** + * Date + */ +public class Date { + + private int month; + private int day; + private int year; + + public Date() { + this.month = 1; + this.day = 1; + this.year = 2019; + } + + public Date(int month, int day, int year) { + this.month = month; + this.day = day; + this.year = year; + } + + public static void main(String[] args) { + Date birthday = new Date(9, 21, 1994); + } +} \ No newline at end of file diff --git a/ch11/Rational.java b/ch11/Rational.java new file mode 100644 index 0000000..63d7559 --- /dev/null +++ b/ch11/Rational.java @@ -0,0 +1,80 @@ +/** + * Rational + */ +public class Rational { + + private int numerator; + private int denominator; + + public Rational() { + this.numerator = 0; + this.denominator = 1; + } + + public Rational(int num, int denom) { + this.numerator = num; + this.denominator = denom; + } + + public static void printRational(Rational r) { + System.out.printf("%d/%d", r.numerator, r.denominator); + System.out.println(); + } + + public String toString() { + return String.format("%d/%d", this.numerator, this.denominator); + } + + public void negate() { + this.numerator *= -1; + } + + public void invert() { + int placeholder = this.numerator; + this.numerator = this.denominator; + this.denominator = placeholder; + } + + public static double toDouble(Rational r) { + return ((double) r.numerator) / r.denominator; + } + + private int gcd(int a, int b) { + if (a == 0) { + return b; + } + if (b == 0) { + return a; + } + if (b > a) { + int q = b / a; + int r = b % a; + return gcd(a, r); + } else { + int q = a / b; + int r = a % b; + return gcd(b, r); + } + } + + public Rational reduce() { + int i = gcd(this.denominator, this.numerator); + if (i > 1) { + return new Rational(this.numerator / i, this.denominator / i); + } + else { + return new Rational(this.numerator, this.denominator); + } + } + public static void main(String[] args) { + Rational rat = new Rational(); + rat.numerator = 5; + rat.denominator = 10; + printRational(rat); + System.out.println(rat); + rat.negate(); + System.out.println(rat); + rat.invert(); + printRational(rat); + } +} \ No newline at end of file diff --git a/ch11/Tile.java b/ch11/Tile.java new file mode 100644 index 0000000..c67e68b --- /dev/null +++ b/ch11/Tile.java @@ -0,0 +1,44 @@ +/** + * Tile + */ +public class Tile { + + private char letter; + private int value; + + public Tile(char letter, int value) { + this.letter = letter; + this.value = value; + } + + public void printTile(Tile tile) { + char letter = tile.getLetter(); + int value = tile.getValue(); + System.out.println(letter + " Tile, worth " + value + " points"); + } + + public void testTile() { + Tile test = Tile('z', 10); + printTile(test); + } + + public String toString() { + return String.format(this.letter + " Tile, worth %02d points", this.value); + } + + public char getLetter() { + return this.letter; + } + + public int getValue() { + return this.value; + } + + public void setLetter(char letter) { + this.letter = letter; + } + + public void setValue(int val) { + this.value = val; + } +} \ No newline at end of file diff --git a/ch11/Time.java b/ch11/Time.java index 53afa0d..925a465 100644 --- a/ch11/Time.java +++ b/ch11/Time.java @@ -89,13 +89,15 @@ public Time add(Time t2) { */ public void increment(double seconds) { this.second += seconds; - while (this.second >= 60.0) { - this.second -= 60.0; - this.minute += 1; + if(this.second >= 60.0) { + int mins = this.second / 60; + this.minute += mins; + this.second %= 60; } - while (this.minute >= 60) { - this.minute -= 60; - this.hour += 1; + if (this.minute >= 60) { + int hrs = this.minute / 60; + this.minute %= 60; + this.hour += hrs; } } diff --git a/ch12/.vscode/launch.json b/ch12/.vscode/launch.json new file mode 100644 index 0000000..94804d3 --- /dev/null +++ b/ch12/.vscode/launch.json @@ -0,0 +1,10 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - CardTable", + "request": "launch", + "mainClass": "CardTable" + } + ] +} \ No newline at end of file diff --git a/ch12/.vscode/settings.json b/ch12/.vscode/settings.json new file mode 100644 index 0000000..2421e38 --- /dev/null +++ b/ch12/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "files.exclude": { + "**/.classpath": true, + "**/.project": true, + "**/.settings": true, + "**/.factorypath": true + } +} \ No newline at end of file diff --git a/ch12/Card.java b/ch12/Card.java index e7a0661..49bb7b6 100644 --- a/ch12/Card.java +++ b/ch12/Card.java @@ -34,6 +34,12 @@ public int compareTo(Card that) { if (this.suit > that.suit) { return 1; } + if (this.rank == 1 && that.rank != 1) { + return 1; + } + if (that.rank == 1 && this.rank != 1) { + return -1; + } if (this.rank < that.rank) { return -1; } diff --git a/ch12/Flush.java b/ch12/Flush.java new file mode 100644 index 0000000..e70f586 --- /dev/null +++ b/ch12/Flush.java @@ -0,0 +1,19 @@ +public class Flush { + public int[] suitHist(Card[] hand) { + int[] hist = new int[4]; + for (Card card : hand) { + hist[card.getSuit()]++; + } + return hist; + } + + public boolean hasFlush(Card[] hand) { + int[] suits = suitHist(hand); + for (int suit : suits) { + if (suit >= 5) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/ch13/.vscode/launch.json b/ch13/.vscode/launch.json new file mode 100644 index 0000000..b540a71 --- /dev/null +++ b/ch13/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Deck", + "request": "launch", + "mainClass": "Deck" + }, + { + "type": "java", + "name": "CodeLens (Launch) - Test", + "request": "launch", + "mainClass": "Test" + } + ] +} \ No newline at end of file diff --git a/ch13/Deck.java b/ch13/Deck.java index 742120e..e039e30 100644 --- a/ch13/Deck.java +++ b/ch13/Deck.java @@ -1,12 +1,14 @@ import java.util.Arrays; import java.util.Random; + /** * A deck of playing cards (of fixed size). */ public class Deck { private Card[] cards; + private Random random = new Random(); /** * Constructs a standard deck of 52 cards. @@ -49,26 +51,45 @@ public void print() { * Returns a string representation of the deck. */ public String toString() { - return Arrays.toString(this.cards); + StringBuilder output = new StringBuilder(); + for (Card card : cards) { + output.append(card.toString() + "\n"); + } + return output.toString(); + //return Arrays.toString(this.cards); } /** * Chooses a random number between low and high, including both. */ public int randomInt(int low, int high) { - return 0; + if (high < low) { + int placeholder = low; + low = high; + high = placeholder; + } + int rand = random.nextInt(high - low + 1); + rand += low; + return rand; } /** * Swaps the cards at indexes i and j. */ public void swapCards(int i, int j) { + Card card1 = cards[i]; + cards[i] = cards[j]; + cards[j] = card1; } /** * Randomly permutes the array of cards. */ public void shuffle() { + for (int i = 0; i < cards.length; i++) { + int j = randomInt(i, cards.length - 1); + swapCards(i, j); + } } /** @@ -76,13 +97,25 @@ public void shuffle() { * between low and high inclusive. */ public int indexLowest(int low, int high) { - return 0; + int min = low; + for (int i = low+1; i <= high; i++) { + if (cards[i].compareTo(cards[min]) == -1) { + min = i; + } + } + return min; } /** * Sorts the cards (in place) using selection sort. */ public void selectionSort() { + int j; + for (int i = 0; i < cards.length; i++) { + if ((j = indexLowest(i, cards.length-1)) >i ) { + swapCards(i, j); + } + } } /** @@ -100,20 +133,63 @@ public Deck subdeck(int low, int high) { * Combines two previously sorted subdecks. */ public static Deck merge(Deck d1, Deck d2) { - return null; + int fullDeck = d1.cards.length + d2.cards.length; + Deck combine = new Deck(fullDeck); + int i = 0; + int j = 0; + for (int k = 0; k < fullDeck; k++) { + if (i >= d1.cards.length) { + combine.cards[k] = d2.cards[j]; + j++; + } else if (j >= d2.cards.length) { + combine.cards[k] = d1.cards[i]; + i++; + } else if (d1.cards[i].compareTo(d2.cards[j]) == 1) { // d2 < d1 + combine.cards[k] = d2.cards[j]; + j++; + } else if (d1.cards[i].compareTo(d2.cards[j]) == -1) { // d1 < d2 + combine.cards[k] = d1.cards[i]; + i++; + } + else { // to avoid freezing i and j if the cards are somehow duplicates + combine.cards[k] = d1.cards[i]; + i++; + } + } + + return combine; } /** * Returns a sorted copy of the deck using merge sort. */ public Deck mergeSort() { - return this; + if (cards.length <= 1) { + return this; + } + Deck d1 = subdeck(0, cards.length / 2 - 1); + Deck d2 = subdeck(cards.length / 2, cards.length - 1); + d1 = d1.mergeSort(); + d2 = d2.mergeSort(); + return merge(d1, d2); } /** * Reorders the cards (in place) using insertion sort. */ public void insertionSort() { + for (int i = 1; i < cards.length; i++) { + for (int k = i; k > 0; k--) { + if (cards[k].compareTo(cards[k-1]) == -1) { + swapCards(k, k-1); + } + } + } + } + + public static void main(String[] args) { + Deck deck = new Deck(); + System.out.println(deck); } } diff --git a/ch14/.vscode/launch.json b/ch14/.vscode/launch.json new file mode 100644 index 0000000..8d15896 --- /dev/null +++ b/ch14/.vscode/launch.json @@ -0,0 +1,10 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Eights", + "request": "launch", + "mainClass": "Eights" + } + ] +} \ No newline at end of file diff --git a/ch14/Eights.java b/ch14/Eights.java index 13b7961..f691add 100644 --- a/ch14/Eights.java +++ b/ch14/Eights.java @@ -25,7 +25,7 @@ public Eights() { one = new Player("Allen"); deck.deal(one.getHand(), handSize); - two = new Player("Chris"); + two = new SmartPlayer("Chris"); deck.deal(two.getHand(), handSize); // turn one card face up @@ -111,8 +111,8 @@ public void takeTurn(Player player) { Card next = player.play(this, prev); discardPile.addCard(next); - System.out.println(player.getName() + " plays " + next); - System.out.println(); + // System.out.println(player.getName() + " plays " + next); + // System.out.println(); } /** @@ -123,23 +123,34 @@ public void playGame() { // keep playing until there's a winner while (!isDone()) { - displayState(); - waitForUser(); + // displayState(); + //waitForUser(); takeTurn(player); player = nextPlayer(player); } // display the final score - one.displayScore(); - two.displayScore(); + //one.displayScore(); + //two.displayScore(); } + /** * Creates the game and runs it. */ public static void main(String[] args) { - Eights game = new Eights(); - game.playGame(); + int[] tally = new int[2]; + for (int i = 0; i < 100; i++) { + Eights game = new Eights(); + game.playGame(); + if (game.one.score() > game.two.score()) { + tally[0]++; + } else if (game.two.score() > game.one.score()) { + tally[1]++; + } + } + System.out.printf("Allen with %d wins, Chris with %d\n",tally[0], tally[1]); + } } diff --git a/ch14/Player.java b/ch14/Player.java index 433ff28..dc882b4 100644 --- a/ch14/Player.java +++ b/ch14/Player.java @@ -58,7 +58,7 @@ public Card searchForMatch(Card prev) { public Card drawForMatch(Eights eights, Card prev) { while (true) { Card card = eights.draw(); - System.out.println(name + " draws " + card); + //System.out.println(name + " draws " + card); if (cardMatches(card, prev)) { return card; } diff --git a/ch14/SmartPlayer.java b/ch14/SmartPlayer.java new file mode 100644 index 0000000..6a3100d --- /dev/null +++ b/ch14/SmartPlayer.java @@ -0,0 +1,35 @@ +public class SmartPlayer extends Player { + + + public SmartPlayer(String name) { + super(name); + } + + public Card play(Eights eights, Card prev) { + Card card = searchForBetterMatch(prev); + if (card == null) { + card = drawForMatch(eights, prev); + } + return card; + } + + public Card searchForBetterMatch(Card prev) { + int bestMatch = -1; + for (int i = 0; i < getHand().size(); i++) { + Card card = getHand().getCard(i); + if (card.getRank() == 8) { + return getHand().popCard(i); + } + if (cardMatches(card, prev)) { + if (bestMatch == -1 || card.getRank() > getHand().getCard(bestMatch).getRank()) { + bestMatch = i; + } + } + } + if (bestMatch > -1) { + return getHand().popCard(bestMatch); + } + return null; + } + +} \ No newline at end of file