Wednesday, March 16, 2011

Permutations of all of N elements without allowing repetition - JAVA

This function generates the permutations of all of N elements given in an ArrayList of Strings. But if two strings are the same in the given array, it does not permute any pair of equal strings.
For example, if we have ["cat", "dog", "cat", "fox"]
we do not want to return ["cat", "cat", "dog", "fox"] twice for instance.
-------------------------------

public static ArrayList<ArrayList<String>> P_n_of_n_with_copies_present(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);

if(first.equals(ith) && (i > 0))
{
continue;
}

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_with_copies_present(copy, prev);
prev.remove(prev.size() - 1);
permutations.addAll(thisPermutations);
items.add(0, ith);
}


return permutations;
}

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

No comments:

Post a Comment