// Demonstrating several ways to build an array containing a range of numbers.
// Each function shows a different style that experienced developers commonly use.
// Build an array using Kotlin's built‑in range syntax.
// This is concise and uses natural language features.
fun makeArrayBasic(start: Int, endExclusive: Int): IntArray {
return (start until endExclusive).toList().toIntArray()
}
// Build an array using a manual loop.
// Clear and flexible; useful when adding extra logic.
fun makeArrayLoop(start: Int, endExclusive: Int): IntArray {
val size: Int = endExclusive - start
val values: IntArray = IntArray(size)
var i = 0
var n = start
while (n < endExclusive) {
values[i] = n
i++
n++
}
return values
}
// Build an array using map on a range.
// Shows how to transform values while generating them.
fun makeArrayMap(start: Int, endExclusive: Int): IntArray {
return (start until endExclusive).map { it }.toIntArray()
}
// Build an array using IntArray(size) with a lambda.
// Useful when generating values based on an index.
fun makeArrayIndexed(start: Int, endExclusive: Int): IntArray {
val size: Int = endExclusive - start
return IntArray(size) { i -> start + i }
}
// Build an array using fold.
// Demonstrates a functional style with an accumulator.
fun makeArrayFold(start: Int, endExclusive: Int): IntArray {
return (start until endExclusive).fold(IntArray(0)) { acc, n ->
acc + n
}
}
// Print an array for demonstration.
fun show(label: String, values: IntArray) {
println("$label: ${values.joinToString(prefix = "[", postfix = "]")}")
}
fun main() {
val a: IntArray = makeArrayBasic(1, 10)
val b: IntArray = makeArrayLoop(1, 10)
val c: IntArray = makeArrayMap(1, 10)
val d: IntArray = makeArrayIndexed(1, 10)
val e: IntArray = makeArrayFold(1, 10)
show("basic range", a)
show("loop", b)
show("map", c)
show("indexed", d)
show("fold", e)
}
/*
run:
basic range: [1, 2, 3, 4, 5, 6, 7, 8, 9]
loop: [1, 2, 3, 4, 5, 6, 7, 8, 9]
map: [1, 2, 3, 4, 5, 6, 7, 8, 9]
indexed: [1, 2, 3, 4, 5, 6, 7, 8, 9]
fold: [1, 2, 3, 4, 5, 6, 7, 8, 9]
*/