Dear reader,
Here I am writing a "Horse Racing" design which is generally asked in Interview questions in Java for
Experienced people.
//This is the main class, you have to execute.
public class HorseRace {
public static void main( String args[] ) {
Horse[] horseArray = new Horse[4]; //Initializing 4 Horses
for (int i=0; i<horseArray.length; i++) {
horseArray[i] = new Horse(i+1);
}
System.err.println( "!!!!!!!!!Starting race!!!!!!!!" );
Horse.resetRace();
for (int i=0; i<horseArray.length; i++) {
horseArray[i].start();
}
Reporter rpt = new Reporter(horseArray);
rpt.start();
}
}
//The below Reporter class is for Displaying purpose, which shows the Horse and Distance Status
public class Reporter extends Thread {
Horse[] horse;
public Reporter(Horse[] h) {
System.out.println("And they have left ground...");
horse = h;
}
public void run() {
System.out.print("Horse Label==>");
for (int i=0; i<horse.length; i++) {
System.out.printf("%5d ", (i+1));
}
System.out.println();
while (!Horse.done()) {
System.out.println();
System.out.print("Distance ");
for (int i=0; i<horse.length; i++) {
System.out.printf("%5d ", horse[i].getDistance());
}
}
System.out.print("\r");
System.out.print("Distance ");
for (int i=0; i<horse.length; i++) {
System.out.printf("%5d ", horse[i].getDistance());
}
System.out.println("\nAnd the winner is "+ Horse.getWinner());
}
}
//This is the actual Horse class, we need as many Instances of this class as number of Horse. Check the
//main class for the same.
class Horse extends Thread {
private static boolean raceOver = false;
private static final int raceLength = 3; //You can choose this.
private static String winner = "";
private int distance;
private String name = "";
public Horse(int id) {
name = "Horse #" + id;
distance = 0;
}
public static void resetRace() {
raceOver = false;
}
public static boolean done() {
return raceOver;
}
public static String getWinner() {
return winner;
}
public int getDistance() {
return distance;
}
public void run() {
while (!raceOver) {
try {
//Get a little rest and then move
Thread.sleep((int)(Math.random() * 500));
if (++distance >= raceLength)
raceOver = true;
} catch (InterruptedException e) {
System.err.println(e);
}
}
if (distance == raceLength) winner = name;
}
}
//Output:
!!!!!!!!!Starting race!!!!!!!!
And they have left ground...
Horse Label==> 1 2 3 4
Distance 0 0 0 0
Distance 0 0 0 0
------------
------------
------------
Distance 1 2 1 0
Distance 1 3 1 0
And the winner is Horse #2
//You can see the Horse Label 2 has completed the distance/race length first.
Friday, February 24, 2012
Horse Racing Design in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment