Last active
April 17, 2016 21:55
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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