For part1 I translated the code directly into C with a program in python:
importosimportstringTEMPLATE=string.Template("""
#include <stdio.h>
int regs[] = $registers;
void addr(int a, int b, int c) {
regs[c] = regs[a] + regs[b];
}
void addi(int a, int b, int c) {
regs[c] = regs[a] + b;
}
void mulr(int a, int b, int c) {
regs[c] = regs[a] * regs[b];
}
void muli(int a, int b, int c) {
regs[c] = regs[a] * b;
}
void banr(int a, int b, int c) {
regs[c] = regs[a] & regs[b];
}
void bani(int a, int b, int c) {
regs[c] = regs[a] & b;
}
void borr(int a, int b, int c) {
regs[c] = regs[a] | regs[b];
}
void bori(int a, int b, int c) {
regs[c] = regs[a] | b;
}
void setr(int a, int b, int c) {
regs[c] = regs[a];
}
void seti(int a, int b, int c) {
regs[c] = a;
}
void gtir(int a, int b, int c) {
regs[c] = (a > regs[b]) ? 1 : 0;
}
void gtri(int a, int b, int c) {
regs[c] = (regs[a] > b) ? 1 : 0;
}
void gtrr(int a, int b, int c) {
regs[c] = (regs[a] > regs[b]) ? 1 : 0;
}
void eqir(int a, int b, int c) {
regs[c] = (a == regs[b]) ? 1 : 0;
}
void eqri(int a, int b, int c) {
regs[c] = (regs[a] == b) ? 1 : 0;
}
void eqrr(int a, int b, int c) {
regs[c] = (regs[a] == regs[b]) ? 1 : 0;
}
int main() {
while (1) {
switch(regs[$ipreg]) {
$cases
default: printf("Execution: %d\\n", regs[0]); return 0;
}
regs[$ipreg] += 1;
}
}
""")defcompile_line(line):opname=line[:4]a,b,c=line[4:].split()return'%s(%s, %s, %s);'%(opname,a,b,c)defcompile_lines(lines):cases=[]forlineno,lineinenumerate(lines):cases.append(' case %d: %s break;'%(lineno,compile_line(line)))return'\n'.join(cases)defcompile_file(fname,registers):withopen(fname,'r')asprogram:registers=str(registers).replace('[','{').replace(']','}')ipreg=program.readline().strip()[4:]cases=compile_lines(line.strip()forlineinprogram)returnTEMPLATE.substitute(ipreg=ipreg,cases=cases,registers=registers)defpart1(fname):name,_=os.path.splitext(fname)withopen(name+'_part1.c','w')ascompiled:program=compile_file(fname,[0,0,0,0,0,0])compiled.write(program)defpart2(fname):name,_=os.path.splitext(fname)withopen(name+'_part2.c','w')ascompiled:program=compile_file(fname,[1,0,0,0,0,0])compiled.write(program)if__name__=="__main__":part1('test_input.txt')part2('test_input.txt')part1('input.txt')part2('input.txt')
The program was able to execute part1 but part2 was taking forever.
Then, after some failed ideas, I did a translator into "assembler" to study the code:
For part1 I translated the code directly into C with a program in python:
The program was able to execute part1 but part2 was taking forever.
Then, after some failed ideas, I did a translator into "assembler" to study the code:
Then I studied the result:
And, after drawing a flowchart, I reassembled the code into:
The code sums all factors of the number stored in r1 !!!!
So, I factored 10551315 = 3*5*31*22691 and then sum all the divisors, as the program does.
For me it has been the best problem so far !!!