user6048670 user6048670 - 3 months ago 8
C# Question

How can define a 26x2 array and then use LINQ on its rows?

Grrrr I have C# and multidimensional arrays. For some reason, coming from a C/C++ background, they really annoy me.

So when I run

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for(int t = 0; t < T; ++t)
{
string str = Console.ReadLine();
if(str.Length % 2 == 1)
{
Console.WriteLine(-1);
continue;
}
int n = str.Length / 2;
// determine how many replacements s1 needs to be an anagram of s2
string s1 = str.Substring(0, n);
string s2 = str.Substring(n, n);
int[][] counter = new int[26][2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a][0] += 1;
counter[(int)s2[i] - ascii_a][1] += 1;
}
int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();
Console.WriteLine(count);
}
}
}


I get


solution.cs(22,42): error CS0029: Cannot implicitly convert type
int'
to
int[][]' Compilation failed: 1 error(s), 0 warnings


No idea why.

I can change it to

int[,] counter = new int[26,2];
int ascii_a = (int)'a';
for(int i = 0; i < n; ++i)
{
counter[(int)s1[i] - ascii_a, 0] += 1;
counter[(int)s2[i] - ascii_a, 1] += 1;
}
int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();


but then, of course, my LINQ statement breaks.

Answer

You can't define jagged array like that:

int[][] counter = new int[26][2];

I recommend reading on jagged arrays:

https://msdn.microsoft.com/en-us/library/2s05feca.aspx

https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx

In your case I'd suggest using not jagged, but multi-dimentional array:

var counter = new int[26,2];

Comments