Skip to content

Instantly share code, notes, and snippets.

@jmprado
Last active July 30, 2018 20:59
Show Gist options
  • Save jmprado/6615570727c797125444a49b311ba68e to your computer and use it in GitHub Desktop.
Save jmprado/6615570727c797125444a49b311ba68e to your computer and use it in GitHub Desktop.
Flatten int array
using System;
using System.Collections.Generic;
namespace Algoritmo1
{
class Program
{
static void Main(string[] args)
{
int[,] testArray = new int[,] { { 1, 2 }, { 3, 4 } } ;
int[] testResult = FlattenArray(testArray);
Console.WriteLine("Gist applying to the job \"Experienced Backend Engineer\" at Cytrusbyte");
foreach(int i in testResult)
{
Console.WriteLine(i);
}
Console.WriteLine("Finish processing, thanks for watch.");
Console.ReadLine();
}
/// <summary>
/// Recursive flattening method
/// </summary>
/// <param name="arrayItem">Array of int or nested int array</param>
/// <returns>Flattened array</returns>
static int[] FlattenArray(dynamic arrayItem)
{
List<int> listReturn = new List<int>();
if (arrayItem.GetType() == typeof(int))
listReturn.Add((int)arrayItem);
else
{
foreach (dynamic arrItem in arrayItem)
{
if (arrItem.GetType() == typeof(int))
listReturn.Add(arrItem);
else
FlattenArray(arrItem);
}
}
return listReturn.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment