Inspirated

 
 

July 1, 2008

Programming Challenges: Interpreter

Filed under: Blog — krkhan @ 8:38 am

PC/UVa IDs: 110106/10033, Popularity: B, Success rate: low, Level: 2

Nothing extraordinarily interesting here — typical straight-outta-the-book exercise.

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
 
using namespace std;
 
bool decode(int &pc, vector< int > &reg, vector< int > &ram)
{
	int inst = ram.at(pc);
	int c = inst / 100,
		a = (inst % 100) / 10,
		b = inst % 10;
 
	switch(c) {
	case 1:
		return false;
		break;
	case 2:
		reg.at(a) = b;
 
		pc++;
		break;
	case 3:
		reg.at(a) += b;
		reg.at(a) %= 1000;
 
		pc++;
		break;
	case 4:
		reg.at(a) *= b;
		reg.at(a) %= 1000;
 
		pc++;
		break;
	case 5:
		reg.at(a) = reg.at(b);
 
		pc++;
		break;
	case 6:
		reg.at(a) += reg.at(b);
		reg.at(a) %= 1000;
 
		pc++;
		break;
	case 7:
		reg.at(a) *= reg.at(b);
		reg.at(a) %= 1000;
 
		pc++;
		break;
	case 8:
		reg.at(a) = ram.at(reg.at(b));
 
		pc++;
		break;
	case 9:
		ram.at(reg.at(b)) = reg.at(a);
 
		pc++;
		break;
	case 0:
		if(reg.at(b) == 0) {
			pc++;
		} else {
			pc = reg.at(a);
		}
 
		break;
	}
 
	return true;
}
 
int main(int argc, char *argv[])
{
	string dummy;
	int ncases;
 
	cin>>ncases;
 
	// ignore two empty lines
	getline(cin, dummy);
	getline(cin, dummy);
 
	for(int n = 0; n < ncases; n++) {
		vector< int > reg(10), ram(1000);
 
		fill(reg.begin(), reg.end(), 0);
		fill(ram.begin(), ram.end(), 0);
 
		for(int i = 0; i < 1000; i++) {
			string str;
 
			getline(cin, str);
			if(str == "") {
				break;
			}
 
			istringstream iss(str);
			iss>>ram.at(i);
		}
 
		int executed = 1;
		int pc = 0;
		while(decode(pc, reg, ram)) {
			executed++;
		}
 
		if(n > 0) {
			cout<<endl;
		}
		cout<<executed<<endl;
	}
 
	return 0;
}
Tags: , , , , , , , , ,