Goldfish/Implementation
Jump to navigation
Jump to search
Goldfish implementation in C++ by User:Fergusq.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
const int SIZE = 10000;
const int HALF = SIZE/2;
int vars[SIZE];
string funcs[SIZE];
int runFunction(int n, int p);
int main(int argc, char * argv[]) {
if (argc != 2) {
cerr << "usage: goldfish <file>" << endl;
return 1;
}
ifstream in(argv[1]);
if (in.is_open()) while (!in.eof()) {
int n;
string code;
char chr;
in >> n;
chr = in.get();
while (chr != '\n' && chr != '\r' && !in.eof()) {
if (!isspace(chr)) code += chr;
chr = in.get();
}
if (code.length()) {
funcs[HALF+n] = code;
}
} else {
cerr << "io error" << endl;
return 1;
}
runFunction(0, 0);
return 0;
}
/**
* Runs a function
*/
int runFunction(int n, int p) {
int &v = vars[HALF+n];
string code = funcs[HALF+n];
int i = 0;
while (code[i]) {
switch (code[i++]) {
case 'i':
v++;
break;
case 'I':
p++;
break;
case 'd':
v--;
break;
case 'D':
p--;
break;
case 's':
v *= v;
break;
case 'S':
p *= p;
break;
case 'n':
v=0;
break;
case 'N':
p=0;
break;
case 'c':
v = runFunction(v, p);
break;
case 'C':
v = runFunction(p, v);
break;
case 'x':
case 'X':
{ int tmp = p; p = v; v = tmp; }break;
case 'm':
funcs[HALF+p] = funcs[HALF+v];
break;
case 'M':
funcs[HALF+v] = funcs[HALF+p];
break;
case 'o':
cout << (char)v; cout.flush();
break;
case 'O':
cout << (char)p; cout.flush();
break;
case 'r':
cin >> (char&)v;
break;
case 'R':
cin >> (char&)p;
break;
case 'h':
case 'H':
exit(0);
break;
}
}
return v;
}