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