Monday, September 8, 2014

Coin change problem in Java


Infinite no of {25,10,5,1} no. of ways to representing n.
// Comment

//Inputs:
  int[] denoms = {25,10,5,1};
  int[][] map = new int[100+1][denoms.length];
  System.out.println(makeChange(100, denoms, 0));
  System.out.println(makeChangeDP(100, denoms, 0, map));



// Recursive algorithm
 
 public static int makeChange(int amount, int[] denoms, int index)
 {
  if(index >= denoms.length-1) return 1;
  
  int denomAmount = denoms[index];
  int ways = 0;
  
  for(int i = 0; i*denomAmount <= amount; i++)
  {
   int amountRemaining = amount-i*denomAmount;
   ways += makeChange(amountRemaining, denoms, index+1);
  }
  
  return ways;
 }
 
// Dynamic programming.. map[amount+1][denoms.length]
 
 public static int makeChangeDP(int amount, int[] denoms, int index, int[][] map)
 {
  if(map[amount][index] != 0) return map[amount][index];
   
  if(index >= denoms.length-1) return 1;

  
  int denomAmount = denoms[index];
  int ways = 0;
  
  for(int i = 0; i*denomAmount <= amount; i++)
  {
   int amountRemaining = amount-i*denomAmount;
   ways += makeChange(amountRemaining, denoms, index+1);
  }
  map[amount][index] = ways;
  return ways;
 }

Place 8 queens on chess board in such a way that other queens are not in same row, column and diagonally in Java


//
// Comment

 public static final int chessGridSize = 8;

 public static void placeQueens(List list, Integer[] columns,
   int row) {
  if (row == chessGridSize ) {
   list.add(columns.clone());
  } else {
   for (int col = 0; col < chessGridSize; col++) {
    if (canPlaceQueen(columns, row, col)) {
     columns[row] = col;
     placeQueens(list, columns, row + 1);
    }

   }
  }
 }

 private static boolean canPlaceQueen(Integer[] columns, int row1, int col1) {

  for (int row2 = 0; row2 < row1; row2++) {
   int col2 = columns[row2];

   if (col1 == col2)
    return false;

   if (Math.abs(col2 - col1) == Math.abs(row2 - row1))
    return false;
  }
  return true;
 }