这个Java for循环在伪代码中应该是什么样子的?

3

我该如何将这段代码转换为伪代码?

ArrayList<Integer> check = new ArrayList<Integer>();
ArrayList<Integer> dup = new ArrayList <Integer> ();
ArrayList<Integer> nonDup = new ArrayList <Integer> ();

for (int i : listA) {
    nonDup.add(i);
}
for (int i : listB) {
    nonDup.add(i);
}
for (int i : listA) {
    check.add(i);
}
for (int i : listB) {
    if (check.contains(i)) {
        dup.add(i);
        nonDup.removeAll(duplicates);                   
    }
}

我不知道如何将for循环、add()、contains()和removeAll()方法转换成伪代码。


1
伪代码只是用普通英语编写的代码。因此,只需编写函数执行的操作即可。例如,“从nonDup中删除所有重复项”。 - ADTC
通常情况下,我们从伪代码转换为实际代码... - DeathByTensors
2
@Drew 一定是作业:)) - ADTC
是的,我已经提前完成了代码,因为我觉得编码很有趣,但伪代码不那么有趣。我相信将来我会学会适应的。 - user3116280
1
@user3116280 看看我的回答 :) 通常情况下,你不需要去烦恼伪代码。它们真的没有太多用处(除了炫耀权利,我是说,帮助你的同行理解你的代码),而且它们也不能被执行。 - ADTC
4个回答

5

PseudoCode可以是你想要的任何东西。因为你或其他人可以理解这些代码的含义。

你可以将它简化为FOR (你的变量值开始) TO (你所需的结束值) i++ -

基本上,这个代码片段可以让人们和你更容易理解它是一个 For Loop(for循环)。


1
好的,我现在明白如何将函数转换为伪代码了。但是对于for (int i : listA) {这段代码会将整数i转换为数组listA中的每个数字你有什么建议吗?谢谢 - user3116280
1
没问题 :) 只是想帮忙。如果您愿意,可以接受我的答案,这样其他可能有同样问题的用户就会更容易找到它。 - João Cunha

4

例如:

getNonDup(listA, listB):
    nonDup = listA + listB
    dup    = an empty list
    for each object i in listB do:
        if listA contains i do:
            add i to dup
            remove i from nonDup
    return nonDup

(我的伪代码风格与Python有些相似...)

在Java中,要使值唯一,你可以将所有值放入一个集合中:

Set<Integer> nonDup = new HashSet<Integer>(listA.addAll(listB));

4

这只是“纯英语”:

Initialize "check" as an empty (array-backed) list of integers.
Initialize "dup" as an empty (array-backed) list of integers.
Initialize "nonDup" as an empty (array-backed) list of integers.

For each integer in listA:
    Add the integer to "nonDup".
End of loop.

For each integer in listB:
    Add the integer to "nonDup".
End of loop.

For each integer in listA:
    Add the integer to "check".
End of loop.

For each integer in listB:
    If "check" contains the integer:
        Add the integer to "dup".
        Remove all integers in "dup" from "nonDup".
    End of if.
End of loop.

通常情况下,您不需要关注伪代码。它们确实没有太多用处(除了可以炫耀一下……我是说,帮助同行理解你的代码),而且它们不能被执行。


3
像这样怎么样:
for each element in list A
    add element to list nonDup

这基本上是普通文本,任何人都可以阅读。您可以为变量选择更具表现力的名称。您也可以选择使用 begin loopend loop 来显示循环的范围,而不是使用缩进。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接