03 & 04 exercises (#96)

This commit is contained in:
NikitaLipatov
2018-12-28 19:25:01 +03:00
committed by Aditya Bhargava
parent 2bf2ab5062
commit 8a0a191975
8 changed files with 69 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
private fun countdown(i: Int) {
println(i)
when {
// base case
i <= 0 -> return
// recursive case
else -> countdown(i - 1)
}
}
fun main(args: Array<String>) = countdown(5)

View File

@@ -0,0 +1,12 @@
private fun greet2(name: String) = println("how are you, $name?")
private fun bye() = println("ok bye!")
private fun greet(name: String) {
println("hello, $name!")
greet2(name)
println("getting ready to say bye...")
bye()
}
fun main(args: Array<String>) = greet("adit")

View File

@@ -0,0 +1,6 @@
private fun fact(x: Int): Int = when (x) {
1 -> 1
else -> x * fact(x - 1)
}
fun main(args: Array<String>) = println(fact(5))

View File

@@ -0,0 +1,7 @@
private fun sum(arr: Array<Int>): Int {
var total = 0
for (x in arr) total += x
return total
}
fun main(args: Array<String>) = println(sum(arrayOf(1, 2, 3, 4)))

View File

@@ -0,0 +1,6 @@
private fun sum(arr: IntArray): Int = when {
arr.isEmpty() -> 0
else -> arr[0] + sum(arr.copyOfRange(1, arr.size))
}
fun main(args: Array<String>) = println(sum(intArrayOf(1, 2, 3, 4)))

View File

@@ -0,0 +1,6 @@
private fun count(list: List<Any>): Int = when {
list.isEmpty() -> 0
else -> 1 + count(list.subList(1, list.size))
}
fun main(args: Array<String>) = println(count(listOf(1, 2, 3, 4, 5)))

View File

@@ -0,0 +1,9 @@
private fun max(list: IntArray): Int = when {
list.size == 2 -> if (list[0] > list[1]) list[0] else list[1]
else -> {
val subMax = max(list.copyOfRange(1, list.size))
if (list[0] > subMax) list[0] else subMax
}
}
fun main(args: Array<String>) = println(max(intArrayOf(1, 5, 10, 25, 16, 1))) // 25

View File

@@ -0,0 +1,12 @@
fun quickSort(list: List<Int>): List<Int> {
// base case, arrays with 0 or 1 element are already "sorted"
if (list.size <= 1) return list
// recursive case
val pivot = list[list.size / 2]
val equal = list.filter { it == pivot }
val less = list.filter { it < pivot }
val greater = list.filter { it > pivot }
return quickSort(less) + equal + quickSort(greater)
}
fun main(args: Array<String>) = println(quickSort(listOf(10, 5, 2, 3))) // [2, 3, 5, 10]