实现方式1
使用数组和对象结合的方式
// 总人数n 报数出环数字k n=100 k=3 第i个人出环
console.time('b')
var stackArr = [];
for(var j=1;j<=100;j++){
stackArr.push(j);
}
function josephusStackDeal(obj){
var objArr = obj.objArr||[];
if(objArr.length == 0){
return;
}
var newArr = obj.newArr||[];
var newObj = {};
var firstEle = '';
var secondEle = '';
var thirdEle = '';
if(objArr.length==1){
newArr.push(objArr[0]-1);
objArr = [];
newObj = {
objArr:objArr,
newArr:newArr
}
console.log(newObj.newArr)
return newObj;
}
if(objArr.length==2){
thirdEle = objArr.shift();
newArr.push(thirdEle-1);
newObj = {
objArr:objArr,
newArr:newArr
}
return josephusStackDeal(newObj);
}
if(objArr.length>2){
firstEle = objArr.shift();
secondEle = objArr.shift();
thirdEle = objArr.shift();
objArr.push(firstEle);
objArr.push(secondEle);
newArr.push(thirdEle-1);
newObj = {
objArr:objArr,
newArr:newArr
}
return josephusStackDeal(newObj);
}
}
var newObjArr = josephusStackDeal({objArr:stackArr,newArr:[]})['newArr']
for (var i = 0; i < newObjArr.length; i++) {
console.log("第"+(i+1)+"次出环,下标为:"+newObjArr[i]);
}
console.timeEnd('b')
实现方式2
使用数组方式/链表
console.time('b')
// 总人数n 报数出环数字k n=100 k=3 第i个人出环
function josephRing(arr,obj){
var arr = arr||[];
var al=arr.length;
if(al ==0){
console.log('循环内没人');
return false;
}
var objArr = obj||[];
// 如果本轮循环数组最后一个出环人后还有1个或者2个人
if(al ==1){
objArr.push(arr[0]);
return objArr;
}
if(al ==2){
objArr.push(arr[0]);
objArr.push(arr[1]);
// console.log(objArr);
return objArr;
}
var l = 0;
var m = '';
var n = '';
var p ='';
if(al%3 == 1){
m = arr[al-1];
}
if(al%3 == 2){
m = arr[al-1];
n = arr[al-2];
}
for (var j = al-1; j >= 2; j--) {
if((j+1)%3 == 0){
p = arr.splice(j,1)[0];
if(l==0){
objArr.push(p);
}else{
objArr.splice(l,0,p);
}
l--;
}
}
// 先后顺序处理好,不然最后出现异常又不容易定位原因
if(m != ''){
arr.pop();
arr.unshift(m);
}
if(n != ''){
arr.pop();
arr.unshift(n);
}
return josephRing(arr, objArr);
}
var distArr = [];
for (var i = 0; i < 100; i++) {
distArr[i] = i;
}
var newObjArr = josephRing(distArr,[])
for (var i = 0; i < newObjArr.length; i++) {
console.log("第"+(i+1)+"次出环,下标为:"+newObjArr[i]);
}
console.timeEnd('b')
以上是原创,使用请注明出处。