Introduction to Logic Tests Series
What you can do with this tiny programming language with only 4 instructions? Today, we are going to implement the DECR function which decrements the variable by one, for example, DECR(X) where X=5 will make X=4.
1 2 3 | DECR(X) { } |
DECR(X) { }
The only 4 instructions are: INCR, LOOP, ZERO and ASGN. And all variables hold non-negative integers. To make X decremented by 1, we can increment a temp variable by (X-1) times..
1 2 3 4 5 6 7 | DECR(X) { ZERO(V1) LOOP(X) { ASGN(X, V1) INCR(V1) } } |
DECR(X) { ZERO(V1) LOOP(X) { ASGN(X, V1) INCR(V1) } }
We translate this to C++, which might be a bit easy to understand.
1 2 3 4 5 6 7 8 9 | void decr(unsigned int &x) { int v1 = 0; int xx = x; for (; x > 0; -- x) { xx = v1; v1 ++; } x = xx; } |
void decr(unsigned int &x) { int v1 = 0; int xx = x; for (; x > 0; -- x) { xx = v1; v1 ++; } x = xx; }
If you change the value of the loop variable x, the loop iteration count may be altered. Therefore, we declare a temp variable xx and assign the xx to X after loop when it gets incremented (x-1) times.
You may also like: 逻辑测试系列之二 – DECR
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: The experience of using Teamviewer on iPhone SE, connecting to desktop, and SSH to VPS, in order to make a Robot Python script up running.
Next Post: Applying Naive Bayes Algorithm in Rock-Scissor-Paper Game