Problem:
There are M monkeys in a circle, ordered every number from 1 to m in order to choose a king; After consultation, decided to choose the King's rules: from the first start cycle count, the number of n monkeys out of the circle, and finally the left is the king. Requirements: From the keyboard input m, N, programmed to calculate which number of monkeys to become king
Example:
For example, there are 5 monkeys, from 1 to 3 count off, the choice of the king's steps are as follows:
first count: 1->2->3 //3 out of the ring for the
second time off: 4->5->1 //1 out of the ring for the
third time: 2- >4->5 //5 Elimination ring
fourth time off: 2->4->2 //2 out of the ring
4th King.
//Monkey.cpp:Defines The entry point for the console application.
Scenario I: Using arrays
#include "stdafx.h" #include <iostream> using namespace std; int findmonkeyking (int m,int n) {int* a= new int[m];//Move the monkey from 1 to m number for (int i=1;i<=m;i++) {a[i-1]=i;} int start=0;//First time Count off starting from the first monkey int count=n;//record number of times int len=m;//record array size while (m>1) {while (count>1) {if (a[start]>0) {count--; if (
start+1) <len) start++;
else start=0;
} else {if (start+1<len) start++; else start=0;} }//Find the monkey to be eliminated from the ring while (a[start]==0) {if (Start+1<len) start++; else start=0;}//cout<<a[start]<< "_" <&L
t;start<<endl;
a[start]=0;//the monkey out. Find the next monkey to start off from 1 while (a[start]==0) {if (Start+1<len) start++; else start=0;}//cout<<a[start]<< "_" <
;<start<<endl;
count=n;//prepare for the next cycle m--;
}//Find an array element that has only the remaining value in the array that is not 0 is the selected monkey King int j=0;
while (a[j++]==0);
Return a[j-1];//This place to be careful, take a step back} int main (int argc, char* argv[]) {int m,n;
cout<< "Please enter the total number of monkeys m:";
cin>>m;
cout<<endl;
cout<< "Please enter the number of counts N:";
cin>>n; Cout<<endL
int monkeyking=findmonkeyking (M,N);
cout<< "No. <<monkeyKing<<" Monkey is king "<<endl;
return 0; }