Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added 22_08 Exercise Solution + 22 09 and 22 10 Exercise Questions #37

Merged
merged 1 commit into from
Sep 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions ch_13/exercise13_01/Triangle.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
//__________________________UML DIAGRAM_____________________________*
/* |
* /GeometricObject/ |
*-------------------------------------------------------------------|
*------------------------------------------------------------------|
* -color: String |
* -filled: boolean |
* -dateCreated : java.util.Date |
* -dateCreated : java.util.Date |
* |
*-------------------------------------------------------------------|
*------------------------------------------------------------------|
* #GeometricObject() |
* #GeometricObject(color:String,filled:boolean) |
* |
Expand All @@ -20,11 +20,11 @@
* +isFilled(): boolean |
* +setFilled(filled: boolean): void |
* +getDateCreated(): java.util.Date |
* |
* +toString(): String |
* |
* +toString(): String |
* /+getArea()/: double/ |
* /+getPerimeter(): double/ |
* __________________________________________________________________| */
* _________________________________________________________________| */
/* ^
^
^
Expand All @@ -38,8 +38,8 @@
* -side3: double |
* _________________________________________________________________|
* |
* +Triangle2D() |
* +Triangle2D(side1:double,side2:double,side3:double) |
* +Triangle2D() |
* +Triangle2D(side1:double,side2:double,side3:double) |
* +getSide1(): double |
* +setSide1(side1: double): void |
* +getSide2(): double |
Expand Down
14 changes: 14 additions & 0 deletions ch_22/Exercise22_09.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package ch_22;

/**
* **22.9 (Geometry: gift-wrapping algorithm for finding a convex hull) Section 22.10.1
* introduced the gift-wrapping algorithm for finding a convex hull for a set of
* points. Assume that the Java’s coordinate system is used for the points. Implement the algorithm using the following method:
* // Return the points that form a convex hull
* public static ArrayList<Point2D> getConvexHull(double[][]s)
* Point2D is defined in Section 9.6.
* Write a test program that prompts the user to enter the set size and the points
* and displays the points that form a convex hull.Here is a sample run:
*/
public class Exercise22_09 {
}
10 changes: 10 additions & 0 deletions ch_22/Exercise22_10.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package ch_22;

/**
* 22.10 (Number of prime numbers) Programming Exercise 22.8 stores the prime numbers in a file named PrimeNumbers.dat.
* Write a program that finds the number of prime numbers that are less than or equal to 10, 100, 1,000, 10,000,
* 100,000, 1,000,000, 10,000,000, 100,000,000, 1,000,000,000, and
* 10,000,000,000. Your program should read the data from PrimeNumbers.dat
*/
public class Exercise22_10 {
}
87 changes: 87 additions & 0 deletions ch_22/exercise22_08/Exercise22_08.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package ch_22.exercise22_08;

import java.io.*;

/**
* *22.8 (All prime numbers up to 10,000,000,000) Write a program that finds
* all prime numbers up to 10,000,000,000. There are approximately
* 455,052,511 such prime numbers. Your program should meet the following
* requirements:
* ■ Your program should store the prime numbers in a binary data file, named
* PrimeNumbers.dat. When a new prime number is found, the number is
* appended to the file.
* ■ To find whether a new number is prime, your program should load the
* prime numbers from the file to an array of the long type of size 10000.
* If no number in the array is a divisor for the new number, continue to read
* the next 10000 prime numbers from the data file, until a divisor is found
* or all numbers in the file are read. If no divisor is found, the new number
* is prime.
* ■ Since this program takes a long time to finish, you should run it as a batch
* job from a UNIX machine. If the machine is shut down and rebooted, your
* program should resume by using the prime numbers stored in the binary data
* file rather than start over from scratch.
*/
public class Exercise22_08 {
private static PrimeStorage primeStorage;
private static final String[] packageParts = Exercise22_08.class.getPackage().getName().split("\\.");
private static final String PATH = packageParts[0] + File.separator + packageParts[1] + File.separator + "PrimeNumbers.dat";
private static long[] primeReadBuffer = new long[10000];
private static final long UPPER_BOUND = 10_000_000_000L;
private static boolean reachedEndOfBuffer = false;

public static void main(String[] args) {
try {
primeStorage = new PrimeStorage(PATH);
long checkNum = primeStorage.getNextNumberToCheck();
// Check primes until reaching upper bound
while (checkNum < UPPER_BOUND) {
boolean isPrime = checkPrime(checkNum, primeStorage);
if (isPrime) {
primeStorage.appendPrime(checkNum);
}
checkNum++;
}

} catch (Exception e) {
System.err.println("Could not create and/or read/write file needed to store prime numbers on this device. " +
"Please confirm Security Manager will allow create/read/write file storage.");
System.exit(0);
}

}

private static boolean checkPrime(long checkNum, PrimeStorage primeStorage) throws IOException {
boolean loop = true;
boolean isPrime = true;
primeStorage.setPosition(0);

while (loop) {
primeReadBuffer = primeStorage.readNextPrimes();
boolean isDivisible = isDivisible(primeReadBuffer, checkNum);
if (isDivisible) {
// checkNum is not prime
loop = false;
isPrime = false;
break;
} else if (reachedEndOfBuffer) {
loop = false;
break;
}
}

return isPrime;
}

public static boolean isDivisible(long[] primes, long checkNum) {
for (long prime : primes) {
if (prime == 0) {
reachedEndOfBuffer = true;
return false;
}
if (checkNum % prime == 0) {
return true;
}
}
return false;
}
}
Binary file added ch_22/exercise22_08/PrimeNumbers.dat
Binary file not shown.
96 changes: 96 additions & 0 deletions ch_22/exercise22_08/PrimeStorage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package ch_22.exercise22_08;

import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class PrimeStorage {
protected File dataFile;
private boolean firstRun;
private long nextNumberToCheck = 0;
private RandomAccessFile randomAccessFile;


public PrimeStorage(String storageFilePath) throws Exception {
dataFile = new File(storageFilePath);
boolean createdOrExists = dataFile.exists();
/* If file does not exist, this is the first run, starting from first prime number */
if (!createdOrExists) {
this.firstRun = true;
try {
createdOrExists = dataFile.createNewFile();
} catch (IOException ioe) {
throw new Exception("Error while trying to create storage file: " + ioe.getLocalizedMessage());
}
}

if (createdOrExists) {
/* Need file channel to be: Closable, seekable, readable, writable */
try {
randomAccessFile = new RandomAccessFile(dataFile, "rws");
// Handle different startup flows
if (firstRun) {
nextNumberToCheck = initializePrimes();
} else {
nextNumberToCheck = restartPrimes();
}
} catch (IOException ioException) {
throw new Exception("IOException while creating in and out file stream: \n" + ioException.getMessage());
}
}

}

private long restartPrimes() throws IOException {
long totalBytes = randomAccessFile.length();
randomAccessFile.seek(totalBytes - 8); // Seek to read the last 8 bytes in the file
long lastPrime = randomAccessFile.readLong();
return nextNumberToCheck = lastPrime + 1;
}


private long initializePrimes() throws IOException {
/* First time running program, prep the file by writing first two prime numbers */
randomAccessFile.writeLong(2L);
randomAccessFile.writeLong(3L);
return 4;
}

public long[] readNextPrimes() {
long[] primes = new long[10000];
try {
for (int i = 0; i < primes.length && (randomAccessFile.getFilePointer() < randomAccessFile.length()); i++) {
primes[i] = randomAccessFile.readLong();
}
} catch (EOFException eof) {
System.out.println("End of File Reached");
return primes;
} catch (IOException e) {
e.printStackTrace();
}
return primes;
}

public void appendPrime(long primeNumber) throws IOException {
long totalBytes = randomAccessFile.length();
randomAccessFile.seek(totalBytes);
randomAccessFile.writeLong(primeNumber);
}

public boolean isFirstRun() {
return firstRun;
}

public long getNextNumberToCheck() {
return nextNumberToCheck;
}

public void setNextNumberToCheck(long nextNumberToCheck) {
this.nextNumberToCheck = nextNumberToCheck;
}

public void setPosition(long position) throws IOException {
randomAccessFile.seek(position);
}
}
28 changes: 28 additions & 0 deletions ch_22/exercise22_08/Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package ch_22.exercise22_08;

import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
* Integration Test will print out the prime numbers from PrimeNumbers.dat
*/
public class Test {
private static final String[] packageParts = Exercise22_08.class.getPackage().getName().split("\\.");
private static final String PATH = packageParts[0] + File.separator + packageParts[1] + File.separator + "PrimeNumbers.dat";

public static void main(String[] args) {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(new File(PATH), "rw");
while (true) {
long nextLong = randomAccessFile.readLong();
System.out.println("Next long: " + nextLong);
}
} catch (EOFException eof) {
System.out.println("EOF reached");
} catch (IOException ioException) {
System.out.println("IOException while creating in and out file stream: \n" + ioException.getMessage());
}
}
}
Loading