How to assign an array with a serrated contour?

I am writing a short program that will ultimately play a mix of four.

Here he is still, pastebin

There is one part that does not work. I have a jagged array declared on line 16:

char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray(); 

What I think looks like this:

 ------- ------- ------- ------- ------- ------- ------- 

when i do this board[5][2] = '*' I get

 --*---- --*---- --*---- --*---- --*---- --*---- --*---- 

instead of what I would like:

 ------- ------- ------- ------- ------- --*---- ------- 

How it works at the moment (the output should have only one asterisk):

+6
source share
1 answer

You create your gear array incorrectly!

 char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray(); 

Enumerable.Repeat will create a sequence containing one repeated value. So you create a char [] [] in which each array will point to the same link. In this case, when you change one of the arrays, you change them all.

You need to create an array with a notch, and the array [5] [2] will only change the 5th array:

 char[][] array = Enumerable.Range(0, 7).Select(i => Enumerable.Repeat('-', 7).ToArray()).ToArray(); array[5][2] = '*'; 
+6
source

Source: https://habr.com/ru/post/1012391/


All Articles