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

Processing's quick enough on the sqrt, hasn't been a problem. And yeah, I can't use two loops, which is why I did it this way in the first place.

Seems like this method works though, and keeps the math a bit lighter:

int s = ceil(sqrt(count)); 
for(int i = 0; i < count; i++) {
  X = i % s;
  Y = i / s;
}

(via http://twitter.com/jasonstitt/status/13468280866 )

@mostlygeek
Copy link

What would be a use case for this?

@mikeday
Copy link

mikeday commented May 6, 2010

Right, that's much better. But I'm really curious how you are using this loop! When count = 17, it produces this:

00 01 02 03 04
05 06 07 08 09
10 11 12 13 14
15 16

Here is an alternative that starts at the origin and expands outwards in a triangle:

x = y = 0;

for (int i = 0; i < count; ++i)
{
    ... do something with x and y ...
    if (x == 0) {
        x = y + 1;
        y = 0;
    } else {
        --x;
        ++y;
    }
}

For count = 17 it does this:

00 01 03 06 10 15
02 04 07 11 16
05 08 12
09 13
14

So yeah, what is this for? Does it produce pretty pictures? Is it a secret? :)

@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