I am trying to write a program that returns all permutations of an ArrayList. So far it's only working when using 0, 1, or 2 elements. However I know there is something wrong with my final "else" statement, I just cannot figure out what. This is pretty confusing to me and I'm not quite sure how to go about it...
import java.util.ArrayList;
public class Permutation
{
public static ArrayList<ArrayList<Integer>> permutation(final ArrayList<Integer> list)
{
ArrayList<Integer> yourList = list;
return insertTypePermutation(yourList);
}
public static ArrayList<ArrayList<Integer>> insertTypePermutation(ArrayList<Integer> yourList)
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for(int i = 0; i < yourList.size(); i++)
{
arrayList.add(yourList.get(i));
}
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(yourList.size() < 2)
{
result.add(yourList);
return result;
}
else if(yourList.size() == 2)
{
result.add(yourList);
result.add(reverse(yourList));
return result;
} //problem starts: -----------------------------------------------
else
{
int firstEntry = yourList.get(0);
yourList.remove(0);
result = insertTypePermutation(yourList);
int currResultSize = result.size();
int currResultElementSize = result.get(0).size();
for(int i = 0; i < currResultSize; i++)
{
for(int j = 0; j <= currResultElementSize; j++)
{
ArrayList<Integer> tempResult = result.get(0);
tempResult.add(j, firstEntry);
result.add(tempResult);
if(j == currResultElementSize)
{
result.remove(0);
}
}
}
return result;
} //problem ends ^ -------------------------------------------
}
public static ArrayList<Integer> reverse(final ArrayList<Integer> someList)
{
ArrayList<Integer> tempList = new ArrayList<Integer>();
for(int i = 0; i < someList.size(); i++)
{
tempList.add(someList.get(i));
}
int temp = tempList.get(0);
tempList.remove(0);
tempList.add(temp);
return tempList;
}
}
Aucun commentaire:
Enregistrer un commentaire