Make array length random

I have these worm things which are just a bunch of circles in a line that are falling down the screen and want to make it so that every time they go off screen they reset back to zero with a different amount of circles, is there a way I can change the how many numbers are stored in the array?

This is what I have so far


int  [] num=new int [4];
int []numx=new int[4];

int rand =int(random(-2,7));

float xball=400;
float yball=200;


void setup() {
  size(400, 400);

}

void draw() {
  
  noStroke();
  background(255);
  for ( int i=0; i<num.length; i++)   
  {
     fill(int(random(255)),int(random(255)),int(random(255)));
      for( int  j =0; j<numx.length;j++)
      {
  ellipse(numx[j],num[i], 40, 40);
  
  num[i]+=rand;
       rand =int(random(-2,7));

       ellipse(xball,yball, 20, 20);
    
    if (dist(xball, yball, numx[j], num[i])<=30)
      println("you lose");
 
      if (num[i]>=height)
  {     
    for(i=0;i<num.length; i++)
    num[i]=-50;
    
 for ( j=0; j<numx.length; j++)    
   numx[j]=int(random(height)); 
  }
  
      }
  }
  
  if(keyPressed)
  {
   if (key ==CODED)
  {
    if (keyCode==LEFT)
      xball-=10;
      
    else if (keyCode == RIGHT)
     xball+=10;

    else  if (keyCode ==UP)
     yball-= 10;

    else if (keyCode ==DOWN)
      yball+=10;
  }
  }
 
}
1 Like

I did not completely understand your whole problem, but as for the question in your title I can say that you can do, for example:

num = new int[int(random(50))];

And you’ll turn num into a new, empty array with 0 to 50 elements.

1 Like

Hello! I figured out another way to do it with expand, but thank you anyways!

I also might want to add that java’s cool and it’s letting you do whatever you want in this case by allowing you to dynamically allocate an array. However, this is something you can’t typically do because array storage is allocated at compile time in most languages. I would never want to randomly allocate memory like this. It’s not very elegant and it can be hard to debug.

I’m glad you’ve found your own solution and I would hope that you would share it so other users learn from it but I also feel like it’s hasty to jump to the conclusion that allocating memory randomly is safe.

Far be it from me to tell you not to do something and not suggest an alternative, both Vector and ArrayList are viable alternatives (that are actually based on the primitive Array)

An example in your implementation would be to use an ArrayList to make a blank ArrayList and then to use ArrayList.add(); to add an arbitrary amount of int objects to that list.

Either way good luck I hope you got exactly what you needed.

1 Like