2

I have a string of 9 space-separated integers, like "3 4 6 9 8 8 2 3 4", which I want to convert to a 3x3 int Array.

A simple solution is to do two loops over a new matrix and convert string values as I go. Is there a more elegant way to do this?

Incredible
  • 3,495
  • 8
  • 49
  • 77
aristotaly
  • 399
  • 2
  • 14

3 Answers3

4

Using my Split extension from Split a collection into `n` parts with LINQ?

var nums = s.Split(' ').Select(n=>Int32.Parse(n)).ToList();
var grid = nums.Split(nums.Count / 3);
Community
  • 1
  • 1
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
1

Basically, your solution is as good as you can go. You can accomplish the same thing with LINQ:

int[][] result = 
    s.Split(' ')
     .Select((a, index) => new {index, value = int.Parse(a)})
     .GroupBy(tuple => tuple.index / 3)
     .Select(g => g.Select(tuple => tuple.value).ToArray())
     .ToArray();

For this problem, the LINQ solution is probably worse than the normal solution; however, the idea may be helpful for similar problems.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
1

You can do an split over the " " character string.split() and you will get an array of string with the numbers. Then you must cast them to integers and distribute a plain array to you desired array and as far as I know there is no way to do that in another way that iterating through the array, but you will need only 1 loop.

Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207