school/cs142/smcquay/midterm2/util.cc
2016-04-06 20:45:34 -07:00

57 lines
1.4 KiB
C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "util.h"
ostream & operator<<(ostream & os, vector<int> & v) {
os << "[";
for(unsigned int i = 0; i < v.size(); i++) {
os << v[i];
if(i != v.size() - 1) {
os << ", ";
}
}
os << "]";
return os;
}
int _increment_to_next_looser(const vector<bool> & players,
int start, const int step) {
int counter = 0;
// the test examples in the pdf have us start by killing the m-1th person
// offset by one for some dumb reason
int attempt = start - 1;
while(counter != step) {
attempt = (attempt + 1) % players.size();
if(players[attempt]) {
counter++;
}
}
return attempt;
}
vector<int> _play_game(vector<bool> & players, int step) {
vector<int> loosers;
int token = 0;
while(loosers.size() < players.size()) {
token = _increment_to_next_looser(players, token, step);
players[token] = false;
loosers.push_back(token);
}
return loosers;
}
int _test_run(int n, int m, bool verbose) {
if(m < 1) {
throw string("rule violation: m > 0");
}
vector<bool> players(n, true);
vector<int> loosers = _play_game(players, m);
if(verbose) {
cout << loosers << endl;
}
return loosers[loosers.size()-1];
}