简单的伪代码问题
我是伪代码新手,我无法将所有部分放在一起:
这是一个名为 foo 的函数的定义,其输入是两个整数和一个整数数组 a[1] ... a[ n]
。
1 Foo(k,m, a[1],...,a[n])
2 if (k < 1 or m > n or k > m) return 0
3 else return a[k] + Foo(k+1,m,a[1],...,a[n])
假设输入整数为 k=2
和 m=5
,输入数组包含 [5, 6, 2, 3, 4, 8, 2]
。 Foo 返回什么值?使用求和符号,给出 Foo 计算内容的通用公式。
这件事让我头疼。这是我到目前为止所做的:
第 2 行有三个条件语句:
- If k<1 // if 2<1..this is false
- If m>n // if 5 大于数组中值的数量,即7,所以这是 false
- 如果 k>m // 如果 2>5,这是 false
所以这个函数将显示第 3 行。第 3 行表示:
- return
a[k]
,即a [2]
是数组的第二个值,即 6。所以将 6 添加到(2+1, 5, a[1].....,a[n ])
我在那里所做的正确吗?如果是这样,我怎么知道a[n]
是什么?我应该找到那个吗?这一切的最终结果会是什么?
I'm new to psuedocode, and I'm having trouble putting all the pieces together:
Here is the definition of a function named foo whose inputs are two integers and an array of integers a[1] ... a[n]
.
1 Foo(k,m, a[1],...,a[n])
2 if (k < 1 or m > n or k > m) return 0
3 else return a[k] + Foo(k+1,m,a[1],...,a[n])
Suppose that the input integers are k=2
and m=5
and the input array contains [5, 6, 2, 3, 4, 8, 2]
. What value does Foo return? Using summation notation, give a general formula for what Foo computes.
This one is making my head hurt. Here's what I did so far:
Line 2 has three conditional statements:
- If k<1 // if 2<1..this is false
- If m>n // if 5 is greater than the amount of values in the array, which is 7, so this is false
- If k>m // if 2>5, this is false
So this function will display line 3. Line 3 says:
- return
a[k]
which isa[2]
which is the second value of the array, which is 6. So take 6 and add it to(2+1, 5, a[1].....,a[n])
Is what I have done correct up there? If so, how would I know what a[n]
is? Am I supposed to be finding that? What would be the final result of all this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简单答案:该函数返回所有数字 a[k]、a[k+1]、... a[m] 的总和。
到目前为止你所做的都是正确的。 “n”只是一个占位符,表示数组的最后一个元素。因此,如果您的输入数组是
{5,6,2,3,4,8,2}
、n = 7
(因为您有七个元素)和a[n] = 2
。但为什么它返回所有数字 a[k], a[k+1], ... a[m] 的和,你应该自己找出来。继续你的分析吧。 :)
Simple answer: that function returns the sum of all the numbers a[k], a[k+1], ... a[m].
What you're doing is correct so far. The "n" is just a placeholder meaning the last element of the array. So if your input array is
{5,6,2,3,4,8,2}
,n = 7
(cause your have seven elements), anda[n] = 2
.But why it returns the sum of all numbers a[k], a[k+1], ... a[m], you should find out for yourself. Just continue with your analysis. :)
取 6 并将其添加到 Foo(2+1, 5, a[1].....,a[n] )。这是一个递归函数。您必须使用 k=3 和 m=5 再次评估该函数。
Take 6 and add it to Foo(2+1, 5, a[1].....,a[n]). It's a recursive function. You have to evaluate the function again with k=3 and m=5.
我认为您很困惑,因为您的伪代码对我来说看起来像真实的代码。我可能是错的,但我们被教导以不同的方式编写伪代码,使用简单的英语短语。
I think you are confused because your pseudocode looks like real code to me. I may be wrong, but we are taught to write pseudocode differently, using plain English phrases.