1

What I want to do is described in the comment below. How can I do, efficiently?

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        int n = Int32.Parse(Console.ReadLine());
        bool[][] flags = new bool[26][n]; // I want this to be a 26 x n array of false values
        for(int k = 0; k < n; ++k)
        {
            string line = Console.WriteLine();
            for(int i = 0; i < line.Length; ++i)
                flags[(int)line[i] - (int)'a'] = true;
        }
        int gems = flags.Count(arr => arr.Count(j => j == true) == arr.Length);       
        Console.WriteLine
    }
}
user6048670
  • 2,861
  • 4
  • 16
  • 20
  • 2
    The array is already initialized to all `false`. It's part of the language specification. See http://stackoverflow.com/a/15300089/56778 for the details. – Jim Mischel Aug 04 '16 at 04:57
  • 1
    If you want all the value to be false, why are you setting them to true? –  Aug 04 '16 at 06:38
  • Possible duplicate of [Default value for bool in c#](http://stackoverflow.com/questions/4996582/default-value-for-bool-in-c-sharp) – progyammer Aug 04 '16 at 13:01

2 Answers2

7

LINQ should work well for your goal:

bool[][] flags = Enumerable.Range(0, 26).Select(_ => Enumerable.Repeat(true, n).ToArray()).ToArray();

Or as Jim Mischel said:

bool[][] flags = Enumerable.Repeat(Enumerable.Repeat(true, n).ToArray(), 26).ToArray();

But the first example uses less memory becuase the Select method doesn't re-define Enumerable.Repeat(true, n).ToArray() as it goes through the items.

  • 1
    Can be simplified to `flags = Enumerable.Repeat(Enumerable.Repeat(true, n).ToArray(), 26).ToArray();` – Jim Mischel Aug 04 '16 at 05:07
  • `flags = Enumerable.Repeat(Enumerable.Repeat(true, n).ToArray(), 26).ToArray();` is incorrect as it will create the "inner" array only once and then will initialize "rows" with a reference to it. So, when you modify, say [0][0], the you'll see the same value in [1][0],.. [n][0]. – Ant Apr 22 '21 at 03:55
5

Looks like you are confused between Multidimensional arrays and Jagged Array (Array of Arrays).

If you are looking for 2d Array, you could simply do this.

bool[,] flags = new bool[26,n]; 
//or
bool[,] flags = new bool[,]; 
bool[,] flags = new bool[26,]; 

If it is Jagged Arrays, you could do this.

bool[][] flags1 = new bool[26][];
flags1[0] = new bool[n];  // since you want n elements 
flags1[1] = new bool[n];
...

// initialization
flags1[0] = new bool[] {true, false};
flags1[1] = new bool[] {false};
AakashM
  • 62,551
  • 17
  • 151
  • 186
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35