fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. // Define all possible states
  5. typedef enum {
  6. STATE_LOCKED,
  7. STATE_UNLOCKING,
  8. STATE_UNLOCKED,
  9. STATE_LOCKING,
  10. STATE_COUNT // Total number of states
  11. } State;
  12.  
  13. // Function pointer type for state handlers
  14. typedef void (*StateHandler)(void);
  15.  
  16. // Current state variable
  17. State currentState = STATE_LOCKED;
  18.  
  19. // Simulated input functions
  20. bool unlockButtonPressed() {
  21. static int count = 0;
  22. return (++count == 2); // Press at step 2
  23. }
  24.  
  25. bool doorOpened() {
  26. static int count = 0;
  27. return (++count == 4); // Opened at step 4
  28. }
  29.  
  30. bool doorClosed() {
  31. static int count = 0;
  32. return (++count == 6); // Closed at step 6
  33. }
  34.  
  35. // State handler functions
  36. void stateLocked() {
  37. printf("[LOCKED] Waiting...\n");
  38. if (unlockButtonPressed()) {
  39. printf("Unlock button pressed.\n");
  40. currentState = STATE_UNLOCKING;
  41. }
  42. }
  43.  
  44. void stateUnlocking() {
  45. printf("[UNLOCKING] Door is being unlocked...\n");
  46. currentState = STATE_UNLOCKED;
  47. }
  48.  
  49. void stateUnlocked() {
  50. printf("[UNLOCKED] Door is unlocked.\n");
  51. if (doorOpened()) {
  52. printf("Door opened.\n");
  53. }
  54. if (doorClosed()) {
  55. printf("Door closed. Locking...\n");
  56. currentState = STATE_LOCKING;
  57. }
  58. }
  59.  
  60. void stateLocking() {
  61. printf("[LOCKING] Door is being locked...\n");
  62. currentState = STATE_LOCKED;
  63. }
  64.  
  65. // State handler table (function pointer array)
  66. StateHandler stateTable[STATE_COUNT] = {
  67. stateLocked,
  68. stateUnlocking,
  69. stateUnlocked,
  70. stateLocking
  71. };
  72.  
  73. int main() {
  74. // Simulate system loop
  75. for (int i = 0; i < 10; i++) {
  76. printf("\nCycle %d:\n", i + 1);
  77. if (currentState < STATE_COUNT) {
  78. stateTable[currentState](); // Call the current state's handler
  79. }
  80. }
  81. return 0;
  82. }
  83.  
Success #stdin #stdout 0.01s 5288KB
stdin
45
stdout
Cycle 1:
[LOCKED] Waiting...

Cycle 2:
[LOCKED] Waiting...
Unlock button pressed.

Cycle 3:
[UNLOCKING] Door is being unlocked...

Cycle 4:
[UNLOCKED] Door is unlocked.

Cycle 5:
[UNLOCKED] Door is unlocked.

Cycle 6:
[UNLOCKED] Door is unlocked.

Cycle 7:
[UNLOCKED] Door is unlocked.
Door opened.

Cycle 8:
[UNLOCKED] Door is unlocked.

Cycle 9:
[UNLOCKED] Door is unlocked.
Door closed. Locking...

Cycle 10:
[LOCKING] Door is being locked...