Created
September 12, 2018 23:40
-
-
Save 4gus71n/65730afc11a5e242330b4a84b7827b78 to your computer and use it in GitHub Desktop.
A simple code challenge
This file contains 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
// Feel free to run it here try.kotlinlang.org | |
fun main(args: Array<String>) { | |
val testCollection = arrayOf( | |
1, 2, 3, | |
arrayOf(4, 5, emptyArray<Int>()), null, | |
arrayOf(emptyArray<Int>(), emptyArray<Int>()), | |
arrayOf(6) | |
) | |
System.out.println("Collection:") | |
testCollection.forEach { System.out.print("$it ") } // The JVM doesn't print Lists the same way than Arrays | |
System.out.println("Result:") | |
testCollection.flattenArray().forEach { System.out.print("$it ") } | |
} | |
fun <T: Any?> Array<T>.flattenArray(): Array<*> { | |
// Easier to handle a mutable list than an array | |
val flatList = mutableListOf<Any?>() | |
flattenArray(this, flatList) | |
return flatList.toTypedArray() | |
} | |
private fun <T: Any?> Array<T>.flattenArray(nestedList: Array<*>, flatList: MutableList<Any?>) { | |
nestedList.forEach{ | |
e -> when(e){ | |
!is Array<*> -> flatList.add(e) | |
else -> flattenArray(e, flatList) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment