简体   繁体   English

查找JavaScript中的所有组合

[英]Finding all combinations in javascript

I am creating a game and I need to generate some game pieces. 我正在创建一个游戏,我需要生成一些游戏作品。 Each piece is an array consisting of 4 numbers(each represents a property of the piece) ranging from 0-2. 每个片段都是一个由4个数字组成的数组(每个数字代表该片段的一个属性),范围为0-2。 I need to generate all combinations to get all the game pieces. 我需要生成所有组合才能获得所有游戏作品。

So I would need [1, 0, 2, 0], [2, 0, 0, 1], [0, 0, 0, 0], [1, 0, 1, 0] etc.. 所以我需要[1、0、2、0],[2、0、0、1],[0、0、0、0],[1、0、1、0]等。

There should be 81 total combinations of [a, b, c, d] where each variable is a number 0-2. [a,b,c,d]总共应该有81个组合,其中每个变量的数字都是0-2。

I am using javascript but any psudocode would be helpful. 我正在使用javascript,但任何伪代码都会有所帮助。

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

If it is a homework, tag it as such. 如果是作业,则将其标记为作业。

var BASE = 3, LEN = 4, LIMIT = Math.round(Math.pow(BASE, LEN));
var c = [];
for (var i = 0; i < LIMIT; ++i) {
  var item = [];
  for (var j = 0, k = i; j < LEN; ++j, k = Math.floor(k/BASE)) {
    item.push(k % BASE);
  }
  c.push(item);
}

Here is a more tricky solution but showing the math behind it better, hopefully: 这是一个更棘手的解决方案,但希望能更好地展示其背后的数学原理:

var BASE = 3, LEN = 4;
var powers = [];
for (var i = 0, LIMIT = 1; i < LEN; ++i, LIMIT *= BASE) {
  powers.push(LIMIT);
}
var c = [];
for (i = 0; i < LIMIT; ++i) {
  c.push(powers.map(function(basePower) {
    return Math.floor(i/basePower) % BASE;
  }));
}

Mine

var arr=[];
for (var str,i=0;i<81;i++) {
  str = i.toString(3);
  arr.push(("000"+str).slice(-4)); // Hmm, I thought slice returned an array.
}

Here is an update taking into account the comments from @katspaugh and @herby 这是考虑到@katspaugh和@herby的评论的更新

var arr=[];
for (var str,i=81;i<162;i++) {
  str = i.toString(3);
  arr.push((str).slice(-4).split('').map(Number));
}
var BASE = 3, COMB_LEN = 4

var max = parseInt(new Array(COMB_LEN + 1).join(BASE - 1), BASE),
    comb = new Array(COMB_LEN + 1).join(0).split('').map(Number)

var combinations = [], i, n
for (i = 0; i <= max; i++) {
    n = i.toString(BASE).split('').map(Number)
    combinations.push(
        comb.slice(0, COMB_LEN - n.length).concat(n)
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM