如何分配锯齿状阵列?

时间:2022-09-25 21:18:14

I am writing a short program which will eventually play connect four.

我正在写一个简短的程序,最终将连接四个。

Here it is so far, pastebin

这是迄今为止,pastebin

There is one part which isn't working. I have a jagged array declared on line 16:

有一部分不起作用。我在第16行声明了一个锯齿状数组:

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

Which I think looks like this:

我认为这看起来像这样:

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

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

当我这样做时[5] [2] ='*'我得到了

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

instead of what I'd like:

而不是我想要的:

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

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

它如何运行(输出应该只有一个星号):

如何分配锯齿状阵列?

1 个解决方案

#1


6  

You are creating your jagged array in wrong way !

你正在以错误的方式创建你的锯齿状阵列!

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

Enumerable.Repeat will create a sequence that contains one repeated value. So you will create an char[][] in which every array will point to same reference. In this case when you change one of the arrays you will change all of them.

Enumerable.Repeat将创建一个包含一个重复值的序列。因此,您将创建一个char [] [],其中每个数组都将指向相同的引用。在这种情况下,当您更改其中一个阵列时,您将更改所有阵列。

You need to create the jagged array this way and array[5][2] will only change the 5th array :

你需要以这种方式创建锯齿状数组,数组[5] [2]只会改变第5个数组:

char[][] array = Enumerable.Range(0, 7).Select(i => Enumerable.Repeat('-', 7).ToArray()).ToArray();

array[5][2] = '*';

#1


6  

You are creating your jagged array in wrong way !

你正在以错误的方式创建你的锯齿状阵列!

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

Enumerable.Repeat will create a sequence that contains one repeated value. So you will create an char[][] in which every array will point to same reference. In this case when you change one of the arrays you will change all of them.

Enumerable.Repeat将创建一个包含一个重复值的序列。因此,您将创建一个char [] [],其中每个数组都将指向相同的引用。在这种情况下,当您更改其中一个阵列时,您将更改所有阵列。

You need to create the jagged array this way and array[5][2] will only change the 5th array :

你需要以这种方式创建锯齿状数组,数组[5] [2]只会改变第5个数组:

char[][] array = Enumerable.Range(0, 7).Select(i => Enumerable.Repeat('-', 7).ToArray()).ToArray();

array[5][2] = '*';