import Foundation
// 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 Swift's built‑in range syntax.
// This is concise and uses natural language features.
func makeArrayBasic(start: Int, endExclusive: Int) -> [Int] {
Array(start..<endExclusive)
}
// Build an array using a manual loop.
// Clear and flexible; useful when adding extra logic.
func makeArrayLoop(start: Int, endExclusive: Int) -> [Int] {
var values: [Int] = []
var n = start
while n < endExclusive {
values.append(n)
n += 1
}
return values
}
// Build an array using map on a range.
// Shows how to transform values while generating them.
func makeArrayMap(start: Int, endExclusive: Int) -> [Int] {
(start..<endExclusive).map { $0 }
}
// Build an array using Array(repeating:count:) with enumerated mapping.
// Useful when generating values based on an index.
func makeArrayIndexed(start: Int, endExclusive: Int) -> [Int] {
let size = endExclusive - start
return Array(repeating: 0, count: size).enumerated().map { index, _ in
start + index
}
}
// Build an array using reduce.
// Demonstrates a functional style with an accumulator.
func makeArrayReduce(start: Int, endExclusive: Int) -> [Int] {
(start..<endExclusive).reduce(into: []) { acc, n in
acc.append(n)
}
}
// Print an array for demonstration.
func show(_ label: String, _ values: [Int]) {
print("\(label): \(values)")
}
func main() {
let a: [Int] = makeArrayBasic(start: 1, endExclusive: 10)
let b: [Int] = makeArrayLoop(start: 1, endExclusive: 10)
let c: [Int] = makeArrayMap(start: 1, endExclusive: 10)
let d: [Int] = makeArrayIndexed(start: 1, endExclusive: 10)
let e: [Int] = makeArrayReduce(start: 1, endExclusive: 10)
show("basic range", a)
show("loop", b)
show("map", c)
show("indexed", d)
show("reduce", e)
}
main()
/*
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]
reduce: [1, 2, 3, 4, 5, 6, 7, 8, 9]
*/