Refactor c/beer-song/beer_song.c

This commit is contained in:
dwrz
2019-05-31 22:08:36 +00:00
parent 36f046e6e9
commit 73920fa56d
+44 -42
View File
@@ -1,57 +1,59 @@
#include <stdio.h> #include <stdio.h>
int verse(char* response, int bottles) { int verse(char* response, int bottles) {
if (bottles < 0) { if (response == NULL || bottles < 0) {
return 0; return 0;
} }
switch (bottles) { switch (bottles) {
case 0: case 0:
return sprintf(response, return sprintf(response,
"No more bottles of beer on the wall, " "No more bottles of beer on the wall, "
"no more bottles of beer.\n" "no more bottles of beer.\n"
"Go to the store and buy some more, " "Go to the store and buy some more, "
"99 bottles of beer on the wall.\n"); "99 bottles of beer on the wall.\n");
case 1: case 1:
return sprintf(response, return sprintf(response,
"1 bottle of beer on the wall, " "1 bottle of beer on the wall, "
"1 bottle of beer.\n" "1 bottle of beer.\n"
"Take it down and pass it around, " "Take it down and pass it around, "
"no more bottles of beer on the wall.\n"); "no more bottles of beer on the wall.\n");
case 2: case 2:
return sprintf(response, return sprintf(response,
"2 bottles of beer on the wall, " "2 bottles of beer on the wall, "
"2 bottles of beer.\n" "2 bottles of beer.\n"
"Take one down and pass it around, " "Take one down and pass it around, "
"1 bottle of beer on the wall.\n"); "1 bottle of beer on the wall.\n");
default: default:
return sprintf(response, return sprintf(response,
"%d bottles of beer on the wall, " "%d bottles of beer on the wall, "
"%d bottles of beer.\n" "%d bottles of beer.\n"
"Take one down and pass it around, " "Take one down and pass it around, "
"%d bottles of beer on the wall.\n", "%d bottles of beer on the wall.\n",
bottles, bottles, bottles - 1); bottles, bottles, bottles - 1);
} }
} }
void sing(char *response, int start, int finish) { void sing(char *response, int start, int finish) {
char *origin = response; if (response == NULL || start < 0 || finish < 0 || start <= finish) {
return;
}
for (int bottles = start; bottles >= finish; bottles--) { char *origin = response;
int charsAdded = verse(response, bottles);
response += charsAdded;
// Add a newline between verses, for (int bottles = start; bottles >= finish; bottles--) {
// except for the last verse. int charsAdded = verse(origin, bottles);
if (bottles != finish) { origin += charsAdded;
sprintf(response, "\n");
response += 1;
}
}
response = origin; // Add a newline between verses,
// except for the last verse.
if (bottles != finish) {
sprintf(origin, "\n");
origin += 1;
}
}
} }