1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
bool is_valid_roman(std::string);
int main()
{
std::vector<std::string> test{"xxix","iphone","xxx","xxxix","XXM","xl","xlviii","xyz","c","lxxxix",\
"lxxxii","abcd","liii","xxvii","house","LXVIII","mmcccxl","monxxv",
"MMMCMXCIX", "vv","dd","xxxx","xxx","ccc","cccc","iii","iiiii"
};
for(auto roman : test)
{
std::cout<<roman;
if(is_valid_roman(roman))
std::cout<<" -- is valid\n";
else
std::cout<<" -- is invalid\n";
}
///you can use it like this.
/*
if(is_valid_roman(number))
///do something with number
else
///print some error
*/
}
///this function follows rules from the referenced website
bool is_valid_roman(std::string roman)
{
auto legal = "IVXLCDM";
for(auto& rom : roman)///to uppercase
rom = std::toupper(rom);
if(roman.find_first_not_of(legal) != std::string::npos)///contains invalid characters
return false;
std::string rule5("IXC"); ///for rule five
for(auto rom : rule5)
{
if(roman.find(std::string(4,rom)) != std::string::npos) ///rule 5
return false;
}
std::string rule6("VLD"); ///for rule 6
for(auto rom : rule6)
{
if(roman.find(std::string(2,rom)) != std::string::npos)///rule 6
return false;
}
///each character can only precede the characters in the string "this is from a table i saw here"
///goo.gl/RTDazU
std::map<char,std::string> rule7{ {'I',"IVX"},{'X',"IVXLC"},{'C',"IXLCDM"} };
std::string check_case = "IXC";
std::size_t index = 0;
auto one_past_last = roman.size();
while(index < one_past_last) ///precedence rule
{
auto rom = roman[index];
if(((index+1) < one_past_last) && (check_case.find(rom)!=std::string::npos))
{
auto next_rom = roman[index+1];
auto preceds = rule7[rom];
if(preceds.find(next_rom) == std::string::npos)
return false;
}
++index;
}
return true;
}
|