Skip to content

Instantly share code, notes, and snippets.

@LuisAlbertoPenaNunez
Last active June 13, 2018 17:48
Show Gist options
  • Save LuisAlbertoPenaNunez/904e1d7e5fe8259ad8e5e55fd2427cb4 to your computer and use it in GitHub Desktop.
Save LuisAlbertoPenaNunez/904e1d7e5fe8259ad8e5e55fd2427cb4 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
using System;
using System.Collections;
using System.Collections.Generic;
namespace Flatten
{
class Program
{
static void Main(string[] args)
{
//I try my best to avoid static methods unless I really have to so I did everything under an instance. :)
var instance = new Program();
}
public Program()
{
Init();
}
void Init()
{
var numbersToParse = new ArrayList{
1,2, new ArrayList {
3,4,
new ArrayList
{
5,6,
new ArrayList
{
20, 40
}
}
}
};
var flattenedList = FlattenToString(numbersToParse);
foreach(var nextInt in flattenedList)
Console.WriteLine($"{nextInt}");
Console.WriteLine("The End! :)");
}
/// <summary>
/// Flattens an ArrayList of ArrayList or int into a one level List
/// </summary>
/// <returns>Flattened List</returns>
/// <param name="toFlatten">ArrayList to flatten.</param>
IList<int> FlattenToString(ArrayList toFlatten)
{
var flattenedList = new List<int>();
foreach(var nextValue in toFlatten)
{
if(nextValue is ArrayList nextValueToArrayList)
{
var result = FlattenToString(nextValueToArrayList);
flattenedList.AddRange(result);
}
else if (nextValue is int nextValueToInt)
{
flattenedList.Add(nextValueToInt);
}
else
{
throw new Exception("Ups, I was expecting ArrayList with int or another ArrayList nested.");
}
}
return flattenedList;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment