Skip to content

Instantly share code, notes, and snippets.

@rathwell
Last active March 21, 2019 22:02
Show Gist options
  • Save rathwell/53ae6b3e198f96e48c4d23c61e5f3be3 to your computer and use it in GitHub Desktop.
Save rathwell/53ae6b3e198f96e48c4d23c61e5f3be3 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
/// <summary>
/// Python or Javascript may have been a bit tighter, but the concept is the same
/// </summary>
public class Program
{
public static void Main()
{
NestedReturnsExpected();
FlatReturnsSelf();
EmptyReturnsEmpty();
InvalidInputThrows();
}
/// <summary>
/// Flatten the arbitrarily nested enumerable
/// </summary>
/// <param name="enumerable">A dynamic enumerable of int or nested enumerable</param>
/// <returns>A flattened array of integers from the nested input array</returns>
public static int[] Flatten(dynamic enumerable)
{
Debug.Assert(enumerable is System.Collections.IEnumerable);
var result = new List<int>();
foreach (var item in enumerable)
{
if (item is int)
{
result.Add(item);
}
else if (item is System.Collections.IEnumerable)
{
result.AddRange(Flatten(item));
}
else
{
throw new Exception("Invalid type. Integer or IEnumerable expected");
}
}
return result.ToArray();
}
// *************
// *** TESTS ***
// *************
// Tests are in same file for this demo and use Debug.Assert for brevity,
// but in a production environment, tests are generally in a separate
// assembly and would use one of xUnit/NUnit/MSTest frameworks
// *************
/// <summary>
/// Assert that a nested array returns expected values
/// </summary>
public static void NestedReturnsExpected()
{
// arrange
var arr = new object[]
{
1,
new int[] { 2, 3 },
4
};
// act
var result = Flatten(arr);
// assert
var expected = new int[] { 1, 2, 3, 4 };
Debug.Assert(result.SequenceEqual(expected));
}
/// <summary>
/// Assert that an already flat array returns the same sequence
/// </summary>
public static void FlatReturnsSelf()
{
// arrange
var arr = new int[] { 2, 4, 6 };
// act
var result = Flatten(arr);
// assert
Debug.Assert(result.SequenceEqual(arr));
}
/// <summary>
/// Assert that an empty array returns an empty array
/// </summary>
public static void EmptyReturnsEmpty()
{
// arrange
var arr = new int[0];
// act
var result = Flatten(arr);
// assert
Debug.Assert(result.SequenceEqual(new int[0]));
}
/// <summary>
/// Verify that invalid input throws
/// *** again, for brevity, only watching exception be thrown
/// here instead of asserting it is thrown with a unit test
/// framework
/// </summary>
public static void InvalidInputThrows()
{
// arrange
var arr = new object[] { 1.0f, 3 };
// act
var result = Flatten(arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment