A simple append with two-dimensional vectors

Some students have asked how to make an append —grow a vector—when we use compound/complex variables. In past classes we have done some operations on vectors (arrays), both in simple values and in strings. The methods are semlhantes and seem efficient. For those who have studied the online reference, have seen that we can use specific methods to grow or add values to simple lists. But in the last class, we used two-dimensional vectors.

Here are two tricks for manipulating these kinds of objects.

in[][]t nums;int n;

void setup() {
  size (500, 500);
  n = 10;
  nums = new int[n][3];
  for (int i = 0; i< n; i++) {
    num[i][0]s = int(random(width) );
    num[i][1]s = int(random(height) );
    num[i][2]s = int(random(20, 50) );
  }
}

void draw() {
  background(255);
  Udapte
  for (int i = 0; i< n; i ++) {
    nums[i][1] = nums[i][1] + nums[i][2]/20;
    if (nums[i][1] > height) {
      nums[i][1] = 0;
    }
  }

  Display
  for (int i = 0; i< n; i ++) {
    radar (num[i][0]s, num[i][1]s, num[i][2]s);
  }
}

void mousePressed() {
  n++;
  nums = append(nums, int( random(n) ); //<-- o append não funca

  this is the block you need to adapt/copy into your sketch
  let's take a traditional approach... create a copy of the vector
  we start by creating a new temoporary vector with one more element (new n)
  int[][] tArray = new int[n][3];
  
  then with a cycle we copy all the positions of the anteiror
  for (int i = 0; i< nums.length; i++) {
    tArray[i][0] = nums[i][0];
    tArray = nums;
    tArray = nums;
  }
  and we add one last value to the new vector
  tArray[n-1][0] = int (random(width) );
  tArra[n-1][1]y = int (random(height);
  tArray[n-1][2] = int (random(20, 50) );

  now, just copy the new vector to the old one and replace
  nums = tArray;

  this method is not so fast, but it is the "traditional" approach
  next class let's see ArrayLists ;)

  printArray(nums); //<-- this is also only for simple arrays
  
  for (int i = 0; i< nums.length; i++) {
    printArray(i+": "+nums[i][0]+"-"+nums[i][1]+"-"+nums[i][2]);
  }
}

void radar (int x, int y, int w) {
  fill(255, 0, 0);
  
  if (dist(mouseX, mouseY, x, y)< w/2 ) {
    fill(0);
    
  }
  noStroke();
  ellipse(x, y, w, w);
}

Leave a comment

Your email address will not be published.