【问题标题】:How to get all combinations of an array with generic size?如何获得具有通用大小的数组的所有组合?
【发布时间】:2018-11-01 09:22:16
【问题描述】:

我有一个类似 [1,-1,0] 的数组,我想用这个数组项和通用大小生成所有组合向量。例如尺寸:3 和输出: [1 1 1] [1 1 0] [1 1 -1] ... [0 0 0] 或大小:4 和输出:[1 1 1 1] [1 1 1 0] ... [0 0 0 0] 或其他大小和其他数组。

如何用泛型数组和泛型大小制作?

【问题讨论】:

  • 您能指定您使用哪种编程语言来执行此操作吗?另外,请添加您尝试过的sn-ps
  • C# 或 Javascript

标签: arrays generics recursion combinations


【解决方案1】:

您提到了 JavaScript,所以这是使用生成器的一种方式

const append = (xs, x) =>
  xs .concat ([ x ])

const ncomb = function* (n, xs = [])
{ const gen = function* (n, acc)
  { if (n === 0)
      yield acc
    else
      for (const x of xs)
        yield* gen (n - 1, append (acc, x))
  }
  yield* gen (n, [])
}

const data =
  [ 1, 2, 3 ]

const print = (...xs) =>
  console.log (...xs.map (x => JSON.stringify (x)))

print
  ( Array.from (ncomb (0, data))
    // [[]]
    
  , Array.from (ncomb (1, data))
    // [[1],[2],[3]]
    
  , Array.from (ncomb (2, data))
    // [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
    
  , Array.from (ncomb (3, data))
    // [[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3],[1,3,1],[1,3,2],[1,3,3],[2,1,1],[2,1,2],[2,1,3],[2,2,1],[2,2,2],[2,2,3],[2,3,1],[2,3,2],[2,3,3],[3,1,1],[3,1,2],[3,1,3],[3,2,1],[3,2,2],[3,2,3],[3,3,1],[3,3,2],[3,3,3]]
  )

组合上方最右边的元素递增,但可以更改此顺序。如果您将append 操作更改为prepend,您将生成最左侧元素递增的组合——

const prepend = (xs, x) =>
  [ x ] .concat (xs)

print
  ( Array.from (ncomb (3, data))
    // [[1,1,1],[2,1,1],[3,1,1],[1,2,1],[2,2,1],[3,2,1],[1,3,1],[2,3,1],[3,3,1],[1,1,2],[2,1,2],[3,1,2],[1,2,2],[2,2,2],[3,2,2],[1,3,2],[2,3,2],[3,3,2],[1,1,3],[2,1,3],[3,1,3],[1,2,3],[2,2,3],[3,2,3],[1,3,3],[2,3,3],[3,3,3]]
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多