Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mezzoblue/391745 to your computer and use it in GitHub Desktop.
Save mezzoblue/391745 to your computer and use it in GitHub Desktop.
// PROBLEM
// so I've run into this at least twice now, where I want to loop through a single
// "0 to whatever" range of numbers, but within that loop use the current iteration to
// address a 2D array.
//
// this is in Processing, so the actual use case is creating a 2D grid of coordinates
// from that single range of numbers. Usually I do it with two loops, ie. loop
// through i and then loop through j within that loop. But I'm finding cases where
// I want to loop through just i, and derive separate X and Y coordinates from the
// current value of i. Easy to do if i is a square, but what if it's irregular?
//
// I'm not sure if I'm explaining it very well, but here's what I came up with. I thought
// it was a neat bit of math. Code in Processing / Java.
int count = 1337;
for (int i = 0; i < count; i++) {
float sqc = sqrt(count);
X = (sqc - ((count - (i + 1)) % sqc));
Y = ceil(sqc - (sqc - (i + 1) / sqc));
}
@mezzoblue
Copy link
Author

It's for aligning coordinates in a grid. Say I want to set up a variable number of squares without having to worry about them matching up perfectly. Done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment