<head>
<title>js两个数组排列组合</title>
<script type="text/javascript">
var a = ["A","B","C"]
var b = ["1", "2","3"]
window.onload = function () {
var a1 = new objPL(a)//计算数组a的排列组合
var b1 = new objPL(b)//计算数组b的排列组合
var str = ""
var n = 0
//a1和b1的排列组合个数就是两者相乘(双层循环)
for (var i = 0 i < a1.length i++) {
for (var j = 0 j < b1.length j++) {
str += a1[i] + b1[j] + " "
n++
}
str += "<br/>"
}
document.write("共" + n + "个<br/>")
document.write(str)
}
//取数组的排列组合
function objPL(arr) {
this.a = arr
this.r = []
this.n = 0
//从M个数里面取N个(递归)
this.mGetN = function (curIndex, num, curSelect) {
if (num == 0) {
this.r[this.n++] = curSelect return
}
if (this.a.length - curIndex < num) return
this.mGetN(curIndex + 1, num - 1, curSelect + this.a[curIndex])
this.mGetN(curIndex + 1, num, curSelect)
}
for (var i = 1 i <= this.a.length i++) {
this.mGetN(0, i, "")
}
return this.r
}
</script>
</head>
<body></body>
</html>
["A","B","C"]与["1","2","3"]组合的结果:
var arr1 = []//你的原始数组function getArr(m,n){
var rt = []
for(var i=0i<mi++){
var arr = arr1.concat()
arr.splice(i,1)
getNext(arr,n-1)
}
return rt
function getNext(arr,n){
if(!n){
return rt.push(arr)
}
for(var i=0arr[i]i++){
var _arr = arr.concat()
_arr.splice(i,1)
getNext(_arr,n-1)
}
}
}
getArr(arr1.length,arr1.length - (arr1.length * Math.random() | 0))//这个也是随机的 m应该就是arr1数组的长度 n要说才是真正随机 第二个参数实际是m-n
function doExchange(doubleArrays){var len=doubleArrays.length
if(len>=2){
var len1=doubleArrays[0].length
var len2=doubleArrays[1].length
var newlen=len1*len2
var temp=new Array(newlen)
var index=0
for(var i=0i<len1i++){
for(var j=0j<len2j++){
temp[index]=doubleArrays[0][i]+
doubleArrays[1][j]
index++
}
}
var newArray=new Array(len-1)
for(var i=2i<leni++){
newArray[i-1]= doubleArrays[i]
}
newArray[0]=temp
return doExchange(newArray)
}
else{
return doubleArrays[0]
}
}