Modify the solution to attached solution to the Josephus problem so that the kil
ID: 3807589 • Letter: M
Question
Modify the solution to attached solution to the Josephus problem so that the kill interval and the initial number of victims are function parameters.
here is my code below:
main.cpp
include <algorithm>
include <iomanip>
include <iostream>
include <iterator>
include <list>
include <string>
include <vector>
using namespace std;
template <typename T>
void show(const list<T>& elts, unsigned fwidth = 2, ostream& sout = cout)
{
for (int elt : elts)
sout << setw(fwidth) << elt << ' ';
sout << endl;
}
void kill(list<unsigned>& victims)
{
unsigned killcount = 1;
list<unsigned>::iterator it = victims.begin();
while (victims.size() > 2)
{
if (killcount == 3)
{
list<unsigned>::iterator dit = it;
it++;
victims.erase(dit);
killcount = 1;
show(victims);
}
else
{
it++;
killcount++;
}
if (it == victims.end()) it = victims.begin();
}
}
void load(list<unsigned>& victims)
{
unsigned id = 1;
for (list<unsigned>::iterator it = victims.begin(); it != victims.end(); it++)
*it = id++;
}
int main()
{
list<unsigned> victims(41);
load(victims);
show(victims);
kill(victims);
system("pause");
return 0;
}
Explanation / Answer
include <algorithm>
include <iomanip>
include <iostream>
include <iterator>
include <list>
include <string>
include <vector>
using namespace std;
template <typename T>
void show(const list<T>& elts, unsigned fwidth = 2, ostream& sout = cout)
{
for (int elt : elts)
sout << setw(fwidth) << elt << ' ';
sout << endl;
}
void kill(list<unsigned>& victims)
{
unsigned killcount = 1;
list<unsigned>::iterator it = victims.begin();
while (victims.size() > 2)
{
if (killcount == 3)
{
list<unsigned>::iterator dit = it;
it++;
victims.erase(dit);
killcount = 1;
show(victims);
}
else
{
it++;
killcount++;
}
if (it == victims.end()) it = victims.begin();
}
}
void load(list<unsigned>& victims)
{
unsigned id = 1;
for (list<unsigned>::iterator it = victims.begin(); it != victims.end(); it++)
*it = id++;
}
int main()
{
list<unsigned> victims(41);
load(victims);
show(victims);
kill(victims);
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.