Skip to content

Instantly share code, notes, and snippets.

@TomaQ
Last active October 5, 2018 03:49
Show Gist options
  • Save TomaQ/19aa6e9bb980746820127138170933ca to your computer and use it in GitHub Desktop.
Save TomaQ/19aa6e9bb980746820127138170933ca to your computer and use it in GitHub Desktop.
Flattens an array of arbitrarily nested arrays
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var array = new Object[]
{
new Object[]
{
1,
2,
new Object[]
{
3
}
},
new Object[]
{
4,
5
},
new Object[]
{
new Object[]
{
6,
new Object[]
{
7,
8
}
},
9
}
};
var result = new List<int>();
FlattenArray(array, result);
//print the result as an array
PrintArray(result.ToArray());
}
//Takes an arbitrarily nested array and flattens it, adding the items to the list passed to it
//Using an array would be too costly here since when we add values to the array we would have to resize the array
//which would initialize a new array
private static void FlattenArray(Object[] array, List<int> result)
{
if(array == null || result == null)
throw new ArgumentException("Parameters must not be null");
for(int i = 0; i < array.Length; i++)
{
//if the current element is an int, add it to the result
//else recursively call this function on the element since it is an array
if(array[i] is int)
{
result.Add((int)array[i]);
}
else
{
FlattenArray((Object[])array[i], result);
}
}
}
//Prints an array to the console
private static void PrintArray(int[] array)
{
foreach(int i in array)
Console.WriteLine(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment