All submissions

State Machine with Enums

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

// enum class State { Idle, Busy, Error };

// const char* toString(State s) {
//    switch (s) {
//        case State::Idle: return "Idle";
//        case State::Busy: return "Busy";
//        case State::Error: return "Error";
//    }
//    return "";
// }

// int main() {
//    int n;
//    cin >> n;
//    State state = State::Idle;
//    for (int i = 0; i < n; i++) {
//        string cmd;
//        cin >> cmd;
       
//        // your code here: implement transition logic to update state
       
//    }
//    cout << toString(state);
//    return 0;
// }

enum class State { Idle, Busy, Error};

const char* toString( State S){

    switch(S){
        case State::Idle : return "Idle";
        case State::Busy : return "Busy";
        case State::Error: return "Error";
    }
    return "";
}

int main(){
    int n;
    cin >> n ;
    State state = State::Idle;

    std::unordered_map<State,std::unordered_map<std::string,State>> fsm ={
        {State::Idle, {{"start",State::Busy}}},
        {State::Busy, {{"done",State::Idle},{"fail",State::Error}}},
        {State::Error, {} }
    };

    for(int i=0; i<n;i++){
        string cmd;
        cin >> cmd;

        if(fsm[state].count(cmd)){
            state = fsm[state][cmd];
        }
        // if(cmd == "start" && state == State::Idle){
        //     state= State::Busy;
        // }else if(cmd== "done" && state == State::Busy){
        //     state = State::Idle;
        // }else if(cmd== "fail" && state == State::Busy){
        //     state = State::Error;
        // }


        
    }
    cout<< toString(state);
    return 0;
}


/*
.count(key) is a method provided by unordered_map. It tells you if a key exists in the map:

Returns 1 if the key exists.

Returns 0 if it doesn't.


fsm[current].count("start") // = 1 → because "start" is a valid command
fsm[current].count("done")  // = 0 → no "done" command from Idle

If you try to access a key that doesn't exist without checking, it might:

Insert a default entry into the map (for regular maps).

Cause a crash or logic bug (for more complex structures).

So using .count(cmd) is a safe way to check if the command is valid for the current state before accessing the transition.

*/
Loading...

Input

3 start done start

Expected Output

Busy