Skip to content

Putting it together

Cambridge Pseudocode Lesson 14 2:03 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Cambridge names four standard methods — totalling, counting, linear search, and finding the maximum or minimum — and it is tempting to learn them as four things. 剑桥给四种标准方法起了名字——求和、计数、线性查找、找最大或最小—— 而人很容易把它们当成四样东西来背。
They are one thing. 它们其实是一样东西。
Every one of them sets an answer to a safe starting value, walks the array with a FOR loop that never changes, and does one line to each item. 它们每一个都先把答案设成一个安全的初始值, 再用一个从不改变的 FOR 循环走一遍数组, 然后对每个元素做一行事情。
That middle line is the only part that makes it a method. 那一行中间的代码,才是让它成为某种"方法"的唯一部分。
Totalling puts the item into the accumulator. 求和把元素本身加进累加器。
Counting looks almost the same, but the middle line adds one instead, and only when a rule holds. 计数看起来几乎一样, 但中间那一行加的是 1,而且只在某个条件成立时才加。
That is the whole difference, and it is where marks go: a totalling answer adds the value every time, while a counting answer adds one, sometimes. 这就是全部的区别,也是分数的所在: 求和的答案每一次都加上那个值, 而计数的答案加的是 1,并且只是有时候加。
Linear search uses a flag — a BOOLEAN that records whether you ever saw the thing. 线性查找用一个"标志"——一个布尔值,记录你到底有没有见到那个东西。
It starts as FALSE before the loop. 它在循环之前从 FALSE 开始。
Then the loop walks the array, and the one item that matches flips it to TRUE. 然后循环走一遍数组, 匹配上的那一个元素把它翻成 TRUE。
And here is the part people leave out: the flag is TESTED after the loop, not inside it, because you only know the answer once every item has been checked. 而这里是大家会漏掉的部分: 标志是在循环"之后"被判断的,不是在循环里面, 因为只有在每个元素都检查过之后,你才知道答案。
Finding the largest keeps the best so far and replaces it whenever something beats it. 找最大值的做法是保留"目前为止最好的那个", 一旦有更好的就替换掉。
One detail decides the mark: start Max at the FIRST item of the array, and loop from two. 有一个细节决定了这一分: 把 Max 从数组的"第一个元素"开始,然后从 2 开始循环。
If you start it at nought instead, then on an array of all-negative numbers nought would win — and nought was never in the array. 如果你改成从 0 开始, 那么在一个全是负数的数组上,0 就会胜出—— 而 0 从来就不在那个数组里。
Four things to take with you. 带走四点。
One: every standard method walks the array once. 第一:每一种标准方法都只走一遍数组。
Two: start the total, count or flag BEFORE the loop. 第二:在循环之前就把总和、计数或标志设好。
Three: a search sets a flag, and you test it afterwards. 第三:查找设置一个标志,而你在循环之后判断它。
Four: a maximum starts at the first item, not at nought. 第四:最大值从第一个元素开始,不是从 0。
Do the three tasks — and that is the course. 做完那三道题——这门课就结束了。

Log in or create account

IGCSE, A-Level & AP