Help with DFA coding to reject and accept strings with two 0's and at most one 1's,
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
enum State {
q00, q01, q02, q10, q11, q20, q21,
ACCEPT
};
enum State transition(enum State currentState, char input) {
switch (currentState) {
case q00:
if (input == '0') return q10;
if (input == '1') return q01;
break;
case q01:
if (input == '0') return q02;
break;
case q02:
// No transitions from q02
break;
case q10:
if (input == '0') return q20;
if (input == '1') return q11;
break;
case q11:
if (input == '0') return q21;
if (input == '1') return q21; // Stay in q21 for any additional '1'
break;
case q20:
if (input == '0') return ACCEPT; // Accept if another '0' is found
if (input == '1') return q21;
break;
case q21:
// No transitions from q21
break;
default:
break;
}
return currentState;
}
bool isAccepted(enum State currentState) {
return currentState != ACCEPT && currentState != q20;
}
int main() {
char input[100];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
if (input[strlen(input) - 1] == '\n') {
input[strlen(input) - 1] = '\0';
}
enum State currentState = q00;
for (int i = 0; input[i] != '\0'; i++) {
currentState = transition(currentState, input[i]);
}
if (isAccepted(currentState)) {
printf("String accepted.\n");
} else {
printf("String rejected.\n");
}
return 0;
}
That is my code, i am trying to get it to reject or accpet strings that have at least two 0's and at most one 1's. I am struggling as when i input 110, it accepts not reject.
5 Replies
$cpp
We're partnered with Together C & C++, check them out here: https://discord.gg/vnyVmAE
oh is this wrong server??
yep this is a c# server
oh ok
thanks