Elton.fd
Elton.fd

Reputation: 1595

help for completing permutation class

I have created a class for calculating the permutation of integer numbers with tree:

 public class Permut {

ArrayList<Integer> list = new ArrayList<Integer>();
public static void main(String args[])
{
    ArrayList<Integer> t = new ArrayList<Integer>();
    t.add(1);
    t.add(2);
    t.add(3);
    Permut permutation = new Permut();
    permutation.permutation(t);
}
public ArrayList<List> permutation(ArrayList<Integer> array)
{
    Node node = new Node();  //root
    node.data = -1;
    node.depth = 1;
    Node parent = node;

    permut(parent,array,node.depth);


    return null;

}
private void permut(Node parent, ArrayList<Integer> array, int i) {
    // TODO Auto-generated method stub
    ArrayList<Integer> noNumbers = new ArrayList<Integer>();
    for (Integer in : array) {
        if(!noNumbers.contains(in) || !parent.noList.contains(in)|| i<array.size())
        {
        Node no = new Node();
        no.data = in;
        no.parent = parent;
        no.depth = i+1;
        no.noList.add(in);
        noNumbers.add(in);
        permut(no,array,no.depth);
        }

    }


}
   }

My program also has a node class, each node has data, parent, depth and also a nList that keeps all of the datas of its parent and grandparent and … I want to have permutation by reading the datas from the root to each leaf. But this code cause java.lang.StackOverflowError At the line

  for (Integer in : array) {  

how can I complete my code? Would you please guid me? thanks

Upvotes: 1

Views: 291

Answers (1)

Raskolnikov
Raskolnikov

Reputation: 296

You are getting a stack overflow because noNumbers is a newly initialized ArrayList. Right after you create it you check to see if it doesn't contain "in"

 ArrayList<Integer> noNumbers = new ArrayList<Integer>();
for (Integer in : array) {
    if(!noNumbers.contains(in) || !parent.noList.contains(in)|| i<array.size())
    {

This will run forever, because each new level's noNumbers will not contain anything on its first iteration.

Upvotes: 2

Related Questions