Skip to content

Instantly share code, notes, and snippets.

@brimonk
Created May 7, 2019 04:05
Show Gist options
  • Save brimonk/9eca9034a730ec570587dce407e8db47 to your computer and use it in GitHub Desktop.
Save brimonk/9eca9034a730ec570587dce407e8db47 to your computer and use it in GitHub Desktop.
Fizz Buzz on State Machine with States Hardcoded
/*
* 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.
*
* He got mad that I didn't hardcode my state machine, so this version's for him.
*/
#include <stdio.h>
#include <stdlib.h>
#define USAGE "%s <num>\n"
struct state_t {
void (*func) (char *);
int 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);
}
// our machine state is hardcoded into the binary :)
struct state_t machine[15] = {
{pnum, 1},
{pnum, 2},
{fizz, 3},
{pnum, 4},
{buzz, 5},
{fizz, 6},
{pnum, 7},
{pnum, 8},
{fizz, 9},
{buzz, 10},
{pnum, 11},
{fizz, 12},
{pnum, 13},
{pnum, 14},
{fizzbuzz, 0}
};
int main(int argc, char **argv)
{
struct state_t *curr;
int i, c, maxnum;
char buf[32];
if (argc < 2) {
fprintf(stderr, USAGE, argv[0]);
return 1;
}
maxnum = atoi(argv[1]);
// execute the machine
for (curr = machine, i = 1; i < maxnum; i++, curr = &machine[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