gpt4 book ai didi

javascript - JS 中的递归挑战将所有可能的数组键组合为 true |错误版本,我附上输入和输出

转载 作者:行者123 更新时间:2023-12-04 09:45:56 29 4
gpt4 key购买 nike

我找到了很多关于数组值之间所有可能组合的解决方案,但我需要一些不同的东西,我希望你能支持我。基本上是创建将数组键与 true|false 值组合在一起的所有可能对象,如下所示:

输入:(应该返回一个包含 32 个对象的数组,2exp5,5 个键中的两个可能值)

let properties = ['arm','lens','season','food','size'];

输出:
let combinations = [
{"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
{"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
{"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
{"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
{"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
{"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
{"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
{"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
and so on...
]

非常感谢!

最佳答案

您可以为每个属性使用带有开和关开关的 2D 矩阵。然后为每个键创建条目并使用 Object.fromEntries() 创建对象

0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
etc
  • 您总共需要2 ** keys.length数组中的对象。因此,使用 Array.from({ 2 ** keys.length }) 创建它
  • 在 map 函数中,使用 row.toString(2) 为当前行创建一个二进制数
  • 添加前导 0 直到字符串为 keys.length长:( "00001" )
  • 拆分字符串以使其成为数组( ["0", "0", "0", "0", "1"] )
  • 映射此数组并为相应的键创建一个条目数组[["arm","false"],["lens","false"],["season","false"],["food","false"],["size","false"]]
  • 使用 Object.fromEntries() 从条目数组创建一个对象

  • 这是一个片段:

    let keys = ['arm', 'lens', 'season', 'food', 'size'];

    function combination(keys) {
    return Array.from({ length: 2 ** keys.length }, (_, row) =>
    Object.fromEntries(
    row.toString(2)
    .padStart(keys.length, 0)
    .split('')
    .map((binary, j) => [keys[j], String(Boolean(+binary))])
    )
    )
    }

    console.log(combination(keys))

    关于javascript - JS 中的递归挑战将所有可能的数组键组合为 true |错误版本,我附上输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62114826/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com