12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- #include <QCoreApplication>
- bool validColor(std::string color);
- std::string okay(std::string s);
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- validColor("rgb(0,,0)");
- return a.exec();
- }
- std::string okay(std::string s) {
- std::string temp;
- for(int i = 0; i<s.size(); i++) {
- if(std::isdigit(s[i])) temp.push_back(s[i]);
- }
- return temp;
- }
- std::string fokay(std::string s) {
- std::string temp;
- for(int i = 0; i<s.size(); i++) {
- // floating pt can have a decimal
- if(std::isdigit(s[i]) || ('.' == s[i])) temp.push_back(s[i]);
- // again, if the first character is +/- this is ok
- if(0 == temp.size() && (('-' == s[i]) || ('+' == s[i]))) temp.push_back(s[i]);
- }
- return temp;
- }
- /* Given an RGB(A) CSS color, determine whether its
- * format is valid or not. Create a function that takes a string
- * (e.g. "rgb(0, 0, 0)") and return true if it's format is correct,
- * otherwise return false.
- * Alpha is between 0 and 1.
- * There are a few edge cases. Check out the Tests tab to know more.
- */
- bool validColor(std::string color) {
- // [!] I DO NOT AGREE WITH THIS TEST (whitespace_before_parenthesis)
- if(std::string::npos != color.find("rgb ")) return false;
- // [!] THIS TEST IS HIGHLY QUESTIONABLE (rgb_with_4_numbers / rgba_with_3_numbers)
- int expected = std::string::npos != color.find("rgba") ?4 :3;
- // [!] DEFINITELY NOT OK (numbers_below_0)
- if(std::string::npos != color.find('-')) return false;
- // [?] IDK, THIS IS MAYBE OKAY (numbers_above_100_percent)
- bool checkPercent = std::string::npos != color.find('%');
- // find the first comma, store the preceding number
- std::vector <std::string> rgb;
- for(int i = 0; i<3; i++){
- int position = color.find(',');
- // if a comma isn't found, stop.
- if(std::string::npos == position)break;
- // empty string is invalid parameter
- if(!position) return false;
- // a comma was found, copy everything before comma.
- rgb.push_back(okay(color.substr(0,position)));
- // delete the commma and everything before it.
- color = color.substr(position+1,std::string::npos);
- }
- // this is the third/fourth number
- if(color.size()){rgb.push_back(fokay(color));}
- if(rgb.size() != expected) return false;
- for(int j = 0;j<rgb.size();j++){
- if(j == 3){
- float rgbA = std::stof(rgb[3]);
- if(0>rgbA || rgbA>1){return false;}
- } else {
- int aNumber = std::stoi(rgb[j], nullptr, 10);
- // if aNumber is greater than 255 or less than 0, then its not valid
- if(0>aNumber || aNumber>255) return false;
- // [?] see (numbers_above_100_percent)
- if(checkPercent && aNumber>100) return false;
- }
- }
- return true;
- }
|