// Demonstrating several ways to build an array containing a range of numbers.
// Each function shows a different style that experienced developers commonly use.
object InitArrayRange {
// Build an array using Scala's built‑in Range.
// This is concise and uses natural language features.
def makeArrayBasic(start: Int, endExclusive: Int): Array[Int] = {
(start until endExclusive).toArray
}
// Build an array using a manual loop.
// Clear and flexible; useful when adding extra logic.
def makeArrayLoop(start: Int, endExclusive: Int): Array[Int] = {
val size: Int = endExclusive - start
val values: Array[Int] = new Array[Int](size)
var i: Int = 0
var n: Int = start
while (n < endExclusive) {
values(i) = n
i += 1
n += 1
}
values
}
// Build an array using map on a Range.
// Shows how to transform values while generating them.
def makeArrayMap(start: Int, endExclusive: Int): Array[Int] = {
(start until endExclusive).map(n => n).toArray
}
// Build an array using Array.tabulate.
// Useful when generating values based on an index.
def makeArrayTabulate(start: Int, endExclusive: Int): Array[Int] = {
val size: Int = endExclusive - start
Array.tabulate(size)(i => start + i)
}
// Build an array using foldLeft.
// Demonstrates a functional style with an accumulator.
def makeArrayFold(start: Int, endExclusive: Int): Array[Int] = {
(start until endExclusive).foldLeft(Array.empty[Int]) { (acc, n) =>
acc :+ n
}
}
// Print an array for demonstration.
def show(label: String, values: Array[Int]): Unit = {
println(s"$label: ${values.mkString("[", ", ", "]")}")
}
def main(args: Array[String]): Unit = {
val a: Array[Int] = makeArrayBasic(1, 10)
val b: Array[Int] = makeArrayLoop(1, 10)
val c: Array[Int] = makeArrayMap(1, 10)
val d: Array[Int] = makeArrayTabulate(1, 10)
val e: Array[Int] = makeArrayFold(1, 10)
show("basic range", a)
show("loop", b)
show("map", c)
show("tabulate", d)
show("foldLeft", 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]
tabulate: [1, 2, 3, 4, 5, 6, 7, 8, 9]
foldLeft: [1, 2, 3, 4, 5, 6, 7, 8, 9]
*/