var a = [1,2,3]
var b = [1,2,3]
var c = [1,2,3,4]
每个数组里面拿出一个数 组成一个三位数
上面的共有36种组合
我想计算出每个组合的位置
[1,1,1] 位置是1
[1,1,2] 位置是2
[2,2,4] 位置是?
我想求其中一个组合的位置是多少,有没有具体的公式?
这是一个数学问题嘛
a
每提升一个位置,就经历了 b
和 c
的全部组合,也就是 12
个b
每提升一个位置,经历了 c
的每一项,也就是 4
所以 [2,2,4] 就是
12([1,x,x])
+ 4([2,1,x])
+ 4[2,2,1-4]
= 20
下面写个程序验证一下
javascript
var a = [1,2,3]; var b = [1,2,3]; var c = [1,2,3,4]; var n = 1; for (var i = 0; i < a.length; i++) { for (var j = 0; j < b.length; j++) { for (var k = 0; k < c.length; k++) { console.log((n++) + ": [" + a[i] + "," + b[j] + "," + c[k] + "]"); } } }
结果(为了缩短调试,只贴了有用的部分)
plain
1: [1,1,1] ... 7: [1,2,3] ... 19: [2,2,3] 20: [2,2,4] 21: [2,3,1] ... 28: [3,1,4] 29: [3,2,1] 30: [3,2,2] ... 35: [3,3,3] 36: [3,3,4]
下面再给个算位置的代码
没写注释,自己试着理解下,不明白的发评论
javascript
var a = [1,2,3]; var b = [1,2,3]; var c = [1,2,3,4]; var all = [a,b,c]; var allCount = [b.length * c.length, c.length, 0]; function getIndex(combo) { var count = 0; for (var i = 0; i < combo.length; i++) { var pos = all[i].indexOf(combo[i]); if (pos < 0) { throw new Error(combo[i] + "不是有效的元素"); } count += allCount[i] * pos; } count += combo[combo.length - 1]; return count; } console.log("index of [2,2,4] is " + getIndex([2,2,4])); console.log("index of [1,1,1] is " + getIndex([1,1,1])); console.log("index of [3,3,4] is " + getIndex([3,3,4])); console.log("index of [1,2,3] is " + getIndex([1,2,3])); console.log("index of [3,2,1] is " + getIndex([3,2,1]));
输出(跟上面的验证输出验证下)
index of [2,2,4] is 20
index of [1,1,1] is 1
index of [3,3,4] is 36
index of [1,2,3] is 7
index of [3,2,1] is 29