Is there a way to randomize the loop increase in for loop?

Samit Paudel :

I needed a for loop to increase randomly between a given range (1 to 5). I've tried the following set of codes but it does not seem to work. This code is written for Processing which is based on Java. My intention was to create a canvas with random points of different color from the background to get paper like texture.

float x = 0;
float y = 0;
float xRandom = x + random(1, 5);
float yRandom = y + random(1, 5);

void setup() {
  size(800, 800);
}

void draw() {
  background(#e8dacf);
  for(float x; x <= width; xRandom){
    for (float y ; y <= height; yRandom){
      fill(#f0e2d7);
      stroke(#f0e2d7);
      point(x, y);
    }
  }
Rabbid76 :

If you want to step forward by a random value, then you have to increment the control variables x and y randomly:

for (float x=0; x <= width; x += random(1, 5)){

    for (float y=0; y <= height; y += random(1, 5)){

        fill(#f0e2d7);
        stroke(#f0e2d7);
        point(x, y);
    }
}

Note, with this distribution, the dots are aligned to columns, because the x coordinates stay the same while the inner loop iterates.
For a completely random distribution, you have to compute the random coordinates in a single loop. e.g:

int noPts = width * height / 9;
for (int  i = 0; i < noPts; ++i ){

   fill(#f0e2d7);
   stroke(#f0e2d7);
   point(random(1, width-1), random(1, height-1));
}

Of course some may have to same coordinate, but that shouldn't be noticeable with this amount of points.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422946&siteId=1