Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <vector>
- #include <sstream>
- #include <iostream>
- #include <iterator>
- void RestoreProgram(std::vector<std::string>& assembly)
- {
- for (unsigned int i = 0; i < assembly.size(); i++)
- {
- std::string& command = assembly[i];
- if (command[command.size() - 1] == '!')
- {
- command[command.size() - 1] = '\n';
- }
- }
- }
- bool RunProgram(std::vector<std::string>& assembly)
- {
- int acc = 0;
- int pos = 0;
- while (true)
- {
- if (pos >= assembly.size()) //Assume program ended successfully
- {
- std::cout << "Accumulator returned: " << acc << std::endl;
- RestoreProgram(assembly);
- return true;
- }
- std::string& command = assembly[pos];
- std::istringstream iss(command);
- std::vector<std::string> results(std::istream_iterator<std::string>{iss},
- std::istream_iterator<std::string>());
- if (command[command.size() - 1] == '!')
- {
- std::cout << "Infinite Loop Error! Last Pos: " << pos << std::endl;
- RestoreProgram(assembly);
- return false;
- }
- else if (results[0] == "acc")
- {
- acc += atoi(results[1].c_str());
- pos++;
- }
- else if (results[0] == "jmp")
- {
- pos += atoi(results[1].c_str());
- }
- else //Assume nop
- {
- pos++;
- }
- //std::cout << "Command: " << results[0] << " " << results[1] << " Pos: " << pos << " Acc " << acc << std::endl;
- command[command.size() - 1] = '!';
- }
- }
- int main()
- {
- std::vector<std::string> instructions;
- std::string text;
- while (getline(std::cin, text))
- instructions.push_back(text);
- std::cout << "Number of Instructions: " << instructions.size() << std::endl;
- for (unsigned int i = 0; i < instructions.size(); i++)
- {
- if (instructions[i][0] == 'n')
- {
- instructions[i][0] = 'j';
- instructions[i][1] = 'm';
- if (!RunProgram(instructions))
- {
- instructions[i][0] = 'n';
- instructions[i][1] = 'o';
- }
- else
- {
- std::cout << "Corrupted NOP found at line: " << i << std::endl;
- return 0;
- }
- }
- else if (instructions[i][0] == 'j')
- {
- instructions[i][0] = 'n';
- instructions[i][1] = 'o';
- if (!RunProgram(instructions))
- {
- instructions[i][0] = 'j';
- instructions[i][1] = 'm';
- }
- else
- {
- std::cout << "Corrupted JMP found at line: " << i << std::endl;
- return 0;
- }
- }
- }
- std::cout << "No fix found! :(" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement