Wednesday, 9 December 2015

Tic-Tac-Toe Game using Java.......

Features - 1.This program always takes constant time for playing a move and       evaluating winning condition.

2.Game can be played on board of any size ,currently I've configured it for max Board size of 10 .

3.Currently only multiplayer mode is implemented ,single player with bot will be implemented soon .

NOTE-  Conventions to play Tic-Tac-Toe game are as follows...
1.When it asked for size of the board enter single digit number for e.g -if you want to play on 3*3 then just enter "3" (without quotes of course) and press "enter".

         
 2.When you want to play a move enter the row and column index of the position separated by a space .
 e.g - If you want to enter a move on first column of first row then just                     enter "1 1" ( without double quotes ) and then press "enter".  

here is the code ...............


       

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.*;

public class TicTacToeProblem {
 static int size;
 static int mode;
 static HashMap < String, ArrayList < String >> player1RowsAndDiagonals = new HashMap < String, ArrayList < String >> (); //to keep track of rows and diagonal formation for player 1 
 static HashMap < String, ArrayList < String >> player2RowsAndDiagonals = new HashMap < String, ArrayList < String >> (); //to keep track of rows and diagonal formation for player 2
 static HashMap < String, ArrayList < String >> player1Columns = new HashMap < String, ArrayList < String >> (); //to keep track of column formation for player 1 
 static HashMap < String, ArrayList < String >> player2Columns = new HashMap < String, ArrayList < String >> (); //to keep track of column formation for player 2 
 static HashSet < String > filledPositions = new HashSet < String > ();

 public static void main(String[] args) throws NumberFormatException,
  IOException {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.println("Please enter the size of board in numeral");
   size = Integer.parseInt(br.readLine());

   while ((size > 10) == true) {
    System.out.println("Max size allowed is 10");
    System.out.println("please re enter the size");
    size = Integer.parseInt(br.readLine());
   }
   System.out.println("please enter playing mode number");
   System.out.println("1.two player");
   System.out.println("2.with bot");
   mode = Integer.parseInt(br.readLine());
   while (mode != 1 && mode != 2) {
    System.out.println("Please enter appropriate choice of mode 1 or 2");
    mode = Integer.parseInt(br.readLine());
   }
   if (mode == 1) {
    System.out.println("Initializing Setup..........");
    multiplayer(size);
   } else
    withBot(size);
   br.close();
  }

 public static void multiplayer(int size) throws IOException {
  String[] playerMove = null;
  String move = null;
  int coordinateX;
  int coordinateY;
  int player;
  int secondDiagonalSum = size + 1;
  int maxMoves = size * size;

  for (int i = 1; i <= size; i++) { //here just initializing arrayLists for each rows and each columns for both players
   ArrayList < String > rowList1 = new ArrayList < String > ();
   ArrayList < String > rowList2 = new ArrayList < String > ();
   ArrayList < String > columnList1 = new ArrayList < String > ();
   ArrayList < String > columnList2 = new ArrayList < String > ();
   player1RowsAndDiagonals.put((new Integer(i).toString()), rowList1);
   player2RowsAndDiagonals.put((new Integer(i).toString()), rowList2);
   player1Columns.put((new Integer(i).toString()), columnList1);
   player2Columns.put((new Integer(i).toString()), columnList2);
  }

  ArrayList < String > player1diag1 = new ArrayList < String > (); //here initializing arrayLists to keep track of both the diagonals for both players
  ArrayList < String > player1diag2 = new ArrayList < String > ();
  ArrayList < String > player2diag1 = new ArrayList < String > ();
  ArrayList < String > player2diag2 = new ArrayList < String > ();

  player1RowsAndDiagonals.put("diag1", player1diag1);
  player1RowsAndDiagonals.put("diag2", player1diag2);
  player2RowsAndDiagonals.put("diag1", player2diag1);
  player2RowsAndDiagonals.put("diag2", player2diag2);

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

  System.out.println("OK,now start playing enter your choices alternatively");

  for (int i = 0; i < maxMoves; i++) {
   if (i % 2 == 0) {
    System.out.println("player 1 turn");
    player = 1;
   } else {
    System.out.println("player 2 turn");
    player = 2;
   }
   move = br.readLine();
   while (filledPositions.contains(move) == true) { //check for already played Move
    System.out.println("this move has been already played please enter another move");
    move = br.readLine();
   }
   filledPositions.add(move);
   playerMove = move.split(" ");
   coordinateX = Integer.parseInt(playerMove[0]);
   coordinateY = Integer.parseInt(playerMove[1]);

   switch (player) {
    case 1:
     if (playerMove[0].equals(playerMove[1])) { //condition for one of the position in diagonal one
      player1RowsAndDiagonals.get("diag1").add(playerMove[1]);
      player1RowsAndDiagonals.get(playerMove[0]).add(playerMove[1]);
      player1Columns.get(playerMove[1]).add(playerMove[0]);

      if ((coordinateX + coordinateY) == secondDiagonalSum) //condition for one of the position in diagonal two 
       player1RowsAndDiagonals.get("diag2").add(playerMove[1]);

      if ((player1Columns.get(playerMove[1]).size() == size) || (player1RowsAndDiagonals.get("diag1").size() == size) || (player1RowsAndDiagonals.get(playerMove[0]).size() == size) || (player1RowsAndDiagonals.get("diag2").size() == size)) {
       System.out.println("Player 1 wins game is finished");
       return;
      }
     } else {
      player1RowsAndDiagonals.get(playerMove[0]).add(playerMove[1]);
      player1Columns.get(playerMove[1]).add(playerMove[0]);

      if ((coordinateX + coordinateY) == secondDiagonalSum)
       player1RowsAndDiagonals.get("diag2").add(playerMove[1]);

      if ((player1Columns.get(playerMove[1]).size() == size) || (player1RowsAndDiagonals.get("diag1").size() == size) || (player1RowsAndDiagonals.get(playerMove[0]).size() == size) || (player1RowsAndDiagonals.get("diag2").size() == size)) {
       System.out.println("Player 1 wins game is finished");
       return;
      }
     }
     break;
    case 2:
     if (playerMove[0].equals(playerMove[1])) {
      player2RowsAndDiagonals.get("diag1").add(playerMove[1]);
      player2RowsAndDiagonals.get(playerMove[0]).add(playerMove[1]);
      player2Columns.get(playerMove[1]).add(playerMove[0]);

      if ((coordinateX + coordinateY) == secondDiagonalSum)
       player2RowsAndDiagonals.get("diag2").add(playerMove[1]);

      if ((player2Columns.get(playerMove[1]).size() == size) || (player2RowsAndDiagonals.get("diag1").size() == size) || (player2RowsAndDiagonals.get(playerMove[0]).size() == size) || (player2RowsAndDiagonals.get("diag2").size() == size)) {
       System.out.println("Player 1 wins game is finished");
       return;
      }
     } else {
      player2RowsAndDiagonals.get(playerMove[0]).add(playerMove[1]);
      player2Columns.get(playerMove[1]).add(playerMove[0]);

      if ((coordinateX + coordinateY) == secondDiagonalSum)
       player2RowsAndDiagonals.get("diag2").add(playerMove[1]);

      if ((player2Columns.get(playerMove[1]).size() == size) || (player2RowsAndDiagonals.get("diag1").size() == size) || (player2RowsAndDiagonals.get(playerMove[0]).size() == size) || (player2RowsAndDiagonals.get("diag2").size() == size)) {
       System.out.println("Player 2 wins game is finished");
       return;
      }
     }
     break;
    default:
     break;
   }
  } //end of loop 
  System.out.println("Match Tie NO one Wins");
 }



 public static void withBot(int size) {
  System.out.println("Working on it, this mode will be added soon till then keep playing multiplayer mode");
  return;
 }
}

       
 

Tuesday, 17 November 2015

Java Program to find Minimum steps to make an integer from two variables by repeatedly adding them ......

Problem Statement- Harsh just loves numbers and loves to have fun with them . Apparently he has two numbers with him , say X and Y . Both of them are integers . Now from these numbers he wants another number , say L . But he doesn’t know how to derive it and needs your help . Given the two numbers you can add one to another , and you can do this any number of times . For example, you can add X to Y , or Y to X , and this can be done until any combination makes either X equal toL or Y equal to L .

“Well , this might actually lead to a solution”, said Harsh, ”but can you do it in a minimum number of operations ?”.
Just to make this problem a little simple let’s assume both the values of X and Y is 1 .
Input Format:
The first line contains T, the number of test cases. For each test case, the first line contains L ,the value that Harsh wants .
Output Format:
For each test case, output the required minimum number of operations .

Problem Link- ( https://www.hackerearth.com/problem/algorithm/simple-addition )

here is the code ....


       
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class TestClass {
 static int evaluateStrings(int a, int b) {
  if (b == 0 && a != 1) return 100000000;
  if (b == 0 && a == 1) return -1;
  else return (a / b + evaluateStrings(b, a % b));
 }

 public static void main(String[] args) throws IOException {

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String line = br.readLine();
  int N = Integer.parseInt(line);
  for (int i = 1; i <= N; i++) {

   int x = Integer.parseInt(br.readLine());
   int ans = 100000000;
   for (int j = 1; j <= x; j++) {
    int tmp = evaluateStrings(x, j);

    if (tmp < ans) ans = tmp;
   }
   System.out.println(ans);
  }


 }
}

       
 

Tuesday, 20 October 2015

Longest common subsequence between two strings using Java ..............

here is  the code........

NOTE:- Here the program is printing the length of the longest common           

              subsequence and also the evaluated sequence. 


       
public class LCS {

 public static void main(String[] args) throws Exception {

  Object[] arr = new Object[2];
  arr = evaluateLCS("suman", "paras");
  int t = arr[1].toString().length() - 1;
  System.out.println("length of longest common subsequence is " + Integer.parseInt(arr[0].toString()));
  System.out.println("the required longest subsequence is " + recursion_string(arr[1].toString(), t));
 }

 public static Object[] evaluateLCS(String first, String second) {
  Object[] arr = new Object[2];
  StringBuffer sequence = new StringBuffer();
  int length = 0;
  if (first.length() == 0 || second.length() == 0) {
   arr[0] = new Integer(0);
   arr[1] = "";
   return arr;
  } else {
   if (first.charAt(first.length() - 1) == second.charAt(second
     .length() - 1)) {
    arr = evaluateLCS(first.substring(0, first.length() - 1),
     second.substring(0, second.length() - 1));
    arr[0] = new Integer(1 + Integer.parseInt(arr[0].toString()));
    arr[1] = (Object) sequence.append(
     first.charAt(first.length() - 1)).append(arr[1]);
    return arr;
   } else {
    Object[] arr1 = new Object[2];
    arr = evaluateLCS(first.substring(0, first.length() - 1),
     second);
    arr1 = evaluateLCS(first,
     second.substring(0, second.length() - 1));
    if (Integer.parseInt(arr[0].toString()) >= Integer
     .parseInt(arr1[0].toString()))
     return arr;
    else
     return arr1;
   }

  }

 }

 public static int max(Object[] arr1, Object[] arr2) {
  int max1 = Integer.parseInt(arr1[0].toString());
  int max2 = Integer.parseInt(arr2[0].toString());

  if (max1 >= max2)
   return max1;
  else
   return max2;
 }

 public static String recursion_string(String name, int t) throws Exception {

  if (name.length() == 0) {
   return "";
  }
  if (name.length() == 1) {
   return name;
  }

  String start = name.substring(t);

  String remainder = name.substring(0, t);
  t--;

  return (start + recursion_string(remainder, t));


 }
}

       
 

Wednesday, 7 October 2015

Breadth First Search of a graph using Java....

NOTE :- while giving input to the adjacency matrix just put "1" against the entry of a[ i ][ j ] if there                  is a path exist between node " i " and " j " or put " 0 " otherwise .

Enter the number of nodes in the graph
4
Enter the adjacency matrix
0 1 0 1
0 0 1 0
0 1 0 1
0 0 0 1
Enter the source for the graph
1
The BFS traversal of the graph is 
1 2 4 3

so here is the code .....



       
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFS {
 private Queue < Integer > queue;
 public BFS() {
  queue = new LinkedList < Integer > ();
 }
 public void bfs(int adjacency_matrix[][], int source) {
  int number_of_nodes = adjacency_matrix[source].length - 1;
  int[] visited = new int[number_of_nodes + 1];
  int i, element;
  visited[source] = 1;
  queue.add(source);
  while (!queue.isEmpty()) {
   element = queue.remove();
   i = element;
   System.out.print(i + "\t");
   while (i <= number_of_nodes) {
    if (adjacency_matrix[element][i] == 1 && visited[i] == 0) {
     queue.add(i);
     visited[i] = 1;
    }
    i++;
   }
  }
 }
 public static void main(String[] arg) {
  int number_no_nodes, source;
  Scanner scanner = null;
  try {
   System.out.println("Enter the number of nodes in the graph");
   scanner = new Scanner(System.in);
   number_no_nodes = scanner.nextInt();
   int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes + 1];
   System.out.println("Enter the adjacency matrix");
   for (int i = 1; i <= number_no_nodes; i++)
    for (int j = 1; j <= number_no_nodes; j++)
     adjacency_matrix[i][j] = scanner.nextInt();
   System.out.println("Enter the source for the graph");
   source = scanner.nextInt();
   System.out.println("The BFS traversal of the graph is ");
   BFS bfs = new BFS();
   bfs.bfs(adjacency_matrix, source);
  } catch (InputMismatchException inputMismatch) {
   System.out.println("Wrong Input Format");
  }
  scanner.close();
 }
}

       
 

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;
 }
}

       
 

Monday, 10 August 2015

Find Transitive relations in a graph represented via adjacency matrix using Java....

Problem:-Using the Java language, have the function TransitivityRelations(strArr) read the strArr parameter being passed which will make up an NxN matrix where the rows are separated by each pair of parentheses (the matrix will range from 2x2 to 5x5). The matrix represents connections between nodes in a graph where each node corresponds to the Nth element in the matrix (with 0 being the first node). If a connection exists from one node to another, it will be represented by a 1, if not it will be represented by a 0. For example: suppose strArr were a 3x3 matrix with input 

["(1,1,1)","(1,0,0)","(0,1,0)"], this means that there is a connection from node 0->0, 0->1, and 0->2. For node 1 the connections are 1->0, and for node 2 the connections are 2->1. This can be interpreted as a connection existing from node X to node Y if there is a 1 in the Xth row and Yth column. Note: a connection from X->Y does not imply a connection from Y->X. 

What your program should determine is whether or not the matrix, which represents connections among the nodes, is transitive. A transitive relationmeans that if the connections 0->1 and 1->2 exist for example, then there must exist the connection 0->2. More generally, if there is a relation xRy and yRz, then xRz should exist within the matrix. If a matrix is completely transitive, return the string transitive. If it isn't, your program should return the connections needed, in the following format, in order for the matrix to be transitive: (N1,N2)-(N3,N4)-(...). So for the example above, your program should return (1,2)-(2,0). You can ignore the reflexive property of nodes in your answers. Return the connections needed in lexicographical order [e.g. (0,1)-(0,4)-(1,4)-(2,3)-(4,1)]. 


Note:-This program is only for 3x3 matrix ,but you can extend to a program generic for any size matrix .

here is the code for it .....




       

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Transitive {

 public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String matrix = br.readLine();
  //String mat="[\"(1,1,1)\",\"(1,1,1)\",\"(1,1,0)\"]";
  System.out.println("the desired result is " + TransitiveRelations(matrix));

 }

 public static ArrayList < String > TransitiveRelations(String strArr) {

  int[][] mat = new int[3][3];

  ArrayList < String > aka = new ArrayList < String > ();
  String[] arr = strArr.split("\\)");

  String[] a1 = arr[0].split("\\(");
  String[] a2 = arr[1].split("\\(");
  String[] a3 = arr[2].split("\\(");

  String[] r1 = a1[1].split(",");
  String[] r2 = a2[1].split(",");
  String[] r3 = a3[1].split(",");

  for (int k = 0; k < 3; k++)
   mat[0][k] = Integer.parseInt(r1[k]);


  for (int s = 0; s < 3; s++)
   mat[1][s] = Integer.parseInt(r2[s]);


  for (int p = 0; p < 3; p++)
   mat[2][p] = Integer.parseInt(r3[p]);


  for (int h = 0; h < 3; h++) {
   for (int q = 0; q < 3; q++) {
    for (int e = 0; e < 3; e++) {
     if (h != q) {
      if (mat[h][e] == 1) {
       if (mat[e][q] == 1) {
        if (mat[h][q] == 1)
         continue;
        else aka.add(h + "-" + q);
       } else {
        aka.add(e + "-" + q);
        if (mat[h][q] == 1)
         continue;
        else aka.add(h + "-" + q);
       }
      } else {
       aka.add(h + "-" + e);
       if (mat[e][q] == 1) {
        if (mat[h][q] == 1)
         continue;
        else aka.add(h + "-" + q);
       } else {
        aka.add(e + "-" + q);
        if (mat[h][q] == 1)
         continue;
        else aka.add(h + "-" + q);

       }
      }
     }

    }
   }
  }
  ArrayList < String > a = new ArrayList < String > ();
  for (int t = 0; t < aka.size(); t++)
   if (!a.contains(aka.get(t)) == true)
    a.add(aka.get(t));

  return a;
 }

}
       
 

Find out minimum cost between two nodes in a weighted graph using greedy approach using java.....

Input :- 1.cost matrix for the graph is given via text file ,just write the matrix in the text file simply like we write normally and save it ,change the path of the file in the program too.

2.For those nodes which don't have direct paths between them corresponding entries in the input adjacency matrix via file should be "-1".
here is the code  ........





       
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ShortestPath {
 public static int count = 0;
 public static int[][] matrix;

 public static void main(String[] args) throws NumberFormatException, IOException {
  // TODO Auto-generated method stub
  File file = new File("C:/Users/gauravy/Desktop/matrix.txt");
  BufferedReader be = new BufferedReader(new FileReader(file));
  while ((be.readLine()) != null)
   count++;
  matrix = new int[count][count];
  String fileName = "C:/Users/gauravy/Desktop/matrix.txt";

  FileInputStream inputStream = new FileInputStream(fileName);
  BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));

  int lineCount = 0;
  String[] numbers;
  String line = null;
  while ((line = bf.readLine()) != null) {
   numbers = line.split(" ");
   for (int i = 0; i < count; i++) {
    matrix[lineCount][i] = Integer.parseInt(numbers[i]);
   }

   lineCount++;
  }
  bf.close();
  for (int l = 0; l < count; l++)
   for (int s = 0; s < count; s++)
    if (matrix[l][s] == -1) matrix[l][s] = Integer.MAX_VALUE;

  System.out.println("Minimum cost which we evaluated is " + minPath(matrix, 3, count - 1));
 }
 public static int minPath(int[][] mat, int i, int j) {
  int cost;
  if (i == j) return 0;
  else {
   int y = getNodeWithMinDistance(i);
   cost = matrix[i][y] + minPath(mat, y, j);
   if (cost < mat[i][j]) return cost;
   else return mat[i][j];
  }
 }

 public static int getNodeWithMinDistance(int source) {
  int min = matrix[source][source + 1];
  int minNeighbourNode = source + 1;
  for (int k = source + 1; k < count; k++) {
   if (matrix[source][k] < min) {
    min = matrix[source][k];
    minNeighbourNode = k;
   }
  }
  return minNeighbourNode;
 }
}

       
 

Friday, 24 July 2015

Java Programming solution to solve a problem on optimal assignments ,detailed problem statement is given below .....

/*Using the Java language, have the function OptimalAssignments(strArr) read strArr which will represent an NxN matrix and it will be in the following format: ["(n,n,n...)","(...)",...] where the n's represent integers. This matrix represents a machine at row i performing task at column j. The cost for this is matrix[i][j]. Your program should determine what machine should perform what task so as to minimize the whole cost and it should return the pairings of machines to tasks in the following format: (i-j)(...)... Only one machine can perform one task. For example: if strArr is ["(5,4,2)","(12,4,3)","(3,4,13)"] then your program should return (1-3)(2-2)(3-1) because assigning the machines to these tasks gives the least cost. The matrix will range from 2x2 to 6x6, there will be no negative costs in the matrix, and there will always be a unique answer*/


import java.util.*; 
import java.io.*;

class Function {  
  String OptimalAssignments(String strArr) { 
  
    // code goes here   
    /* Note: In Java the return type of a function and the 
       parameter types being passed are defined, so this return 
       call must match the return type of the function.
       You are free to modify the return type. */
       int[][] mat=new int[3][3];
       
       
       String[] arr=strArr.split("\\)");
        
        
        
        String[] a1=arr[0].split("\\(");
        String[] a2=arr[1].split("\\(");
        String[] a3=arr[2].split("\\(");
        
          String[] r1=a1[1].split(",");
          String[] r2=a2[1].split(","); 
          String[] r3=a3[1].split(",");  
          
          for(int k=0;k<3;k++)
            mat[0][k]=Integer.parseInt(r1[k]);


          for(int s=0;s<3;s++)
            mat[1][s]=Integer.parseInt(r2[s]);


          for(int p=0;p<3;p++)
            mat[2][p]=Integer.parseInt(r3[p]);
           
         /* for (int y=0;y<3;y++)
           for (int r=0;r<3;r++)
          System.out.println(mat[y][r]);
          */
          Function d=new Function();
         int[] sum=d.mincost_map(mat,0);
          strArr="\"(1-"+sum[0]+")(2-"+sum[1]+")(3-"+sum[2]+")\"";
    return strArr;
    
  } 
  
  
  public int[] mincost_map(int[][] a,int b){
 int[] c=new int[3];
 Function f=new Function();
 //int[][] arr=new int[b][b]; 
        c[0]=f.find_min(a,0,3);
        c[1]=f.find_min(a,1,c[0]);
        c[2]=f.find_min(a,2,c[1]);
 
 return  c;
  }
  
  public int find_min(int[][] a,int r,int num){
 int sum=a[r][0];
 int q=0;
for(int y=0;y<3;y++){
if(a[r][y]<sum)

if(y==num) 
continue;
else { sum=a[r][y]; q=y;}
}
}
return q;
  }
  
  public static void main (String[] args) throws Exception{  
    // keep this function call here     
    BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
    String str=s.readLine();
    Function c = new Function();
    //String str="[\"(5,4,2)\",\"(12,4,4)\",\"(3,4,13)\"]";
    System.out.print(c.OptimalAssignments(str));
  //Function c=new Function();

   
  
  //System.out.println(c.OptimalAssignments(str));
    
  }   
  
}


Tuesday, 21 July 2015

Java program to find out all possible expressions to insert '+' and '-' in between values 1..to ..9 so that the given sum of the expression remains constant ....like below

/*
Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100

*/


       
import java.util.ArrayList;
import java.util.Iterator;

public class TestIt {

 private static int SUM = 200;
 private static int[] values = {
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9
 };

 static ArrayList add(int digit, String sign, ArrayList branches) {
  for (int i = 0; i < branches.size(); i++) {
   branches.set(i, digit + sign + branches.get(i));
  }

  return branches;
 }

 static ArrayList f(int sum, int number, int index) {

  int digit = Math.abs(number % 10);
  //System.out.println(digit);
  if (index >= values.length) {
   if (sum == number) {
    ArrayList result = new ArrayList();
    result.add(Integer.toString(digit));
    return result;
   } else {
    return new ArrayList();
   }
  }

  ArrayList branch1 = f(sum - number, values[index], index + 1);
  ArrayList branch2 = f(sum - number, -values[index], index + 1);

  int concatenatedNumber = number >= 0 ? 10 * number + values[index] : 10 * number - values[index];
  ArrayList branch3 = f(sum, concatenatedNumber, index + 1);

  ArrayList results = new ArrayList();

  results.addAll(add(digit, "+", branch1));
  results.addAll(add(digit, "-", branch2));
  results.addAll(add(digit, "", branch3));

  return results;
 }

 public static void main(String[] args) {

  Iterator < String > itr = f(SUM, values[0], 1).listIterator();
  //for (String string :f(TARGET_SUM, VALUES[0], 1))
  if (itr.hasNext()) {
   System.out.println(itr.next());
  }

 }
}

       
 

Perfect numbers in a given range using Java........

Here is the code ....


       
import java.util.ArrayList;
import java.util.Iterator;

import java.util.List;

public class test5 {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  List d = getPerfectNumbers(1, 1000);

  Iterator itr = ((ArrayList < Integer > ) d).listIterator();

  while (itr.hasNext())
   System.out.println(itr.next());
 }


 public static java.util.List < Integer > getPerfectNumbers(int from, int to) {
  /*
    return a list of all perfect numbers in the given range inclusively.
    A perfect number is defined as a positive integer which is the sum of its positive divisors not including the number itself.
    For example: 6 is a perfect number because 6 = 1 + 2 + 3 (1, 2, 3 are divisors of 6)
    28 is also a perfect number: 28 = 1 + 2 + 4 + 7 + 14
   */
  int k;
  java.util.List < Integer > l = new ArrayList < Integer > ();
  for (int p = from; p <= to; p++) {
   k = sum(p);
   if (k == p) {
    l.add(p);

   }
  }
  return l;
 }


 public static int sum(int t) {
  int sum = 0;
  for (int i = 1; i < t; i++) {
   if (t % i == 0)
    sum = sum + i;
  }
  return sum;
 }

}

       
 

Java program to find sum of two elements closest to zero from an integer array ...

Here is the code ....


       
public class test3 {

 public static int getSumOfTwoClosestToZeroElements(int[] a) {
  /*
    Please implement this method to
    return the sum of the two elements closest to zero.
    If there are two elements equally close to zero like -2 and 2,
    consider the positive element to be "closer" to zero than the negative one.
   */
  int sum = 0;
  int h = 0;
  int[] d = new int[a.length + 1];
  d[0] = 0;

  for (int i = 1; i < a.length + 1; i++) {
   d[i] = a[h];
   h++;
  }



  int i = partition(d, 0, d.length);
  //System.out.println(i);

  for (int e = 0; e < d.length; e++)
   System.out.print(d[e] + "  ");
  System.out.println();



  int g = min(d, i + 1, d.length - 1);
  int g1 = max(d, 0, i - 1);
  //  System.out.println(g1);

  sum = g + g1;

  return sum;
 }

 public static int partition(int[] s, int i, int l) {
  int p = i;
  int a = i;
  for (int k = i + 1; k < s.length; k++) {
   if (s[p] > s[k]) {
    int temp;
    a++;
    temp = s[a];
    s[a] = s[k];
    s[k] = temp;
   }

  }
  int temp = s[a];
  s[a] = s[p];
  s[p] = temp;

  return a;
 }

 public static int min(int[] a, int f, int c) {
  int i = a[f];
  for (int s = f; s <= c; s++) {
   {
    if (i > a[s]) {
     i = a[s];

    }
   }
  }
  return i;
 }

 public static int max(int[] a, int f, int c) {
  int i = a[f];
  for (int s = f; s <= c; s++) {
   {
    if (i < a[s]) {
     i = a[s];

    }
   }
  }
  return i;
 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  int[] w = {
   1,
   -2,
   3,
   5,
   6,
   7,
   8,
   -3,
   -6,
   2
  };
  System.out.println("The required sum is- " + getSumOfTwoClosestToZeroElements(w));
 }

}

       
 

Java program to check whether a string is palindrome or not ....

Here is the code....


       

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class test2 {

 static boolean isPalindrome(String s) {

  int y = 0;
  for (int u = s.length() - 1; u >= 0; u--) {
   if (s.charAt(y) != s.charAt(u))
    return false;
   y++;
  }

  return true;
 }

 public static void main(String args[]) throws Exception {

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String str = br.readLine();
  System.out.println(isPalindrome(str));
 }

}
       
 

Thursday, 28 May 2015

Hamming distance between two integers using Java...

Here is the code.......


       

public class Hamming {

 public static int distance(int a, int b) {
  int k = 0;
  k = a ^ b;
  int sum = 0;
  int t = requiredbits(k); //it returns the required no. of bits to represent k in binary 
  int[] arr = new int[k];

  for (int f = t - 1; f >= 0; f--) //in this loop we are converting the no. k into binary 
  {
   arr[f] = k % 2;
   k = k / 2;

  }

  for (int r = 0; r < t; r++) // here counting number of 1's in the binary representation of k
  {

   if (arr[r] == 1)
    sum++;

  }
  return sum;
 }

 public static int requiredbits(int w) {
  int i = 0;
  while ((2 << i) <= w)
   i++;
  i++;
  return i;
 }

 public static void main(String args[]) throws Exception {

  int a = 3, b = 2;
  System.out.println("hamming distance between " + a + " and " + b + " is " + distance(a, b));
 }

}
       
 

Sunday, 24 May 2015

Number of bits required to represent a number in binary using Java....

Here is the code ....


       

import java.io.*;
import java.util.*;
public class Bitsrequired {

 public static int getRequiredNumberOfBits(int N) {
  int i = 0;
  while ((2 << i) <= N) {
   i++;
  }
  return ++i;
 }



 public static void main(String args[]) throws Exception {

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the number");
  int me = Integer.parseInt(br.readLine());

  getRequiredNumberOfBits(me);
  System.out.println(getRequiredNumberOfBits(me));


 }

}
       
 

Java program to reverse a string using recursion ....

Here is the code....


       
import java.io.*;
import java.util.*;
class reverse_string {

 public static String recursion_string(String name, int t) throws Exception {

  if (name.length() == 0) {
   return "";
  }
  if (name.length() == 1) {
   return name;
  }

  String start = name.substring(t);
  //System.out.println(start);

  String remainder = name.substring(0, t);
  t--;
  //System.out.println(remainder);
  //System.out.println(remainder);
  return (start + recursion_string(remainder, t));


 }

 public static void main(String args[]) throws Exception {
  String s = "cobra123";
  int l = s.length() - 1;
  //System.out.println(l);
  System.out.println(recursion_string(s, l));
 }

}

       
 

Convert decimal to binary using Java..........

here is the code ......


       
import java.io.*;
import java.util.*;
import java.math.*;
class decimal_to_binary {


 public static void main(String args[]) {
  int k = 10, i = 1;

  while ((2 << i) <= k) {
   i++;
  }
  i++;

  int[] a = new int[i];

  for (int n = i - 1; n >= 0; n--) {
   a[n] = k % 2;
   k = k / 2;
  }

  for (int g: a)
   System.out.print(g);

 }

}

       
 

Java program to convert binary to decimal ....

here is the code ......


       
import java.io.*;
import java.util.*;
class binary_to_decimal {

 public static void main(String args[]) {
  int[] a = {
   0,
   0,
   0,
   1,
   1,
   1
  };
  int sum = 0;

  for (int k = a.length - 1, h = 0; k >= 0; k--, h++) {
   sum = sum + a[k] * (1 << h);
  }
  System.out.println(sum);
 }

}

       
 

Saturday, 23 May 2015

Java program to print all the permutations of a string ...

here  is the code 


       
 import java.io.*;
 import java.util.*;
 class permute_string {
  public static ArrayList < String > getPerms(String s) {
   ArrayList < String > permutations = new ArrayList < String > ();
   if (s == null) { // error case
    return null;
   } else if (s.length() == 0) {
    permutations.add("");
    return permutations;
   }

   char first = s.charAt(0); // get the first character
   String remainder = s.substring(1); // remove the first character
   ArrayList < String > words = getPerms(remainder);
   for (String word: words) {
    for (int j = 0; j <= word.length(); j++) {
     permutations.add(insertCharAt(word, first, j));
    }
   }
   return permutations;
  }

  public static String insertCharAt(String word, char c, int i) {
   String start = word.substring(0, i);
   String end = word.substring(i);
   return start + c + end;
  }


  public static void main(String args[]) {


   System.out.println(getPerms(args[0]));
  }
 }

       
 

Wednesday, 20 May 2015

Sort an array of strings in a way so that all the anagrams will be adjacents in the sorted array using Java....

here is the code ..


       
import java.io.*;
import java.util.*;

class sortanagram {

 public static boolean anagram(String arg1, String arg2) {
  int f;
  int[] arr = new int[256];
  if (arg1.length() == arg2.length()) {
   for (int i = 0; i < arg1.length(); i++) {
    f = arg1.charAt(i);
    arr[f] = arr[f] + 1;
   }

   for (int k = 0; k < arg2.length(); k++) {
    f = arg2.charAt(k);
    arr[f] = arr[f] - 1;
   }
   for (int d = 0; d < 256; d++) {
    if (arr[d] != 0) {
     return false;
    }

   }
   return true;
  } else {
   return false;
  }

 }

 public static void main(String args[]) {

  String[] args3 = {
   "abcd",
   "save",
   "dcba",
   "dog",
   "easv",
   "god",
   "free"
  };
  String temp;
  int p;

  for (int i = 0; i < args3.length; i++) {
   p = i;
   for (int l = i + 1; l < args3.length; l++) {
    if (anagram(args3[i], args3[l]) == true) {


     p++;
     temp = args3[l];
     args3[l] = args3[p];
     args3[p] = temp;

    }

   }

  }

  for (int r = 0; r < args3.length; r++)
   System.out.println(args3[r]);

 }

}