Skip to content

Commit b24236d

Browse files
Merge pull request #61 from PawanJaiswal0843/master
1823.find-the-winner-of-the-circular-game.cpp
2 parents 63d64c3 + 2792ff0 commit b24236d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// 1823. Find the Winner of the Circular Game
2+
// Josephus Problem
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
6+
void solve(vector<int> &arr, int index, int k){
7+
if(arr.size() == 1)
8+
return;
9+
10+
index = (index + k) % arr.size();
11+
12+
arr.erase(arr.begin() + index);
13+
index--;
14+
15+
solve(arr, index, k);
16+
}
17+
18+
int findTheWinner(int n, int k) {
19+
vector<int> arr;
20+
for(int i = 1; i <= n; i++){
21+
arr.push_back(i);
22+
}
23+
int index = -1;
24+
solve(arr, index, k);
25+
return arr[0];
26+
}
27+
28+
int main(){
29+
// Input: n = 5, k = 2
30+
// Output: 3
31+
// Explanation: Here are the steps of the game:
32+
// 1) Start at friend 1.
33+
// 2) Count 2 friends clockwise, which are friends 1 and 2.
34+
// 3) Friend 2 leaves the circle. Next start is friend 3.
35+
// 4) Count 2 friends clockwise, which are friends 3 and 4.
36+
// 5) Friend 4 leaves the circle. Next start is friend 5.
37+
// 6) Count 2 friends clockwise, which are friends 5 and 1.
38+
// 7) Friend 1 leaves the circle. Next start is friend 3.
39+
// 8) Count 2 friends clockwise, which are friends 3 and 5.
40+
// 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
41+
int n = 4, k = 2;
42+
cout << findTheWinner(n,k);
43+
return 0;
44+
}
45+
46+
// for(int i = 0; i < arr.size(); i++){
47+
// cout << arr[i] << ' ';
48+
// }
49+
// cout<<endl;

0 commit comments

Comments
 (0)