返回列表

排列、组合计算 javascript

默认分类 2020/06/17 03:15

从n个中选m个 排列 计算方法:n!/(n-m)! 如 3选2 = 3!/1! = 3

从n个中选m个 组合 计算方法:n!/(m!(n-m)!) 如 3选2 = 3!/(1!*2!) = 3

javascript 代码如下:

function combine (list, num) {
  let arr = arrange (list, num)
  let maps = {}
  let result = []
  arr.forEach(it => {
    it.sort()
    if (!maps[JSON.stringify(it)]) {
      maps[JSON.stringify(it)] = true
      result.push(it)
    }
  })
  return result
}

function arrange (list, num) {
  if (num === 1) return list.map(it => [it])
  else if (num < 1 || num > list.length) return []
  // list = [1, 5, 3]
  let result = []
  let len1 = list.length
  for (let i = 0; i < len1; i++) {
    let cur = list[i]

    let left = [].concat(list)
    left.splice(i, 1)
    let arr = arrange(left, num - 1)

    for (let j = 0, len2 = arr.length; j < len2; j++) {
      result.push([cur].concat(arr[j]))
    }
  }
  return result
}

>> arrange([1,2,3], 2)
[[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]

>> combine([1,2,3], 2)
[[1,2],[1,3],[2,3]]


>> 留言评论