Wrap around iteration

Is there a way to get this effect of generating
0, 1
1, 2
2, 3
3, 0

with a single condition, I mean either without using if/else, or taking the if/else out of the for loop? And avoid hard coding ‘0’

This just seems janky to me

PVector[] points;
int nPoints;
float textSz;
void setup() {
  size(100, 100);
  textSz = 16;
  nPoints = 4;
  points = new PVector[nPoints];
}
void draw() {
  background(50);

  for (int i = 0; i < points.length; i++) {
    if (i+1 < points.length) {
      points[i] = new PVector(i, i+1);
    } else {
      points[i] = new PVector(i, 0);
    }
  }
  display();
}
void display() {
  for (int i = 0; i < points.length; i++) {
    textAlign(LEFT, TOP);
    textSize(textSz);
    String x = nf(points[i].x, 1, 0);
    String y = nf(points[i].y, 1, 0);
    String p = x + ", " + y;
    text(p, 0, i * textSz);
  }
}
1 Like

Hello,

Your code did not run as and needs some work.

This (only providing a hint) came to mind and worked:

  for (int i = 0; i < p.length; i++) 
    {
    // new Pvector
    // ?
    p[i].y = p[i%4].x+1;
    }

image
That modulo operator % comes in so handy!
https://processing.org/reference/modulo.html

:slight_smile:

1 Like

Sorry… what’s not working? It runs on the Processing iCompiler, which of course runs lots of things it shouldn’t, but maybe it’s that text() doesn’t like outputting a PVector?

I’ll update the code after I check it in the Processing IDE.

The output I get is

[0, 1, 0]
[1, 2, 0]
[2, 3, 0]
[3, 0, 0]

… which is what I’m trying for.

I don’t follow the example you provided, it should go back to 0, not 1

1 Like

I am running on PC with Processing 3.5.3

I was incorrect with answer… back to drawing board.

:slight_smile:

1 Like

I updated the code so it runs normally as-is.

1 Like

This worked:
p[i].y = (p[i].x+1)%4;

image

I will leave the rest with you.

:slight_smile:

1 Like
PVector[] v = new PVector[4];

for(int i = 0; i < v.length; i++){
  v[i] = new PVector(i, v.length - 1 - i);
  println(v[i]);
}

Ignore this answer misread question :blush:

3 Likes

Hey There!

Try this:

for(int i = 0 ; i < points.length ; i++){
	points[i] = new PVector( i , (i+1)%points.length );
}

This should work as we start from 0 , move up i+1 in the second index and wrap it back down depending on the array length by using modulo.

1 Like

I’m sure this is an answer to a question I might have had in the near future, but now will not have to ask. Thank you in advance! :grinning:

What’s this called?

0 [ 0.0, 4.0, 0.0 ]
1 [ 1.0, 3.0, 0.0 ]
2 [ 2.0, 2.0, 0.0 ]
3 [ 3.0, 1.0, 0.0 ]
4 [ 4.0, 0.0, 0.0 ]

1 Like

Thank you, this is good.

1 Like