Array processing function

The main problem with this code is that it assumes that

  1. the parameter arr1 is not null in other words the array exists and
  2. if the array exists it contains at least 20 elements

It would be best if we create a function that avoids both these issues like this

float[] coord(float [] target) {
  if (target == null) { 
    // create the array if it doesn't exit
    target = new float[20];
  }
  for (int x = 0; x < target.length; x++) { 
    // for each element in the array assign a random number between 0 and 1
    target[x] = random(1);
  }
  return target;
}

If the array does not exist i.e. target == null then it creates a new array otherwise it uses the existing array.

Notice the for loop uses target.length to find the number of elements in an array. This is a safe way to do it.

The following sketch shows it in action. Press ‘n’ key for a new array or ‘e’ key to use an existing array

float[] a = new float[20];

void setup() {
  size(640, 480);
}

float[] coord(float [] target) {
  if (target == null) {
    target = new float[20];
  }
  for (int x = 0; x < target.length; x++) {
    target[x] = random(1);
  }
  return target;
}

void keyTyped() {
  if (key == 'n') { // replace existing array with new with random data
    a = coord(null);
  }
  if (key == 'e') { // populate existing array with new random data
    a = coord(a);
  }
  println("-------------------------------------");
  println(a);
}

void draw() { 
  background(100, 10, 100);
  fill(0, 255, 0);
  noStroke();
  for (int i = 0; i < a.length; i++) {

    ellipse((i*20)+20, a[i]*height, 16, 16);
  }
}
2 Likes