Skip to content

Instantly share code, notes, and snippets.

@brimonk
Created May 7, 2019 03:51
Show Gist options
  • Save brimonk/d68bc98f87582d6958aa776508ff0d6f to your computer and use it in GitHub Desktop.
Save brimonk/d68bc98f87582d6958aa776508ff0d6f to your computer and use it in GitHub Desktop.
Doing Fizz Buzz with a State Machine
/*
* Brian Chrzanowski
* Mon May 06, 2019 23:41
*
* This was a meme. A friend of mine thought about how you could do fizz-buzz
* as a 15(ish) state machine.
*
* I think my thing is closer to a circular linked list with function pointers,
* but that's whatever.
*/
#include <stdio.h>
#include <stdlib.h>
#define USAGE "%s <num>\n"
struct state_t {
void (*func) (char *);
struct state_t *next;
};
void fizz(char *s)
{
printf("fizz\n");
}
void buzz(char *s)
{
printf("buzz\n");
}
void fizzbuzz(char *s)
{
printf("fizz buzz\n");
}
void pnum(char *s)
{
printf("%s\n", s);
}
int main(int argc, char **argv)
{
struct state_t *curr;
struct state_t machine[15];
int i, c, maxnum;
char buf[32];
if (argc < 2) {
fprintf(stderr, USAGE, argv[0]);
return 1;
}
maxnum = atoi(argv[1]);
// push states onto the machine
for (curr = machine, i = 0, c = 1; i < 15; i++, c++, curr++) {
curr->next = curr + 1;
if (c % 3 == 0 && c % 5 == 0) {
curr->func = fizzbuzz;
} else if (c % 5 == 0) {
curr->func = buzz;
} else if (c % 3 == 0) {
curr->func = fizz;
} else {
curr->func = pnum;
}
}
// hook up the link to the first state, to execute "forever"
curr--;
curr->next = &machine[0];
// execute the machine
for (curr = machine, i = 1; i < maxnum; i++, curr = curr->next) {
snprintf(buf, sizeof(buf), "%d", i);
printf("%d\t", i);
curr->func(buf);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment