Wednesday, March 16, 2011

Permutations of all of N elements - JAVA

This code generates the permutations of all of N elements given in an ArrayList of Strings.

-----------------------

public static ArrayList<ArrayList<String>> P_n_of_n(ArrayList<String> items, ArrayList<String> prev)
{
ArrayList<ArrayList<String>> permutations = new ArrayList<ArrayList<String>>();


if(items.size() == 0)
{
ArrayList<String> copy = new ArrayList<String>();
for(int i = 0; i < prev.size(); i++)
{
copy.add(prev.get(i));
}
permutations.add(copy);
}


for (int i = 0; i < items.size(); i++)
{
String first = items.get(0);
String ith = items.get(i);
items.set(i, first);
items.remove(0);

ArrayList<String> copy = new ArrayList<String>();
for(int j = 0; j < items.size(); j++)
{
copy.add(items.get(j));
}

prev.add(ith);
ArrayList<ArrayList<String>> thisPermutations = P_n_of_n(copy, prev);
prev.remove(prev.size() - 1);
permutations.addAll(thisPermutations);
items.add(0, ith);
}


return permutations;
}

-----------------------


MArio

No comments:

Post a Comment