几个人换礼物,且分到的不能是自己的(方法1)
作者:互联网
//根据索引值分礼物
function getPres(personNum,presentNum){
var getP = [];
for(var i=0;i<personNum.length;i++){
for(var j=0;j<presentNum.length;j++){
if(personNum[i]!=presentNum[j]){
getP.push([personNum[i],presentNum[j]]);
}
}
}
var getResult = [];
var result = randomGet(getP,getResult);
if(!result[result.length-1]){
getResult = [];
result = randomGet(getP,getResult);
}
//console.log(result);
}
function randomGet(getP,getResult){ var rad = Math.floor(Math.random()*(getP.length-1)); var getRad = getP[rad]; //console.log(getRad); getResult.push(getRad); if(getResult.length==personNum.length){ return getResult; } getP = getP.filter((item,index)=>{ if(item[0]!=getRad[0]&&item[1]!=getRad[1]){ return item; } }) //console.log(getP); return randomGet(getP,getResult); } var personNum = [1,2,3,4,5]; var presentNum = [1,2,3,4,5]; getPres(personNum,presentNum);
标签:分到,personNum,item,人换,var,getRad,getResult,getP,礼物 来源: https://www.cnblogs.com/xinyouhunran/p/14923420.html