Created
May 5, 2019 05:25
-
-
Save KarolisKaj/4d1946bbab77ec59c7e70742c886bdb5 to your computer and use it in GitHub Desktop.
Flatten array of ints c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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