c# - Properly printing a 2D array? -
currently working on writing conways life in c# class. i've been taking little steps hang out language , game programming in general , have nail snag in printing 2d char array. i'm using getlength - 1 not go on bound fails print out lastly chars in array.
what initial file looks like
+*++ ++*+ ****
after read placed char (i believe)
* * ****
what ends printed
* ** using system; using system.io; using system.collections.generic; using system.text; namespace conwayslife { class programme { static char[,] universe; static void bigbang(int h, int w, list<string> grid) { universe = new char[h,w]; int row = 0; foreach (string line in grid) { (int = 0; < line.length; i++) { if (line.tochararray()[i] == '*') { universe[row, i] = '*'; } } row++; } } //how i'm attempting print out 2d char array static void offspring() { stringbuilder cellline = new stringbuilder(); (int y = 0; y < universe.getlength(1)-1; y++) { (int x = 0; x < universe.getlength(0)-1; x++) { console.write(universe[y, x]); } console.writeline(); } //pause console.readline(); } static void main(string[] args) { list<string> templine = new list<string>(); //console.writeline("file path?"); int width = 0; int height = 0; //read file list using (streamreader r = new streamreader("life.txt")) { while (r.peek() >= 0) { templine.add(r.readline()); //compare current width new width if (templine[height].length >= width) { width = templine[height].length; } //increase height when going next row height++; } bigbang(height, width, templine); } offspring(); } } }
update offspring()
static void offspring() { stringbuilder cellline = new stringbuilder(); (int x = 0; x <= universe.getlength(1); x++) { (int y = 0; y <= universe.getlength(0); y++) { console.write(universe[x, y]); } console.writeline(); } //pause console.readline(); }
you have off-by-one error in offspring
function. note you're doing correctly in bigbang
function.
you looping while x < getlength()-1
. need x < getlength()
, because excludes case when x == getlength()
.
an analagous loop:
for (i = 0; < 4; i++) console.writeline(i);
output:
0 1 2 3
c# multidimensional-array
No comments:
Post a Comment