Josephus Problem I

Consider a game where there are n children (numbers from 1,2,3,....,n) in a circle. During the game, every second child is removed from the circle, until there are no children left. In which order will the children be removed?

Example:

Input:  7
Output: 2 4 6 1 5 3 7 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

//function to solve the josephus problem
vector<intjosephusProblemI(int n)
{
    list<intarr;
    for (int i = 1i <= ni++)
    {
        arr.push_back(i);
    }
    auto it = arr.begin();

    //vector array to store the result
    vector<intres;
    while (arr.size() > 0)
    {
        it++;
        if (it == arr.end())
            it = arr.begin();
        res.push_back(*it);
        it = arr.erase(it);
        if (it == arr.end())
            it = arr.begin();
    }
    return res;
}
int main()
{

    int n = 7;

    vector<intres = josephusProblemI(n);

    for (int i = 0i < res.size(); i++)
        cout << res[i] << " ";
    return 0;
}


No comments:

Post a Comment