Sunday, 27 September 2015

Java program to find two numbers in an integer array such that their sum is greater than some integer in O(n) linear time....

problem -find two number 'a' and 'b' such that a+b>sum where sum can be any given integer value...

here is the code ......

logic =you have to execute two passes of bubble sort and then pick the last two elements ...


       
public class findElements {

 public static void main(String[] args) {
  int[] arr = {
   45,
   4,
   23,
   56,
   87,
   27,
   34,
   89
  };
  int temp;
  int sum = 100;
  for (int y = 0; y < 2; y++) {
   for (int i = 0; i < arr.length - y - 1; i++) {

    if (arr[i] > arr[i + 1]) {
     temp = arr[i];
     arr[i] = arr[i + 1];
     arr[i + 1] = temp;
    }
   }
  }
  if (arr[arr.length - 1] + arr[arr.length - 2] > sum)
   System.out.println("required elements are" + arr[arr.length - 1] + " and " + arr[arr.length - 2]);
  else System.out.println("elements not found");
  //for(int s:arr) { System.out.print(s); System.out.print(" ");}
 }

}

time complexity = 2(first loop) + n(second loop) = O(n)

       
 

Friday, 18 September 2015

Dining philosopher's synchronization problem implemented using Java........

here is the code .....


       

public class DiningPhilosopherProblem {
 // Makes the code more readable.
 public static class ChopStick {
  // Make sure only one philosopher can have me at any time.
  Lock up = new ReentrantLock();
  // Who I am.
  private final int id;

  public ChopStick(int id) {
   this.id = id;
  }

  public boolean pickUp(Philosopher who, String where) throws InterruptedException {
   if (up.tryLock(10, TimeUnit.MILLISECONDS)) {
    System.out.println(who + " picked up " + where + " " + this);
    return true;
   }
   return false;
  }

  public void putDown(Philosopher who, String name) {
   up.unlock();
   System.out.println(who + " put down " + name + " " + this);
  }

  @Override
  public String toString() {
   return "Chopstick-" + id;
  }
 }

 // One philosoper.
 public static class Philosopher implements Runnable {
  // Which one I am.
  private final int id;
  // The chopsticks on either side of me.
  private final ChopStick leftChopStick;
  private final ChopStick rightChopStick;
  // Am I full?
  volatile boolean isTummyFull = false;
  // To randomize eat/Think time
  private Random randomGenerator = new Random();
  // Number of times I was able to eat.
  private int noOfTurnsToEat = 0;

  /**
   * **
   *
   * @param id Philosopher number
   *
   * @param leftChopStick
   * @param rightChopStick
   */
  public Philosopher(int id, ChopStick leftChopStick, ChopStick rightChopStick) {
   this.id = id;
   this.leftChopStick = leftChopStick;
   this.rightChopStick = rightChopStick;
  }

  @Override
  public void run() {

   try {
    while (!isTummyFull) {
     // Think for a bit.
     think();
     // Make the mechanism obvious.
     if (leftChopStick.pickUp(this, "left")) {
      if (rightChopStick.pickUp(this, "right")) {
       // Eat some.
       eat();
       // Finished.
       rightChopStick.putDown(this, "right");
      }
      // Finished.
      leftChopStick.putDown(this, "left");
     }
    }
   } catch (Exception e) {
    // Catch the exception outside the loop.
    e.printStackTrace();
   }
  }

  private void think() throws InterruptedException {
   System.out.println(this + " is thinking");
   Thread.sleep(randomGenerator.nextInt(1000));
  }

  private void eat() throws InterruptedException {
   System.out.println(this + " is eating");
   noOfTurnsToEat++;
   Thread.sleep(randomGenerator.nextInt(1000));
  }

  // Accessors at the end.
  public int getNoOfTurnsToEat() {
   return noOfTurnsToEat;
  }

  @Override
  public String toString() {
   return "Philosopher-" + id;
  }
 }
 // How many to test with.
 private static final int NO_OF_PHILOSOPHER = 50;
 //private static final int SIMULATION_MILLIS = 1000 * 60 * 8;
 private static final int SIMULATION_MILLIS = 1000 * 10;

 public static void main(String args[]) throws InterruptedException {
  ExecutorService executorService = null;

  Philosopher[] philosophers = null;
  try {

   philosophers = new Philosopher[NO_OF_PHILOSOPHER];

   //As many forks as Philosophers
   ChopStick[] chopSticks = new ChopStick[NO_OF_PHILOSOPHER];
   // Cannot do this as it will fill the whole array with the SAME chopstick.
   //Arrays.fill(chopSticks, new ReentrantLock());
   for (int i = 0; i < NO_OF_PHILOSOPHER; i++) {
    chopSticks[i] = new ChopStick(i);
   }

   executorService = Executors.newFixedThreadPool(NO_OF_PHILOSOPHER);

   for (int i = 0; i < NO_OF_PHILOSOPHER; i++) {
    philosophers[i] = new Philosopher(i, chopSticks[i], chopSticks[(i + 1) % NO_OF_PHILOSOPHER]);
    executorService.execute(philosophers[i]);
   }
   // Main thread sleeps till time of simulation
   Thread.sleep(SIMULATION_MILLIS);
   // Stop all philosophers.
   for (Philosopher philosopher: philosophers) {
    philosopher.isTummyFull = true;
   }

  } finally {
   // Close everything down.
   executorService.shutdown();

   // Wait for all thread to finish
   while (!executorService.isTerminated()) {
    Thread.sleep(1000);
   }

   // Time for check
   for (Philosopher philosopher: philosophers) {
    System.out.println(philosopher + " => No of Turns to Eat =" + philosopher.getNoOfTurnsToEat());
   }
  }
 }
}
       
 

Wednesday, 16 September 2015

Java program to print reverse number triangle pattern......

Output Pattern-

              123456787654321
                1234567654321
                  12345654321
                    123454321  
                      1234321  
                        12321    
                          121    
                            1      

here is the code .....





       
class printPattern {
 public static void main(String[] args) {
  int ad = 8;
  for (int i = 0; i < 8; i++, ad--) {

   for (int r = 0; r < i; r++) {
    System.out.print(" ");
   }
   for (int k = 1,
    var = ad; k <=
    var; k++) {
    System.out.print(k);

   }
   for (int j = (ad - 1); j >= 1; j--) {
    System.out.print(j);
   }
   for (int r = 0; r < i; r++) {
    System.out.print(" ");
   }

   System.out.println(" ");
  }

 }
}

       
 

Tuesday, 15 September 2015

Trigonometric Sine function calculation using Java......


//Using the below series here is the code to calculate the Sine value

ExerciseBasics_TrigonometricSeries.png

NOTE-  value of x (the argument of sine function) is given in degree or you can                       modify the code to accept the input in radian 




       
public class sineFunction {
 public static void main(String[] args) {
   int numTerms = 4;
   double degree = 20;
   double argsinRadian;
   argsinRadian = (degree * 3.14) / 180;
   System.out.println("value of sin(" + argsinRadian + ") is -" + evaluateSine(argsinRadian, numTerms));
  } //main

 public static double evaluateSine(double argsinRadian, int numTerms) {
  double functionValue = argsinRadian;
  double value = argsinRadian;
  double squareValue = argsinRadian;
  squareValue = argsinRadian * argsinRadian;
  double temp = 0;
  int p = 3;
  for (int t = 2; t <= numTerms; t++) {
   temp = value * squareValue;
   value = temp;
   temp = temp / fact(p);
   p = p + 2;
   if (t % 2 == 0) {
    temp = temp * -1;
   }
   functionValue = functionValue + temp;
  }
  return functionValue;
 }
 public static int fact(int num) {
  int factorial = 1;
  for (int k = 1; k <= num; k++) {
   factorial = factorial * k;
  }
  return factorial;
 }
}