Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

排列组合矩阵实现 #8

Open
erbing opened this issue Apr 23, 2019 · 2 comments
Open

排列组合矩阵实现 #8

erbing opened this issue Apr 23, 2019 · 2 comments

Comments

@erbing
Copy link
Owner

erbing commented Apr 23, 2019

有这么几个变量:

  • a 其值可能为 0、1
  • b 其值可能为 3、4、5
  • c 其值可能为 6、7

实现一个函数 getArranging 可以返回它们的可能值的排列组合二维数组:

function getArranging( ){
      //TODO - 返回参数的排列组合
}

var a = [0, 1];
var b = [3, 4, 5];
var c = [6, 7];

var ret = getArranging( a, b, c );
// ret 值为:
/**
[ [0,3,6], [0,3,7], [0,4,6], [0,4,7], [0,5,6], [0,5,7], [1,3,6], [1,3,7], [1,4,6], [1,4,7], [1,5,6], [1,5,7] ]
**/
@bq-hentai
Copy link

/** [1, 2] [3, 4, 5] [6, 7, 8] */

function gen (...xss) {
  const len = xss.length
  const ret = []

  if (len === 0) {
    return ret
  }

  function genCore (acc, xssIndex) {
    const xs = xss[xssIndex]
    if (xs.length !== 0) {
      xs.forEach((x, i) => {
        const newAcc = [...acc, x]
        if (xssIndex + 1 === len) {
          ret.push(newAcc)
          return
        }
        genCore(newAcc, xssIndex + 1)
      })
      return
    }
    genCore(acc, xssIndex + 1)
  }

  genCore([], 0)
  return ret
}

function test (...xs) {
  console.time('gen')
  const ret = gen(...xs)
  console.timeEnd('gen')
  return ret
}

test([1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])

爽不爽

@erbing
Copy link
Owner Author

erbing commented Apr 24, 2019

function cartesian (...lists) {
  return lists
    .map(list => list.map(item => [item]))
    .reduce((listsA, listsB) =>
      listsA.reduce((list, listA) =>
        list.concat(
          listsB.map(listB => listA.concat(listB))
        ), []
      )
    )
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

2 participants