-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfa.c
92 lines (78 loc) · 2 KB
/
dfa.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include"dfa.h"
#include<stdlib.h>
#include <string.h>
struct DFA{
int nstates;
int** table;
bool* accept;
};
/**
* Allocate and return a new DFA containing the given number of states.
*/
DFA* new_DFA(int nstates) {
DFA* object = (DFA*)malloc(sizeof(struct DFA));
if (object != NULL) {
object->nstates = nstates;
object->table = (int**)calloc(nstates, sizeof(int*));
for (int i =0; i < nstates; i++){
object->table[i] = (int*)calloc(128, sizeof(int));
for (int j = 0; j<128; j++){
object->table[i][j] = -1;
}
}
}
object->accept = (bool*)calloc(nstates,sizeof(bool));
return object;
}
//Free?
/**
* Return the number of states in the given DFA->
*/
int DFA_get_size(DFA* dfa){
return dfa->nstates;
}
/**
* Return the state specified by the given DFA's transition function from
* state src on input symbol sym->
*/
int DFA_get_transition(DFA* dfa, int src, char sym){
return dfa->table[src][(int)sym];
}
/**
* For the given DFA, set the transition from state src on input symbol
* sym to be the state dst->
*/
void DFA_set_transition(DFA* dfa, int src, char sym, int dst){
dfa->table[src][(int)sym] = dst;
}
/**
* Set whether the given DFA's state is accepting or not->
*/
void DFA_set_accepting(DFA* dfa, int state, bool value){
dfa->accept[state] = value;
}
/**
* Return true if the given DFA's state is an accepting state->
*/
bool DFA_get_accepting(DFA* dfa, int state){
return dfa->accept[state];
}
/**
* Run the given DFA on the given input string, and return true if it accepts
* the input, otherwise false->
*/
bool DFA_execute(DFA* dfa, char *input){
int current = 0;
for (int i = 0; i<strlen(input);i++){
current = dfa->table[current][(int)input[i]];
if (current == -1){
break;
}
}
if(DFA_get_accepting(dfa, current)){
return true;
}else{
return false;
}
}