Last active
January 26, 2024 14:28
-
-
Save cgsdev0/e2c518c30dac6c05376243ad0c5fbbbf to your computer and use it in GitHub Desktop.
FizzBuzz State Machine (C++)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
(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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sketch of the state machine:
