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
+9 -7
View File
@@ -1,7 +1,7 @@
#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;
} }
@@ -39,19 +39,21 @@ int verse(char* response, int bottles) {
} }
void sing(char *response, int start, int finish) { void sing(char *response, int start, int finish) {
if (response == NULL || start < 0 || finish < 0 || start <= finish) {
return;
}
char *origin = response; char *origin = response;
for (int bottles = start; bottles >= finish; bottles--) { for (int bottles = start; bottles >= finish; bottles--) {
int charsAdded = verse(response, bottles); int charsAdded = verse(origin, bottles);
response += charsAdded; origin += charsAdded;
// Add a newline between verses, // Add a newline between verses,
// except for the last verse. // except for the last verse.
if (bottles != finish) { if (bottles != finish) {
sprintf(response, "\n"); sprintf(origin, "\n");
response += 1; origin += 1;
} }
} }
response = origin;
} }