File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 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;
You can’t perform that action at this time.
0 commit comments