Skip to content

Instantly share code, notes, and snippets.

@jonikarppinen
Last active July 2, 2024 05:03
Show Gist options
  • Save jonikarppinen/139a2b7222d7da6454b8beef54219803 to your computer and use it in GitHub Desktop.
Save jonikarppinen/139a2b7222d7da6454b8beef54219803 to your computer and use it in GitHub Desktop.
onlyEvenInt in Kotlin ("Write a function that takes an array of integers as an input, and returns a new array containing only even integers, sorted.")
// Run it at play.kotlinlang.org
fun onlyEvenInt(numbers: List<Int>) = numbers.filter { it % 2 == 0 }.sorted()
fun main() {
println(onlyEvenInt(listOf(1, 2, 3, 4, 5, 6, 7)))
println(onlyEvenInt(listOf(6, 7, 1, 2, 3, 4, 5)))
println(onlyEvenInt(listOf(1, 3, 5, 7)))
println(onlyEvenInt(listOf(-2, -3, -4, 0)))
}
@jonikarppinen
Copy link
Author

jonikarppinen commented Jul 2, 2024

Being on JVM, using lists is idiomatic. But could use arrays just as well.

fun onlyEvenInt(numbers: IntArray) = numbers.filter { it % 2 == 0 }.sorted().toIntArray()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment