Skip to content

Instantly share code, notes, and snippets.

@KarolisKaj
Created May 5, 2019 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KarolisKaj/4d1946bbab77ec59c7e70742c886bdb5 to your computer and use it in GitHub Desktop.
Save KarolisKaj/4d1946bbab77ec59c7e70742c886bdb5 to your computer and use it in GitHub Desktop.
Flatten array of ints c#
using System;
using System.Collections.Generic;
namespace Playground
{
class Program
{
static void Main(string[] args)
{
var result = new Solution().FlattenArray(new object[]
{
new object[]
{ 1, new object[]
{ 2,3,4, new object[] { 5,6,7,8},
new object[] {9,10,new object[] { 11,12,13,14,15 },16,17 }
},
new object[] { 18,19,20,21,22,23}
},
new object[]{ 24,25,26,27 }
});
Console.Read();
}
}
public class Solution
{
public int[] FlattenArray(object[] target)
{
var flatten = new List<int>();
FlattenArrayRec(target, flatten);
return flatten.ToArray();
}
private void FlattenArrayRec(object[] target, List<int> flatten)
{
for (int i = 0; i < target.Length; i++)
{
if (target[i] is int) { flatten.Add((int)target[i]); Console.WriteLine(target[i]); }
else if (target[i] is object[]) FlattenArrayRec((object[])target[i], flatten);
else throw new ArgumentException("Given argument contains invalid types.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment