Bowling/src/NumberUtils.cpp

140 lines
3.3 KiB
C++

#include "../include/NumberUtils.h"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cctype>
vector<int> NumberUtils::getRolls(const string& csv){
vector<int> rolls;
stringstream ss(csv);
string number;
// Get number from the CSV file, split by comma, and convert to int.
while (getline(ss, number, ',')) {
if (!isNumber(number)) {
cerr << number << " is not a number.";
break;
}
rolls.push_back(stoi(number));
}
return rolls;
}
bool NumberUtils::validateRolls(const vector<int>& rolls){
int rollCount = rolls.size();
for (int i = 0; i < rollCount; ++i) {
if (rolls[i] > 10 || rolls[i] < 0) {
cerr << "Number: " << rolls[i] << " is invalid.";
return false;
}
}
// A game can not have less than 12 rolls, and more than 21.
if (rollCount < 12 || rollCount > 21) {
cerr << "Incorrect amount of rolls.";
return false;
}
// 10th frame rule.
if (rollCount == 21) {
if (rolls[18] != 10 && rolls[18] + rolls[19] != 10) {
return false;
}
}
return true;
}
vector<Frame> NumberUtils::createFrames(const vector<int>& rolls){
vector<Frame> frame;
int roll = 0;
while (roll != rolls.size()) {
// Strike
if (rolls[roll] == 10) {
// If we're on our last frame, and roll a strike, we're given two bonus rolls.
if (roll + 3 == rolls.size() && rolls[roll - 3] == 10) {
frame.push_back(createBonusFrame(rolls[roll], rolls[roll + 1], rolls[roll + 2]));
break;
}
frame.push_back(createStrikeFrame(10));
roll += 1;
}
// Spare
else if (rolls[roll] + rolls[roll + 1] == 10) {
// If we're on our last frame, and roll a spare, we're given a bonus roll.
if (roll + 3 == rolls.size()) {
frame.push_back(createBonusFrame(rolls[roll], rolls[roll + 1], rolls[roll + 2]));
break;
}
frame.push_back(createFreeFrame(rolls[roll], rolls[roll + 1]));
roll += 2;
}
// Open Frame
else {
frame.push_back(createFreeFrame(rolls[roll], rolls[roll + 1]));
roll += 2;
}
}
return frame;
}
Frame NumberUtils::createStrikeFrame(int i){
struct Frame frame = Frame();
vector<int> rolls;
rolls.push_back(i);
frame.Roll = rolls;
return frame;
}
Frame NumberUtils::createFreeFrame(int i, int j){
struct Frame frame = Frame();
vector<int> rolls;
rolls.push_back(i);
rolls.push_back(j);
frame.Roll = rolls;
return frame;
}
Frame NumberUtils::createBonusFrame(int i, int j, int k){
struct Frame frame = Frame();
vector<int> rolls;
rolls.push_back(i);
rolls.push_back(j);
rolls.push_back(k);
frame.Roll = rolls;
return frame;
}
bool NumberUtils::isNumber(const std::string& str){
for (size_t i = 0; i < str.size(); ++i) {
if (!isdigit(str[i]) && !isspace(str[i])) return false;
}
return true;
}