前两天遇到的一道机试题,觉得挺有意思的,分享出来,大家可以在评论区中对代码予以改进,欢迎大家踊跃讨论😄
描述:
实现一个简单的语言解释器,支持以下指令:
指令格式 | 描述 |
---|---|
mov a v | 把数v赋值给a,其中a是变量名称,由不超过10个小写字母组成,v是变量名或者常数(常数为-10000~10000的整数) |
inc a | 变量a加1 |
dec a | 变量a减1 |
jnz a v | 如果变量a的值不是0,则相对跳转v条指令。比如-2 |
输入保证最多有100个变量,100条语句;执行inc, dec和jnz之前,相应变量一定已经用mov赋值过。
输出执行完毕后各个变量的值。
样例输入1
mov bx 2
mov ax 5
inc bx
dec ax
jnz ax -2
dec ax
样例输出1
ax -1
bx 7
Coding:
import java.util.*;
import java.util.regex.Pattern;
/**
* @author:eamon
* @create:2022/3/7,18:47
* @version:1.0
*/
public class Interpreter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> objs = new ArrayList<>();
boolean flag = true;
System.out.println("开始输入(输入 end 结束):");
while (flag) {
String s = sc.nextLine();
objs.add(s);
if ("end".equals(s) || objs.size() >= 100) {
flag = false;
}
}
System.out.println(test(objs));
}
public static HashMap<String, Integer> test(List<String> objs) {
boolean flag = true;
int size = objs.size();
int count = size;
HashMap<String, Integer> map = new HashMap<>();
while (flag) {
String s = objs.get(size - count);
String[] s1 = s.split(" ");
if (s1[0].equals("mov")) {
if (isInteger(s1[2])) {
map.put(s1[1], Integer.valueOf(s1[2]));
} else {
String[] s2 = objs.get(0).split(" ");
map.put(s1[1], map.get(s2[1]));
}
count--;
} else if (s1[0].equals("dec")) {
Integer res = map.get(s1[1]);
map.put(s1[1], res - 1);
count--;
} else if (s1[0].equals("inc")) {
Integer res = map.get(s1[1]);
map.put(s1[1], res + 1);
count--;
} else if (s1[0].equals("jnz")) {
Integer res = map.get(s1[1]);
if (res != 0) {
count = objs.size() - (size - count - Math.abs(Integer.valueOf(s1[2])));
} else {
count--;
}
}
if ("end".equals(s1[0])) {
flag = false;
}
}
return map;
}
/**
* 判断字符串中是否为数字
*
* @param str
* @return
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
}
测试&结果:
开始输入(输入 end 结束):
mov bx 2
mov ax 5
inc bx
dec ax
jnz ax -2
dec ax
end
{bx=7, ax=-1}