4 ms·
FizzBuzz from 1 to N (supplied as command-line argument) and exiting gracefully without using loops, conditionals, or segfaults - in C: #include <stdio.h>
by cronin101 11y ago
FizzBuzz from 1 to N (supplied as command-line argument) and exiting gracefully without using loops, conditionals, or segfaults - in C:
#include <stdio.h>
#include <stdlib.h>
int i(const int i) { printf("%d\n", i); return i; }
int f(const int i) { printf("Fizz\n"); return i; }
int b(const int i) { printf("Buzz\n"); return i; }
int fb(const int i) { printf("FizzBuzz\n"); return i; }
int (* PC[15])(int i) = { i,i,f,i,b,f,i,i,f,b,i,f,i,i,fb }; // Printer Cycle
int go(const int arg) {
return PC[(arg - 1) % 15](arg) + 1;
}
int stop(const int arg) {
PC[(arg - 1) % 15](arg);
exit(0);
}
int (* LC[2]) (int index) = { go, stop }; // Logic Cycle
void recurse(const int i, const int kill_num) {
recurse(LC[!(i % kill_num)](i), kill_num);
}
int main(const int argc, const char *argv[]) {
recurse(1, atoi(argv[1]));
}
- adrae5df 11y agoSo at what input value does it overflow the stack on your machine?
- jacquesm 11y agoNeat!
- ilurk 11y agoCould you explain these lines: > int (* PC[15])(int i) = { i,i,f,i,b,f,i,i,f,b,i,f,i,i,fb }; // Printer Cycle > int (* LC[2]) (int index) = { go, stop }; // Logic Cycle I can see they behave as functions, but I don't understand what exactly are they or the logic that makes then work.
- cronin101 11y agoI can try! They are both an array of pointers to functions. Go(int i) is a function that finds the correct "printer" for a number, i, within the cycle of 15. `Go` then calls the printer function with the argument and prints the corresponding line. Stop(int i) has similar side-effect but exits immediately after. Since all of the printers return the value of "i", you can recursively call them in cycle-sequence through `go` until the return value lines up with the "kill number" and causes `stop` to be called instead (this works as `i % n > 0` for all numbers below n and you can force this to be zero, and thus index the first element of the array, by negating it). Sorry for the scatterbrained explanation, the code wasn't designed to be particularly comprehensible!