code.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. std::string okay(std::string s) {
  2. std::string temp;
  3. for(int i = 0; i<s.size(); i++) {
  4. if(std::isdigit(s[i])) temp.push_back(s[i]);
  5. }
  6. return temp;
  7. }
  8. std::string fokay(std::string s) {
  9. std::string temp;
  10. for(int i = 0; i<s.size(); i++) {
  11. // floating pt can have a decimal
  12. if(std::isdigit(s[i]) || ('.' == s[i])) temp.push_back(s[i]);
  13. // again, if the first character is +/- this is ok
  14. if(0 == temp.size() && (('-' == s[i]) || ('+' == s[i]))) temp.push_back(s[i]);
  15. }
  16. return temp;
  17. }
  18. /* Given an RGB(A) CSS color, determine whether its
  19. * format is valid or not. Create a function that takes a string
  20. * (e.g. "rgb(0, 0, 0)") and return true if it's format is correct,
  21. * otherwise return false.
  22. * Alpha is between 0 and 1.
  23. * There are a few edge cases. Check out the Tests tab to know more.
  24. */
  25. bool validColor(std::string color) {
  26. // [!] I DO NOT AGREE WITH THIS TEST (whitespace_before_parenthesis)
  27. if(std::string::npos != color.find("rgb ")) return false;
  28. // [!] THIS TEST IS HIGHLY QUESTIONABLE (rgb_with_4_numbers / rgba_with_3_numbers)
  29. int expected = std::string::npos != color.find("rgba") ?4 :3;
  30. // [!] DEFINITELY NOT OK (numbers_below_0)
  31. if(std::string::npos != color.find('-')) return false;
  32. // [?] IDK, THIS IS MAYBE OKAY (numbers_above_100_percent)
  33. bool checkPercent = std::string::npos != color.find('%');
  34. // find the first comma, store the preceding number
  35. std::vector <std::string> rgb;
  36. for(int i = 0; i<3; i++){
  37. int position = color.find(',');
  38. // if a comma isn't found, stop.
  39. if(std::string::npos == position)break;
  40. // empty string is invalid parameter
  41. if(!position) return false;
  42. // a comma was found, copy everything before comma.
  43. rgb.push_back(okay(color.substr(0,position)));
  44. // delete the commma and everything before it.
  45. color = color.substr(position+1,std::string::npos);
  46. }
  47. // this is the third/fourth number
  48. if(color.size()){rgb.push_back(fokay(color));}
  49. if(rgb.size() != expected) return false;
  50. for(int j = 0;j<rgb.size();j++){
  51. if(j == 3){
  52. float rgbA = std::stof(rgb[3]);
  53. if(0>rgbA || rgbA>1){return false;}
  54. } else {
  55. int aNumber = std::stoi(rgb[j], nullptr, 10);
  56. // if aNumber is greater than 255 or less than 0, then its not valid
  57. if(0>aNumber || aNumber>255) return false;
  58. // [?] see (numbers_above_100_percent)
  59. if(checkPercent && aNumber>100) return false;
  60. }
  61. }
  62. return true;
  63. }