arrays - 如何在 Swift 中生成给定大小的 1 位和 0 位的所有排列

标签 arrays swift algorithm collections combinatorics

我希望能够生成 Bool(true/false1/0)所有可能排列的数组给定大小的 n,在 Swift 中。例如,给定 n=2,调用 generate(2) 的结果将是

let array: [Bool] = generate(2) // [[false, false], [false, true], [true, false], [true, true]]

我查看了 Swift 算法,但我看到的只是提供的元素数组的排列和组合。这些算法似乎无法解决 n>2Bool 场景。另外,我不确定该算法的名称。

最佳答案

这是一个简单的递归实现:

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: [[]]))

这给出了输出:

[[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]]

关于arrays - 如何在 Swift 中生成给定大小的 1 位和 0 位的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71175124/

相关文章:

algorithm - 递归查找一组给定的不同整数的所有子集

c++ - 快速实现大型整数计数器(在C/C++中)

ios - 我可以返回两个数组吗?

php - 用键内爆关联数组的最快方法

java - 如何在java中增加id并获取冗长的描述

xcode - 我应该使用 CoreData 谓词来填充我的 UITableview 吗?

ios - CollectionView Label 多行标签自动布局在小屏幕 iOS 设备上陷入困境

php - 来自mysql存储过程和php json_decode的正确格式的关联数组

ios - 使用 Computed 变量和 Snapkit 时 : No common superview between views

algorithm - 试图提高数组中此搜索的效率