约瑟夫环问题
今天在做面试题时,用递归解决了约瑟夫环问题;
=======================================================================================
public class Test extends Sprite {
/**存储当前人数*/
private var arr:Array = [];
/**总人数*/
private static const TOTAL:int = 10;
/**间隔*/
private static const NUM:int = 3;
/**初始位置*/
private var startIndex:int = 0;
public function Test() {
initArr();
find(startIndex);
}
/**初始化数组*/
private function initArr():void{
arr = [];
for (var i:int = 1; i <= TOTAL; i++){
arr.push(i);
}
}
/**从指定的index处开始查找第NUM个数*/
private function find(index):int{
if ( arr.length > 1){
var i:int = (index + NUM - 1) % arr.length;
trace("出队序号:" + arr[i]);
resetArr(i);
return find(i);
}else{
trace("最后一个:" + arr[0]);
return 0;
}
}
/**去掉被踢出的人*/
private function resetArr(index:int):void{
for (var i:int = index; i < arr.length-1; i++){
arr[i] = arr[i+1];
}
arr.pop();
}
}