c# - how to convert a grid into a 2D array -


for euler problem 11, want convert 20x20 grid 2d integer array.

the numbers in each row separated space, , rows separated return.

ex:
34 34 34 34
34 34 34 34
34 34 34 34
34 34 34 34

i think grid shown string, , want copy/paste, create array; multiple line strings don't seem allowed. easier save grid file , read array?
i'm not asking solve problem, looking creating array.
found how take each line , convert single-dimensional array using .split(), .select(), , .toarray()

int[] rowone = "34 34 34 34".split(' ').select(int.parse).toarray();   

i still c# novice, , i'm unsure of simplest way convert whole grid 2d array.

lets grid stored in string called grid

string grid = @"34 34 34 34             34 34 34 34             34 34 34 34             34 34 34 34";  var myarray = grid     .split('\n')     .select(t => t.split(' ')                     .where((t1) =>                     {                         int = 0;                         return int.tryparse(t1, out i);                     })                     .select(int.parse).toarray()             ).toarray(); 

the code here first splits based on newline character , space character. call "where" sends in anonymous method returns true or false, tries parse see if value integer therefore selecting integers.

var statically typed therefore whatever expression returns type myarray be. happens @ compile time not runtime. int [][] myarray = ...

test

for (int = 0; < myarray.length; i++) {     (int j = 0; j < myarray[i].length; j++)     {         console.write(myarray[i][j].tostring() + ' ');     }     console.writeline(); } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -