-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03_bf.c
67 lines (63 loc) · 1.34 KB
/
03_bf.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
static void jumpFront(const char *str, int *index) {
if (str[*index] != '[')
return;
for (int count = 0; str[*index] != '\0'; (*index)++) {
if (str[*index] == '[')
count++;
else if (str[*index] == ']')
count--;
if (count == 0)
break;
}
}
static void jumpBack(const char *str, int *index) {
if (str[*index] != ']')
return;
for (int count = 0; *index >= 0; (*index)--) {
if (str[*index] == '[')
count--;
else if (str[*index] == ']')
count++;
if (count == 0)
break;
}
}
static int brainfuck(const char *str) {
static int data[100];
int pointer = sizeof(data) / sizeof(int) / 2;
for (int index = 0; str[index] != '\0'; index++) {
switch (str[index]) {
case '+':
data[pointer]++;
break;
case '-':
data[pointer]--;
break;
case '>':
pointer++;
break;
case '<':
pointer--;
break;
case '.':
// No device to output to...
break;
case ',':
// No device to input from...
break;
case '[':
if (data[pointer] == 0)
jumpFront(str, &index);
break;
case ']':
if (data[pointer] != 0)
jumpBack(str, &index);
break;
}
}
return data[pointer];
}
int main(int argc, char **argv) {
// Run argv[1] as brainf*ck code.
return brainfuck(argv[1]);
}