表示许多数组的唯一索引的数字

时间:2016-11-16 21:34:55

标签: javascript arrays algorithm

我有一个应用程序,它接收每个或可变长度的多个数据数组。我计划循环并显示我给出的每个数组的每个数据组合。我的第一个倾向是让一个数字代表每个数组的状态,因为我知道组合的数量是每个数组元素数量的乘积。

例如:

A = [0,1,2,3]

B = [0,1,2,3]

C = [0,1]

所以我需要代表4 x 4 x 2 = 32种组合

我已经设法通过使用每个array.length将modulo和division应用于给定索引来表示所有状态。我的问题是它排序不好(参见下面的代码段)。有没有人解决过类似的问题,或者知道如何更改算法以使其按顺序排列?

<p id="demo"></p>
struct list {
    ...  
    ...
    const unsigned char nop=0x90; // 27 bytes since the begining of the structure
    const unsigned char jump=0xeb; // 28 bytes since the begining of the structure
    const unsigned char hlt=0xf4; // 29 bytes since the begining of the structure
    unsigned __int128 i=0xeb90eb90eb90eb90f4f4 // should start at the 30th byte, but get aligned on a 16 byte boundary and starts on the 32th byte instead
    const unsigned char data=0x66; // should start at the 46th byte, but start on the 48th instead.
}; // end of struct list.

1 个答案:

答案 0 :(得分:0)

在我看来,保持指数分离将是一个更好的方法。

增加指数可能有点类似于我们在小学中手工添加两个数字的方式 - 如果索引太大,则将其设置为零并逐个增加下一个数字:

&#13;
&#13;
var a = [0, 1, 2, 3]
var b = [0, 1, 2, 3]
var c = [0, 1]

var state = {
  a: 0,
  b: 0,
  c: 0
}

function increment() {
  state.a++;

  if (state.a >= a.length) {
    state.b++;
    state.a = 0;
  }
  if (state.b >= b.length) {
    state.c++;
    state.b = 0;
  }
  if (state.c >= c.length) {
    state.c = 0;
  }

  console.log(state);
}

console.log(state);
&#13;
<button onclick='increment()'>Increment</button>
&#13;
&#13;
&#13;

根据state更新文档应该是非常简单的。

相关问题