3 - Brainf interpreter

2024 September 11, 1.5 hours

Slideshow

We split up the team into two groups. The people who were new to Java worked on the Wordle clone. The people who were more familiar worked on the Brainf interpreter.

Final code

Main.java
1public class Main {
2    public static void main(String[] args) {
3        BrainfuckReader reader = new BrainfuckReader();
4        String code = reader.getCode("code.brainf");
5        BrainfuckInterpreter interpreter = new BrainfuckInterpreter(code);
6        interpreter.interpret();
7    }
8}
BrainfuckReader.java
 1import java.io.File;
 2import java.nio.file.Files;
 3
 4public class BrainfuckReader {
 5    public String getCode(String fileName) {
 6        try {
 7            return Files.readString(new File(fileName).toPath());
 8        } catch (Exception err) {
 9            System.err.println(err);
10        }
11        return "";
12    }
13}
BrainfuckInterpreter.java
 1public class BrainfuckInterpreter {
 2    String code;
 3    char[] memory = new char[3000];
 4    int[] posRightBracketForLeftBracket = new int[3000];
 5
 6    public BrainfuckInterpreter(String code) {
 7        this.code = code;
 8    }
 9
10    public void interpret() {
11        int dataPointer = 0;
12        int posLeftBracket = -1;
13        for(int i = 0; i < this.code.length(); i++) {
14            char command = this.code.charAt(i);
15
16            switch (command) {
17                case '[': {
18                    posLeftBracket = i;
19                } break;
20                case ']': {
21                    posRightBracketForLeftBracket[posLeftBracket] = i;
22                }
23                default: break;
24            }
25        }
26        posLeftBracket = -1;
27        for(int i = 0; i < this.code.length(); i++) {
28            char command = this.code.charAt(i);
29
30            switch (command) {
31                case '>':
32                    dataPointer++;
33                    break;
34                case '<':
35                    dataPointer--;
36                    break;
37                case '+':
38                    memory[dataPointer]++;
39                    break;
40                case '-':
41                    memory[dataPointer]--;
42                    break;
43                case '.': {
44                    System.out.print(memory[dataPointer]);
45                } break;
46                case '[': {
47                    posLeftBracket = i;
48                    if(memory[dataPointer] == 0) {
49                        i = posRightBracketForLeftBracket[i];
50                    }
51                } break;
52                case ']': {
53                    if(memory[dataPointer] != 0) {
54                        i = posLeftBracket;
55                    }
56                } break;
57                default:
58                    break;
59            }
60        }
61    }
62}