Enhanced For Loops and selecting every nth

Hi,

I have a simple question about enhanced for loops.

I created a new arraylist and filled them with objects. and now I am trying to select every nth object. I tried to use:

if(arraylist.size() % 2 == 0) {}

but it doesn’t work. What should I do for selecting every nth object in that arraylist, inside an enhanced for loop?

cells = new ArrayList <Cell>();
createCells(cellSize);


void setup() {
  size(1920, 960); 
  rectMode(CENTER);
  cells = new ArrayList <Cell>();
  createCells(cellSize);
}


void draw() {
  for ( Cell c : cells) {

    if (cells.size() % 2 == 0) {

      // do struff here
    }
  }
} 



void createCells (float size) {

  for ( int i = 0; i<height; i++) {
    for (int j = 0; j<width; j++) {
      if ( i% size == 0) {
        if (j% size == 0) {
          float cellOpacity = random(20);
          float cellRotation = random(360);
          cells.add(new Cell( j, i, size, cellOpacity, cellRotation));
        }
      }
    }
  }
}



class Cell {
  float x, y, scale;
  float opacity;
  float rotation;

  Cell( float x, float y, float scale, float opacity, float rotation) {
    this.x = x;
    this.y = y;
    this.scale = scale;
    this.opacity = opacity;
    this.rotation = rotation;
  }
}
1 Like

A container’s size() doesn’t change just by iterating over it alone. :roll_eyes:

Either use a regular for ( ; ; ) loop or declare some counting variable: :wink:

int count = 0;

for (final Cell c : cells) {
  if ((count++ & 1) == 0) {
  }
}

And given you’re simply alternating the decision about doing the stuff for each iteration, you can also use a boolean variable too: :game_die:

boolean doIt = false;

for (final Cell c : cells) {
  if (doIt ^= true) {
  }
}
1 Like

For performance reasons, the regular loop version would be better: :racing_car:

for (int len = cells.size(), i = 0; i < len; i += 2) {
  final Cell c = cells.get(i);
}

The if () condition can be now omitted in this case, given the iterator i is already being increased by 2. :star_struck:

hi! thank you very much for many different answers :slight_smile:

I think I understand all of them.

Since I have an additional for loop in the draw() section I think I will use the boolean method. 3 for-loops will make it really slow, or at least I think it will make it slow :slight_smile:

I didn’t know this method?

  if (doIt ^= true) {
  }

The expression doIt ^= true is the same as doIt = !doIt: :nerd_face:
Processing.org/reference/logicalNOT.html

And (count++ & 1) == 0 is the same as count++ % 2 == 0: :innocent:
Processing.org/reference/bitwiseAND.html

1 Like