A Stupendous Program For Getting The Time In Words When We Input Hours And Minutes

 string timeInWords(int h, int m) {


map<int,string> mp{
{1,"one"},{2,"two"},{3,"three"},{4,"four"},{5,"five"},{6,"six"},{7,"seven"},
{8,"eight"},{9,"nine"},{10,"ten"},{11,"eleven"},{12,"twelve"},
{13,"thirteen"},{14,"fourteen"},{15,"fifteen"},{16,"sixteen"},
{17,"seventeen"},{18,"eighteen"},{19,"nineteen"},{20,"twenty"},
{21,"twenty one"},{22,"twenty two"},{23,"twenty three"},{24,"twenty four"},
{25,"twenty five"},{26,"twenty six"},{27,"twenty seven"},
{28,"twenty eight"},{29,"twenty nine"},{30,"thirty"},{31,"thirty one"},
{32,"thirty two"},{33,"thirty three"},{34,"thirty four"},{35,"thirty five"},
{36,"thirty six"},{37,"thirty seven"},{38,"thirty eight"},{39,"thirty nine"},
{40,"fourty"},{41,"fourty one"},{42,"fourty two"},{43,"fourty three"},
{44,"fourty four"},{45,"fourty five"},{46,"fourty six"},{47,"fourty seven"},
{48,"fourty eight"},{49,"fourty nine"},{50,"fifty"},{51,"fifty one"},
{52,"fifty two"},{53,"fifty three"},{54,"fifty four"},{55,"fifty five"},
{56,"fifty six"},{57,"fifty seven"},{58,"fifty eight"},{59,"fifty nine"},
{60,"sixty"}
};
//Iterator for pointing to string of minutes
map<int,string>:: iterator min=mp.find(m);
// Now pointing an iterator to string of hours 
map<int,string>:: iterator hour=mp.find(h);
//min is pointing to the string version of the Minute and hour to the string 
version of the Hour

//Checking if minute is 0
if(m==0){
        return hour->second+" o' clock"; 
}
//Also if minute is 15 that's a corner case where putting a different condition 
is needed
if(m==15){
return "quarter past "+hour->second;
}
//Same with case when minute is 30
if(m==30){
    return "half past "+hour->second;
}

//Now that we dealt with some corner cases we know that the minutes are not 
equal to them if we have come to this part of the code

//Therefore dealing with the rest default cases 
if(m>0 && m<30){
    if(m==1){
        return min->second+" minute past "+hour->second;
    }else{
        return min->second+" minutes past "+hour->second;
    }
}

//Iterator pointing to the string of the next hour which we will r
map<int,string>:: iterator next_hour=mp.find(h+1);

//Again dealing with the corner cases between 30 and 60
if(m==45){
    return "quarter to "+next_hour->second;
}

//Finding the difference of the minute from 60 to use it afterwards
int diff=60-m;
map<int,string>:: iterator itr=mp.find(diff);
//Dealing the default cases
if(m>30 && m!=59){
    return itr->second+" minutes to "+next_hour->second;
}

//A special case for 59
if(m==59){
    return "one minute to "+next_hour->second;
}
/* Most probably we won't reach this part of the code if the input
* is valid
*/
 /* But if we do by the grace of some malicious user then we will return simply
  * "buzz"
  *
  */
return "buzz";
}

Comments

Popular Posts