DEV Community

Juliuz Christian Llanillo
Juliuz Christian Llanillo

Posted on

Finite State Machine - How vending machines know you're actually a good guy that pays the right amount

Ever wonder how those vending machines act like they are something so intelligent but does not actually have a chance to proclaim that they'll conquer the world? You don't? Oh I see... Well let's talk about it anyway. You never know...

These darlings uses something called "Finite State", hence the term "Finite State Machine". They actually works without any memory but instead dwell on their current "state".
No memory yet they can remember where they are?
Yep, but let's not use the term "remember", as it will become confusing. Instead, they "stay" in a place and from there, they'll know what do they need to reach your desired drink on that vending machine. This is what we call "state".

Every time the machine needs to know what it needs, it just knows its current state. It does not hold any history data or anything that will tell it "where" it came from. It just knows what state it is in.

Alt Text

Note that the currency is simplified to 5 & 10 gold for simplicity. Also, it's more like a game if we do it that way. Yes, I just went for a cooler currency I apologize for reasoning it as basely for simplicity.

The above chart illustrates a simple FSM (Finite State Machine) logic behind those seemingly-intelligent vending machine buddy of yours. As you can see, whenever you insert a 5 gold, it goes into its next state, from 0 to 5, it does not need to know "How much do I need?", it just needs to know "Am I there yet?" (To its accepted state, which is 20). When it reaches the accepted state, that's the only time you can get your desired drink.
You can think of it as a conversation between you and that vending machine:

Alt Text

Though there's that possibility that what if you put in too much gold? Well, there are vending machines that are just accepts that, well it's profit anyway but there are vending machines that weren't put in too much effort and just errors out as it came across an invalid state. That's rare nowadays as vending machines are quite advanced now, but in reality, they don't need that much of an advancement, they're capable enough of giving you your drink but of course we're humans, we level up things. Otherwise, it wouldn't be fun ain't it?

Kudos to you for spending time with me! Now for a challenge, why don't you create a program that replicates vending machines? It'll be fun!

Top comments (0)