Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 13-2: Random number distribution

// An array to keep track of how often random numbers are picked.
float[] randomCounts;

void setup() {
  size(200,200);
  randomCounts = new float[20];
}

void draw() {
  background(255);
  
  // Pick a random number and increase the count
  int index = int(random(randomCounts.length));
  randomCounts[index] ++ ;
  
  // Draw a rectangle to graph results
  stroke(0);
  fill(175);
  for (int x = 0; x < randomCounts.length; x ++ ) {
    rect(x*10,0,9,randomCounts[x]);
  }
}

2 Comments

»

  1. 1.
    In this example, where is the part of initializing an array “radomCounts”?
    I think there is no initializing and randomCounts[0] ~ randomCounts[19] have same default value “0.00″… right? (I’m confusing about array’s data have default value when there’s no initializing start values of array’s data.)

    2.
    I tried to ” print(randomCounts[0]); “, and the value of randomCounts[0] increased by 0.01, not by 1 that the value I expected..
    I guess, according to ” randomCounts[ index ] ++; “, the value of randomCounts[0] increase by 1.
    I changed ” randomCounts[index]++ ” to ” randomCounts[index] += 3; “, and the value of randomCounts[0] increased by 0.03, not by 3 that I expected… Explain me, please…;-)

    Comment by P3HO — March 10, 2010 @ 12:08 pm

  2. 1. Yes, technically speaking, it would be better for me to have written:

      for (int i = 0; i < randomCounts.length; i++ ) {
        randomCounts[i] = 0;
      }
    

    It's always a good idea to initialize. Since the default value for a float is 0, the code works without it anyway.

    2. I'm not seeing this. When I add:

      println(randomCounts[0]);
    

    to the end of draw(), the output I see is 0.0, 1.0, 2.0, etc.

    Comment by Daniel Shiffman — March 11, 2010 @ 10:16 am

Leave a comment