-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.sh
68 lines (59 loc) · 1.23 KB
/
.sh
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
bash
#!/bin/bash
Define constants
MEMORY_SIZE=1024
PROGRAM_COUNTER=0
ACCUMULATOR=0
Initialize memory
declare -a MEMORY
for ((i=0; i<$MEMORY_SIZE; i++)); do
MEMORY[$i]=0
done
Load program
load_program() {
local program=("$@")
for ((i=0; i<${#program[@]}; i++)); do
MEMORY[$i]=${program[$i]}
done
}
Execute program
execute_program() {
while [ $PROGRAM_COUNTER -lt $MEMORY_SIZE ]; do
instruction=${MEMORY[$PROGRAM_COUNTER]}
case $instruction in
1) # ADD
PROGRAM_COUNTER=$((PROGRAM_COUNTER+1))
ACCUMULATOR=$((ACCUMULATOR+MEMORY[$PROGRAM_COUNTER]))
;;
2) # SUB
PROGRAM_COUNTER=$((PROGRAM_COUNTER+1))
ACCUMULATOR=$((ACCUMULATOR-MEMORY[$PROGRAM_COUNTER]))
;;
3) # HALT
break
;;
*) # Unknown instruction
echo "Unknown instruction: $instruction"
exit 1
;;
esac
PROGRAM_COUNTER=$((PROGRAM_COUNTER+1))
done
}
Reset VM
reset_vm() {
PROGRAM_COUNTER=0
ACCUMULATOR=0
for ((i=0; i<$MEMORY_SIZE; i++)); do
MEMORY[$i]=0
done
}
Example program: ADD 5, SUB 3, HALT
program=(1 5 2 3 3)
Load and execute program
load_program "${program[@]}"
execute_program
Print result
echo "Accumulator: $ACCUMULATOR"
Reset VM
reset_vm