同事今天出了一道题,已知一个序列[1,2,3,4,5],求由五个数组成的随机序列。结果比如12345,54321,32145这样的序列。
一个组合排列A(5,5)的问题,以下是我JS版本的实现。
如有其它算法,欢迎讨论。
var initData = [1,2,3,4,5];
var result = new Array();
function build(array, value){
if(array.length == 1){
value += array[0];
result.push(value);
return;
}
//检测每次取得随机数是否和之前有冲突
var conflictArr = new Array();
for(var i=0; i<array.length; i++){
var elems, rand;
do{
var index = getRandom(array);
elems = array.slice(0);
rand = array[index];
//删除随机数
elems.splice(index,1);
}while(checkconflict(conflictArr, rand))
var buffer = (value || '') + rand;
build(elems, buffer);
}
}
//检测冲突
function checkconflict(array, value){
for(var i=0; i<array.length;i++){
if(array[i] == value)
return true;
}
array.push(value);
return false;
}
function getRandom(array){
var index = Math.floor(Math.random() * array.length + 1) -1;
return index;
}
build(initData);
document.getElementById('show').innerText = result.join('\n');