6

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

Here it is so far, pastebin

There is one part which isn't working. I have a jagged array declared on line 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

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

instead of what I'd like:

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

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


(source: cubeupload.com)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • As I said [earlier](http://stackoverflow.com/questions/40644799/convert-ienumerable-to-multidimensional-array?noredirect=1#comment68521711_40644799), you need an MCVE, because I don't believe this is how it works. – Kirk Woll Nov 17 '16 at 00:55
  • @KirkWoll done,,, – theonlygusti Nov 17 '16 at 00:57

1 Answers1

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.

You need to create the jagged array this way and 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] = '*';
mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • Yep, this is the right answer. Though I sympathize with the OP in his confusion. It was natural, in a way. – Kirk Woll Nov 17 '16 at 01:04
  • 1
    @theonlygusti, you'll love it eventually. In every programming language, syntax can be very subtle. But +1 to you in that your question and confusion was legitimate and interesting. :) – Kirk Woll Nov 17 '16 at 01:04
  • 1
    Please don't say that amongst C# enthusiasts. ;) (I mostly kid, but let's not get started on the pandora's box that is the argument between dynamic and statically typed languages. ;) ) – Kirk Woll Nov 17 '16 at 01:08