Towers of Hanoi
public class Towers
{
public static void towers (int n, char source, char spare, char dest)
{
if (n == 1)
System.out.println (source + "->" + dest);
else
{
towers (n - 1, source, dest, spare);
System.out.println (source + "->" + dest);
towers (n -1, spare, source, dest);
}
}
public static void main (String[] args)
{
towers (3, 'A', 'B', 'C');
}
}
Permutation
public class Permute
{
public static void printArray (char[] a)
{
for (int i = 0; i < a.length; i++)
{
System.out.print (a[i] + " ");
}
System.out.println();
}
public static void swap (char[] a, int i, int j)
{
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void permute (char[] a, int lo)
{
int hi = a.length;
if (lo == hi)
{
printArray (a);
}
else
{
for (int i = lo; i < hi; i++)
{
swap (a, lo, i);
permute (a, lo + 1);
swap (a, i, lo);
}
}
}
public static void main (String[] args)
{
char[] a = {'A', 'B', 'C', 'D'};
permute (a, 0);
}
}
All Subsets
import java.util.*;
public class Subsets
{
public static void printArray (int[] a)
{
for (int i = 0; i < a.length; i++)
{
if (a[i] != -1)
{
System.out.print (a[i] + " ");
}
}
System.out.println ();
}
public static int[] copy (int[] a)
{
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
{
b[i] = a[i];
}
return b;
}
public static void subsets (int[] a, int[] b, int index)
{
if (index == a.length)
{
printArray (b);
}
else
{
int[] c = copy (b);
b[index] = a[index];
subsets (a, b, index + 1);
subsets (a, c, index + 1);
}
}
public static void main (String[] args)
{
int[] a = {15, 9, 30, 21, 19, 3, 12, 6, 25, 27};
int[] b = new int [a.length];
Arrays.fill (b, -1);
subsets (a, b, 0);
}
}
Combination
public class Combine
{
public static void printArray (int[] b, int size)
{
for (int i = 0; i < size; i++)
{
System.out.print (b[i] + " ");
}
System.out.println ();
}
public static void combine (int[] a, int[] b, int aIdx, int bIdx, int size)
{
int range = a.length - size + 1;
if (bIdx == size)
{
printArray (b, size);
}
else
{
while (aIdx < range + bIdx)
{
b[bIdx++] = a[aIdx++];
combine (a, b, aIdx, bIdx, size);
bIdx--;
}
}
}
public static void main (String[] args)
{
int [] a = {1, 2, 3, 4, 5};
int [] b = {0, 0, 0, 0, 0};
int size = 3;
combine (a, b, 0, 0, size);
}
}