Swift - 将输入整数平均分配给正数和负数数组

Swift - Distribute an input integer equally to an array of positive & negative numbers

如何从输入整数生成均匀分布的正数和负数数组?
对于奇数整数,数组必须包含 0 作为“中间”。
对于偶数,数组不能包含 0,而是有 0.5 个步长,例如-0.5 & 0.5.
输入的整数不能为负数或 0。因此可以忽略这些输入。

示例:

Input : Output
Int 1 = [0]
Int 2 = [-0.5, 0.5]
Int 3 = [-1, 0, 1]
Int 4 = [-1.5, -0.5, 0.5, 1.5]
Int 5 = [-2, -1, 0, 1, 2]
Int 6 = [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]
and so on...

是否有聪明的方法来做到这一点,或者它是 for 循环和 if/else 语句的级联?

尝试使用 stride(from:through:by:)

  1. 请注意所需输出数组中的最后一个元素 (end) 始终是 (input - 1) * 0.5。 (您也可以对第一个元素执行此操作,但只需翻转符号即可)
  2. 对于stridefrom,只需翻转end
  3. 的符号
let inputs = [1, 2, 3, 4, 5, 6]
inputs.forEach { input in
    let end = Double(input - 1) * 0.5 /// 1.
    let output = Array(stride(from: -end, through: end, by: 1)) /// 2.
    print("Input: \(input), Output: \(output)")
}

Input: 1, Output: [-0.0]
Input: 2, Output: [-0.5, 0.5]
Input: 3, Output: [-1.0, 0.0, 1.0]
Input: 4, Output: [-1.5, -0.5, 0.5, 1.5]
Input: 5, Output: [-2.0, -1.0, 0.0, 1.0, 2.0]
Input: 6, Output: [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]

模式似乎是:

Array((1...1).map { Double([=10=]) - (2 * 0.5) })

Array((1...2).map { Double([=10=]) - (3 * 0.5) })

Array((1...3).map { Double([=10=]) - (4 * 0.5) })

总的来说:

func f(_ n: Int) -> [Double] {
    (1...n).map { Double([=11=]) - (Double(n + 1) / 2.0) }
}