Skip to content

Instantly share code, notes, and snippets.

@cgsdev0
Last active January 26, 2024 14:28
Show Gist options
  • Save cgsdev0/e2c518c30dac6c05376243ad0c5fbbbf to your computer and use it in GitHub Desktop.
Save cgsdev0/e2c518c30dac6c05376243ad0c5fbbbf to your computer and use it in GitHub Desktop.
FizzBuzz State Machine (C++)
/*
(Dumb) idea to implement the classic FizzBuzz
problem as a state machine with 16 states.
*/
#include <iostream>
#include <vector>
#include <functional>
#include <stdlib.h>
#define HALT_AT 100
typedef std::function<int(int)> State;
State stateBuilder(auto func) {
return [=](int i) -> int {
// Perform the action of the state
std::cout << func(i) << std::endl;
// Transition state
if (i >= HALT_AT) return 0;
return i % 15 + 1;
};
}
#define MAKE_STATE(x) stateBuilder([](int i) { return (x); })
State itos = MAKE_STATE(std::to_string(i));
State fizz = MAKE_STATE("Fizz");
State buzz = MAKE_STATE("Buzz");
State fzbz = MAKE_STATE("FizzBuzz");
State halt = [](auto) -> int { exit(0); };
int main() {
// Create and program our state machine
std::vector<State> machine(0x10, itos);
machine[0x3] = machine[0x6] = machine[0x9] = machine[0xC] = fizz;
machine[0x5] = machine[0xA] = buzz;
machine[0xF] = fzbz;
machine[0x0] = halt;
// Run the state machine
int i = 1, state = 1;
while(state) {
state = machine[state](i++);
}
return 0;
}
@brimonk
Copy link

brimonk commented Jun 10, 2019

I love this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment