Last active
February 13, 2025 21:10
-
-
Save jamescurran/ad5b05621ac77894032fd42dd473c2c2 to your computer and use it in GitHub Desktop.
Daily Challenge #JS-101: Find the Maximum Depth of a Nested Array (In C#)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Find the Maximum Depth of a Nested Array | |
| Develop a function to find the maximum depth of nested arrays. | |
| The function will receive an array as its input, | |
| which can contain other arrays to any depth, | |
| and it should return the maximum depth integer. | |
| Example: | |
| Input: [1, [2, [3, [4]], 5], 6] | |
| Output: 4 | |
| */ | |
| void Main() | |
| { | |
| object[] array = new object[] { 1, new object[] { -1 } , new object[] { 2, new object[] { 3, new object[] { 4 } }, 5 }, 6}; | |
| CountLevel(array).Dump(); | |
| } | |
| int CountLevel(object[] array) => | |
| array.OfType<object[]>() | |
| .Aggregate(1, (deepest, item) => Math.Max(deepest, CountLevel(item) + 1)); | |
| int CountLevel_ver1(object[] array) | |
| { | |
| int deepest = 1; | |
| foreach(object[] item in array.Where(i => i is object[])) | |
| deepest = Math.Max(deepest, CountLevel_ver1(item) + 1); | |
| return deepest; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment