Commit d05b2bbe authored by tammam.alsoleman's avatar tammam.alsoleman

ADD_BinarySearchHacker

parent 897a00f6
public class BinarySearchHackerThread extends Thread {
private Vault vault;
private int attempts;
public BinarySearchHackerThread(Vault vault) {
this.vault = vault;
this.setName("BinarySearchHacker");
this.setPriority(Thread.MAX_PRIORITY);
this.attempts = 0;
}
@Override
public void run() {
System.out.println(this.getName() + " started hacking with REAL binary search algorithm");
int low = 0;
int high = 9999;
while (low <= high) {
attempts++;
int mid = low + (high - low) / 2;
int result = vault.comparePassword(mid);
if (result == 0) {
// Password is true
System.out.println(this.getName() + " cracked the vault! Password: " + mid);
System.out.println("Binary search completed in " + attempts + " attempts");
System.exit(0);
} else if (result == -1) {
// less than password
low = mid + 1;
} else {
// bigger than Password
high = mid - 1;
}
}
}
}
\ No newline at end of file
......@@ -6,12 +6,14 @@ public class Main {
AscendingHackerThread ascendingHacker = new AscendingHackerThread(vault);
DescendingHackerThread descendingHacker = new DescendingHackerThread(vault);
BinarySearchHackerThread binarySearchHacker = new BinarySearchHackerThread(vault);
PoliceThread police = new PoliceThread();
System.out.println("Starting all threads...");
ascendingHacker.start();
descendingHacker.start();
binarySearchHacker.start();
police.start();
System.out.println("All threads are running !");
......
......@@ -13,4 +13,21 @@ public class Vault {
}
return guess == this.password;
}
public int comparePassword(int guess) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Exception during password comparison");
}
if (guess == this.password) {
return 0;
} else if (guess < this.password) {
return -1;
} else {
return 1;
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment