Advertisement
B1KMusic

99 bottles in english

Apr 13th, 2016
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.32 KB | None | 0 0
  1. /* Task: Generate the lyrics to 99 bottles.
  2.  * I decided to challenge myself and make it spell out the numbers, which proved to be a very interesting challenge.
  3.  * Because of the elegant way the versing is handled, this could be translated to a spanish version by merely changing the dictionaries and the verses.
  4.  * In fact, I'll do that right now. Google Translate, ahoy!
  5.  * -Braden
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10.  
  11. #define VERSE_1 "%s bottle%s of beer on the wall, %s bottle%s of beer.\n"
  12. #define VERSE_2 "Take one down, pass it around, %s bottle%s of beer on the wall.\n\n"
  13. #define VERSE_3 "No more bottles of beer on the wall, no more bottles of beer.\n"
  14. #define VERSE_4 "Go to the store, buy some more, ninety-nine bottles of beer on the wall.\n"
  15. #define SEPARATOR "-"
  16.  
  17. const char *ones_dict[] = {"no more", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
  18. const char *tens_dict[] = {0, 0, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
  19. const char *teens_dict[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
  20.  
  21. void to_english(char *buf, int bottles);
  22. int plural(int qty);
  23. void write_verse(int bottles);
  24.  
  25. void
  26. to_english(char *buf, int bottles)
  27. {/*{{{*/
  28.     int ones = bottles % 10,
  29.         tens = (bottles - ones) / 10;
  30.  
  31.     if(bottles == 0){
  32.         strncpy(buf, ones_dict[0], 30);
  33.     } else if(tens == 0){
  34.         strncpy(buf, ones_dict[ones], 30);
  35.     } else if(tens == 1){
  36.         strncpy(buf, teens_dict[ones], 30);
  37.     } else if(ones == 0){
  38.         strncpy(buf, tens_dict[tens], 30);
  39.     } else {
  40.         snprintf(buf, 30, "%s" SEPARATOR "%s", tens_dict[tens], ones_dict[ones]);
  41.     }
  42. }/*}}}*/
  43.  
  44. int
  45. plural(int qty)
  46. {/*{{{*/
  47.     return qty != 1;
  48. }/*}}}*/
  49.  
  50. void
  51. write_verse(int bottles)
  52. {/*{{{*/
  53.     char numbuf[30] = "";
  54.  
  55.     to_english(numbuf, bottles);
  56.     printf(VERSE_1, numbuf, plural(bottles) ? "s" : "", numbuf, plural(bottles) ? "s" : "");
  57.  
  58.     to_english(numbuf, bottles - 1);
  59.     printf(VERSE_2, numbuf, plural(bottles - 1) ? "s" : "");
  60.  
  61.     if(bottles - 1 == 0){
  62.         printf(VERSE_3 VERSE_4);
  63.     }
  64. }/*}}}*/
  65.  
  66. int
  67. main()
  68. {/*{{{*/
  69.     int bottles = 99;
  70.  
  71.     while(bottles){
  72.         write_verse(bottles);
  73.         bottles--;
  74.     }
  75. }/*}}}*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement