Skip to content

Instantly share code, notes, and snippets.

@aibars
Last active October 31, 2020 11:17
Show Gist options
  • Save aibars/d70b5bd3014ac7c5031f73a744580d58 to your computer and use it in GitHub Desktop.
Save aibars/d70b5bd3014ac7c5031f73a744580d58 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace FlattenArray
{
public class Program
{
/// <summary>
/// Main console program method with tests cases
/// Author: Agustín Ibars
/// </summary>
public static void Main()
{
try
{
// Sample [[1,2,[3]],4] -> [1,2,3,4]
var array1 = new object[] { new object[] { 1, 2, new object[] { 3 } }, 4 };
var result1 = Flatten(array1);
Console.WriteLine("Flattened results:");
Console.WriteLine("[{0}]", string.Join(", ", result1));
var array2 = new object[] { 4 };
var result2 = Flatten(array2);
Console.WriteLine("[{0}]", string.Join(", ", result2));
var array3 = new object[] { 4, new object[] { 1, 2, new object[] { 4, 5 }, 6 }, 7 };
var result3 = Flatten(array3);
Console.WriteLine("[{0}]", string.Join(", ", result3));
var array4 = new object[] { 4, 9, new object[] { new object[] { 1, 2, 3 }, 4 }, new object[] { 13, "a" } }; //this should fail
var result4 = Flatten(array4);
Console.WriteLine("[{0}]", string.Join(", ", result4));
}
catch (Exception ex)
{
Console.WriteLine(string.Format("There was an error processing the array input\nReason: {0}", ex.Message));
}
}
/// <summary>
/// Flattens an array of arbitrarily nested arrays of integers into a flat array of integers
/// </summary>
/// <param name="A">An arbitrarly nested array of objects</param>
/// <returns>A flattened integer array</returns>
public static int[] Flatten(object[] A)
{
var list = new List<int>();
FlattenHelper(ref list, A);
return list.ToArray();
}
/// <summary>
/// Recursive method that actually does the flattening of the array
/// </summary>
/// <param name="list">A list passed by reference so that the partial results are being added</param>
/// <param name="A">The sub-array or main array of nested items</param>
public static void FlattenHelper(ref List<int> list, object[] A)
{
for (int i = 0; i < A.Length; i++)
{
if (A[i].GetType() == typeof(object[]))
{
FlattenHelper(ref list, A[i] as object[]);
}
else if (A[i].GetType() == typeof(int))
{
list.Add((int)A[i]);
}
else
{
throw new ArgumentException("The element is neither an integer nor an array of integers");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment