0

I'm trying to create an array list of string arrays containing all possible combinations of 0s and 1s, in four dimensions. That is, [0,0,0,0] is one combination and [0,0,0,1] is another. There are $2^4$ total combinations, so I'm using several nested loops to generate this array list. However, when I try to run the loop, I get an "out of memory" error. Take a look:

String[] t4 = new String[4]; 

ArrayList<String[]> list4 = new ArrayList<String[]>();

for(int i=0; i<= 1; i++)
{
String count = Integer.toString(i);    
t4[0]=count;
list4.add(t4); 
 for(int j=0; j<= 1; j++)
 {
 String count1 = Integer.toString(j);    
 t4[1]=count1;
 list4.add(t4);
  for(int k=0; k<= 1; k++)
  {
  String count2 = Integer.toString(k);    
  t4[2]=count2;
  list4.add(t4); 
   for(int m=0; m<= 1;)
   {
   String count3 = Integer.toString(m);    
   t4[3]=count3;
   list4.add(t4);
   t4 = new String[4];
   }
  }
 }
}

Is there something wrong with my loop? Or is there another way to generate the desired array list?

1
  • 1
    You forgot to increment m in your m for loop. It's an infinite loop.
    – rgettman
    Commented Aug 16, 2013 at 19:18

4 Answers 4

8

You have:

for(int m=0; m<= 1;)

You need:

for(int m=0; m<= 1; ++ m)

Otherwise it's an infinite loop that ultimately ends up filling up list4 with String[4]'s until you run out of memory.

By not incrementing m, m stays at 0 and the loop condition is always true.

1
  • Good catch, and quick as well.
    – nanofarad
    Commented Aug 16, 2013 at 19:20
2

You don't modify m

Change this

for(int m=0; m<= 1;)

to

for(int m=0; m<= 1;m++)
0

In your inner 'FOR' loop, you forgot to increment variable 'm' and hence it is going into infinite loop.

0

The problem was with absence of an m++. Also, the loop should look like this:

for(int i=0; i<= 1; i++)
{
String count = Integer.toString(i);    
 for(int j=0; j<= 1; j++)
 {
 String count1 = Integer.toString(j);    
  for(int k=0; k<= 1; k++)
  {  
  String count2 = Integer.toString(k);    
   for(int m=0; m<= 1;m++)
   {
   String count3 = Integer.toString(m);    
   t4[0]=count;   
   t4[1]=count1;
   t4[2]=count2;    
   t4[3]=count3;
   list4.add(t4);
   t4 = new String[4];
   }
  }
 }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.