exercism

Exercism solutions.
git clone git://code.dwrz.net/exercism
Log | Files | Refs

beer_song.c (1471B)


      1 #include <stdio.h>
      2 
      3 int verse(char* response, int bottles) {
      4 	if (response == NULL || bottles < 0) {
      5 		return 0;
      6 	}
      7 
      8 	switch (bottles) {
      9 	case 0:
     10 		return sprintf(response,
     11 			       "No more bottles of beer on the wall, "
     12 			       "no more bottles of beer.\n"
     13 			       "Go to the store and buy some more, "
     14 			       "99 bottles of beer on the wall.\n");
     15 
     16 	case 1:
     17 		return sprintf(response,
     18 			       "1 bottle of beer on the wall, "
     19 			       "1 bottle of beer.\n"
     20 			       "Take it down and pass it around, "
     21 			       "no more bottles of beer on the wall.\n");
     22 
     23 	case 2:
     24 		return sprintf(response,
     25 			       "2 bottles of beer on the wall, "
     26 			       "2 bottles of beer.\n"
     27 			       "Take one down and pass it around, "
     28 			       "1 bottle of beer on the wall.\n");
     29 
     30 	default:
     31 		return sprintf(response,
     32 			       "%d bottles of beer on the wall, "
     33 			       "%d bottles of beer.\n"
     34 			       "Take one down and pass it around, "
     35 			       "%d bottles of beer on the wall.\n",
     36 			       bottles, bottles, bottles - 1);
     37 
     38 	}
     39 }
     40 
     41 void sing(char *response, int start, int finish) {
     42 	if (response == NULL || start < 0 || finish < 0 || start <= finish) {
     43 		return;
     44 	}
     45 
     46 	char *origin = response;
     47 
     48 	for (int bottles = start; bottles >= finish; bottles--) {
     49 		int charsAdded = verse(origin, bottles);
     50 		origin += charsAdded;
     51 
     52 		// Add a newline between verses,
     53 		// except for the last verse.
     54 		if (bottles != finish) {
     55 			sprintf(origin, "\n");
     56 			origin += 1;
     57 		}
     58 	}
     59 }