开发者

tactics to think as a computer

开发者 https://www.devze.com 2023-02-04 17:18 出处:网络
I have some question from the exam in which I need to deduce the output of the following code: 01 int foo(int a) {

I have some question from the exam in which I need to deduce the output of the following code:

01 int foo(int a) {
02 print 'F';
03 if (a <= 1) return 1;
04 return bar(a, foo(a-1));
05 }
06
07 int bar(int x, int y) {
08 print 'B';
09 if (x > y) return baz(x, y);
10 return baz(y, x);
11 }
12
13 int baz(int x, int y) {
14 print 'Z'
15 if (y == 0) return 0;
16 return baz(x, y-1) + x;
17 }
18
19 void main() {
20 foo(3);
21 }

my question is what tactic will be the best to solve this kind of the questions? I'm not开发者_开发问答 allowed to use PC of course P.S. You can use eager evaluation as in c++ or normal order evaluation(output will be different of course, but I'm interested in tactics only), I tried to solve it using stack, every time write the function which I call, but anyway it is complicated thanks in advance for any help


I would use a "bottom-to-top" attempt:

baz is the function that is called, but doesn't call other functions (except itself). It outputs 'Z' exactly y + 1 times, the return code is x*y (you add x after each call).

bar is the "next higher" function, it outputs 'B' once and calls baz with its lower argument as the second parameter - the return code is x*y, too.

foo is the "top" function (right after main) and its the most complicated function. It outputs 'F', not only once, but a times (because of the foo(a-1) at the end that is evaluated before the bar call. The bar call multiplies a and foo(a-1), which will multiply a-1 and foo(a-2) and so on, until foo(1) is evaluated and returns 1. So the return code is a * (a-1) * ... 2 * 1, so a!.

This is not a complete analysis, f.e. we don't know in which order the characters will be output, but it is a rough scheme of what happens - and as you and other people in the comments pointed out, this is what you want - tactics instead of a complete answer.


What I'd probably do is to start with the main() function at the top left corner of the page, write down the first line executed, keeping track of local variables etc., then write the next line under it and so on.

But when a function is called, also move right by one column, writing down the function's name and the actual value of the input arguments for that invocation first and then proceding with the lines in that function.

When you return from the function, move left and write the return value between the two columns.

Also, keep a separate area for the "standard output", where all the printed text goes.

These steps should take you through most of "think like a computer" problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消