Skip to content

Instantly share code, notes, and snippets.

@soraphis
Last active April 17, 2016 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soraphis/3d0c0802beb8573e1feaebc2892f932f to your computer and use it in GitHub Desktop.
Save soraphis/3d0c0802beb8573e1feaebc2892f932f to your computer and use it in GitHub Desktop.
Three equivalent ways to loop over an 2D array. the second one has less indentation.
/*
watching this video: https://unity3d.com/learn/tutorials/modules/advanced/scripting/procedural-cave-generation-pt1
made me scream because of this much copy-and-paste the nested-loop thing
so here are a few workarounds:
*/
int width = 3, height = 2;
int[,] fields = new int[height, width]; // (m x n)-matrix
// ---------------------
// the original:
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
var field = fields[y, x];
}
}
// ---------------------
// a 1-line alternative
for (int x = 0, y = 0; y < height; x = (x + 1) % width, y += Convert.ToInt32(x == 0)) {
// maybe replaced with: y += x == 0 ? 1 : 0
var field = fields[y, x];
}
// ---------------------
// Make-A-Method-For-It & Delegates-Are-Fun
public delegate void Stuff(ref int f); // we need the delegate for the "ref" parameter, this allows us to modify the object
public static void DoStuff(int[,] fields, Stuff stuff) {
for (int x = 0, y = 0; y < fields.GetLength(0); x = (x + 1) % fields.GetLength(1),
y += Convert.ToInt32(x == 0)) {
var field = fields[y, x];
stuff(ref field);
}
}
DoStuff(fields, (ref int field) => { /*... do stuff ...*/ }); // calls the method above like this, looks rly clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment