[英]How to generate all permutations of 1 and 0 bits of a given size in Swift
I would like to be able to generate an array of all possible permutations of a Bool
( true/false
or 1/0
) of a given size n
, in Swift. For example, given n=2
the result of calling generate(2)
would be我希望能够在 Swift 中生成给定大小n
的Bool
( true/false
或1/0
)所有可能排列的数组。例如,给定n=2
调用generate(2)
的结果将是
let array: [Bool] = generate(2) // [[false, false], [false, true], [true, false], [true, true]]
I looked in Swift-algorithms but all I see is permutations and combinations of a provided array of elements.我查看了 Swift 算法,但我看到的只是提供的元素数组的排列和组合。 These algorithms don't appear to address scenario for a Bool
with n>2
.这些算法似乎无法解决n>2
的Bool
场景。 Also, I'm not sure what name to call this algorithm.另外,我不确定该算法的名称。
Here's a simple recursive implementation:这是一个简单的递归实现:
import Foundation
func recursion(depth: Int, arr: [[Bool]]) -> [[Bool]] {
if depth == .zero {
return arr
}
var newArr: [[Bool]] = []
for item in arr {
let newItem1 = item + [false]
let newItem2 = item + [true]
newArr += [newItem1, newItem2]
}
return recursion(depth: depth-1, arr: newArr)
}
print(recursion(depth: 1, arr: [[]]))
print(recursion(depth: 2, arr: [[]]))
print(recursion(depth: 3, arr: [[]]))
This gives the output:这给出了 output:
[[false], [true]]
[[false, false], [false, true], [true, false], [true, true]]
[[false, false, false], [false, false, true], [false, true, false], [false, true, true], [true, false, false], [true, false, true], [true, true, false], [true, true, true]]
Just for fun a functional approach:只是为了好玩一个功能性的方法:
extension RangeReplaceableCollection {
var combinations: [Self] { generate(2) }
func generate(_ n: Int) -> [Self] {
repeatElement(self, count: n).reduce([.init()]) { result, element in
result.flatMap { elements in
element.map { elements + CollectionOfOne($0) }
}
}
}
}
Usage:用法:
let elements = [false, true] // [false, true]
let combinations = elements.combinations // [[false, false], [false, true], [true, false], [true, true]]
let generateThree = elements.generate(3) // [[false, false, false], [false, false, true], [false, true, false], [false, true, true], [true, false, false], [true, false, true], [true, true, false], [true, true, true]]
or或者
let elements = [0, 1] // [0, 1]
let combinations = elements.combinations // [[0, 0], [0, 1], [1, 0], [1, 1]]
let generateThree = elements.generate(3) // [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
or with Strings (Collection Of Characters):或使用字符串(字符集合):
let elements = "01" // "01"
let combinations = elements.combinations // ["00", "01", "10", "11"]
let generateThree = elements.generate(3) // ["000", "001", "010", "011", "100", "101", "110", "111"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.