Reputation: 113
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?
Upvotes: 0
Views: 485
Reputation: 113
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];
}
}
}
}
Upvotes: 0
Reputation: 65
In your inner 'FOR' loop, you forgot to increment variable 'm' and hence it is going into infinite loop.
Upvotes: 0
Reputation: 14413
You don't modify m
Change this
for(int m=0; m<= 1;)
to
for(int m=0; m<= 1;m++)
Upvotes: 2
Reputation: 40356
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.
Upvotes: 8