Wednesday, March 30, 2005
Abstract Computer
[Question]
You have an abstract computer, so just forget everything you know about computers, this one only does what I'm about to tell you it does. You can use as many variables as you need, there are no negative numbers, all numbers are integers. You do not know the size of the integers, they could be infinitely large, so you can't count on truncating at any point. There are NO comparisons allowed, no if statements or anything like that. There are only four operations you can do on a variable.
1) You can set a variable to 0.
2) You can set a variable = another variable.
3) You can increment a variable (only by 1), and it's a post increment.
4) You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn't change so the first line in the loop can change value of v1 without changing the number of times you loop.
You need to do 3 things.
1) Write a function that decrements by 1.
2) Write a function that subtracts one variable from another.
3) Write a function that divides one variable by another.
4) See if you can implement all 3 using at most 4 variables. Meaning, you're not making function calls now, you're making macros. And at most you can have 4 variables. The restriction really only applies to divide, the other 2 are easy to do with 4 vars or less. Division on the other hand is dependent on the other 2 functions, so, if subtract requires 3 variables, then divide only has 1 variable left unchanged after a call to subtract. Basically, just make your function calls to decrement and subtract so you pass your vars in by reference, and you can't declare any new variables in a function, what you pass in is all it gets.
[Answer]
int dec(int a) //if a==0, return 0 else return a-1
{
int b = 0;
loop(a) { a = b; b++; }
// in the loop, the new a will be 0, 1, 2, ..., a-1
return a;
}
Based on decreament, substraction looks like
int sub(int a, int b)
{
loop(b) { dec(a); }
return a;
}
The other trick is how to implement if (!a) b++;
It is
loop(a) {a=0;a++;} //when a==0, a=0 else a=1
loop(a) {b++;} //when a==0, do nothing, else b++
Therefore we have
int Div(int a, int b)
{
int r=0; //store result
loop(a)
{
a = sub(a,b);
d = a;
// if (!d) r++
loop(d) {d=0;d++;};
loop(d) {r++;}
}
return r;
}