Untitled
unknown
java
a year ago
3.1 kB
3
Indexable
package org.opcode.service; import org.opcode.model.Register; import org.opcode.model.RegisterState; import java.util.*; public class OpcodeSimulatorImpl implements OpcodeSimulator { private Map<Character, Register> registerMap; private Map<String, InstructionFactory> instructionFactoryMap; public OpcodeSimulatorImpl() { initializeRegisters(); initializeInstructionFactoryMap(); } private void initializeRegisters() { registerMap = new HashMap<>(); registerMap.put('A', new Register('A')); registerMap.put('B', new Register('B')); registerMap.put('C', new Register('C')); registerMap.put('D', new Register('D')); } private void initializeInstructionFactoryMap() { instructionFactoryMap = new HashMap<>(); instructionFactoryMap.put("SET", parts -> new SetInstruction(parts[1].charAt(0), Integer.parseInt(parts[2]))); instructionFactoryMap.put("ADD", parts -> new AddInstruction(parts[1].charAt(0), Integer.parseInt(parts[2]))); instructionFactoryMap.put("ADR", parts -> new AdrInstruction(parts[1].charAt(0), parts[2].charAt(0))); instructionFactoryMap.put("MOV", parts -> new MovInstruction(parts[1].charAt(0), parts[2].charAt(0))); instructionFactoryMap.put("INR", parts -> new InrInstruction(parts[1].charAt(0))); instructionFactoryMap.put("DCR", parts -> new DcrInstruction(parts[1].charAt(0))); instructionFactoryMap.put("RST", parts -> new RstInstruction()); instructionFactoryMap.put("XOR", parts -> new XorInstruction(parts[1].charAt(0), parts[2].charAt(0))); } @Override public RegisterState execute(List<String> instructions) { for (String instruction : instructions) { String[] parts = instruction.split(" "); InstructionFactory factory = instructionFactoryMap.get(parts[0]); if (factory != null) { Instruction inst = factory.create(parts); inst.execute(registerMap); } else { throw new UnsupportedOperationException("Unsupported operation: " + parts[0]); } } return new RegisterState(new ArrayList<>(registerMap.values())); } public static void main(String[] args) { // Initialize the simulator OpcodeSimulator simulator = new OpcodeSimulatorImpl(); // Define the instructions to be executed List<String> instructions = new ArrayList<>(); instructions.add("SET A 10"); instructions.add("SET B 5"); instructions.add("XOR A B"); // Execute the instructions RegisterState state = simulator.execute(instructions); // Print the final state of the registers System.out.println("Register A: " + state.getRegister('A').getValue()); // Should print 15 if XOR works System.out.println("Register B: " + state.getRegister('B').getValue()); // Should print 5 } } @FunctionalInterface interface InstructionFactory { Instruction create(String[] parts); }
Editor is loading...
Leave a Comment