// ------------------------------------------------------------
// A small program demonstrating how to remove every Nth element
// from an Array using clear, expressive Swift patterns.
// ------------------------------------------------------------
import Foundation
/*
removeEveryNth returns a new array with every Nth element removed.
Swift arrays use zero‑based indexing, so we check (index + 1) % n != 0
to keep elements that are *not* in the Nth position.
The variable "size" captures the array length before the loop,
which avoids repeatedly accessing items.count inside the loop.
A new array is allocated with enough capacity to avoid repeated
growth operations during append.
*/
func removeEveryNth<T>(_ items: [T], n: Int) -> [T] {
precondition(n > 0, "n must be a positive integer")
let size: Int = items.count // capture size once
var result: [T] = [] // output array
result.reserveCapacity(size) // reserve capacity for efficiency
for i in 0..<size {
if (i + 1) % n != 0 {
result.append(items[i])
}
}
return result
}
/*
main demonstrates the function with a simple example.
Keeping main small and focused makes the program easy to extend.
*/
func main() {
let data: [Int] = Array(1...20) // Example array: numbers 1–20
let n: Int = 3 // Remove every 3rd element
let cleaned: [Int] = removeEveryNth(data, n: n)
// Build space‑separated strings without needing escaped quotes
let originalString = data.map { String($0) }.joined(separator: " ")
let cleanedString = cleaned.map { String($0) }.joined(separator: " ")
print("Original: \(originalString)")
print("After removing every \(n)-th element: \(cleanedString)")
}
main()
/*
run:
Original: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After removing every 3-th element: 1 2 4 5 7 8 10 11 13 14 16 17 19 20
*/