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

问题描述 投票:3回答:4

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

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()方法转换为伪代码。

java pseudocode
4个回答
5
投票

PseudoCode可以是你想要的任何东西。由于您或其他人可以理解线条的含义。

你可以把它变成简单的FOR(你的变量值开始)TO(你想要的结束)i ++ -

基本上是让人和你大多数人理解它是For Loop的东西


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.

通常你不需要打扰伪代码。它们真的没有多大用处(除了吹牛的权利......我的意思是,帮助你的同行理解你的代码)并且它们不可执行。


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));

3
投票

这样的事情怎么样:

for each element in list A
    add element to list nonDup

它基本上只是纯文本,任何人都可以阅读。您可以为变量选择更多的发言名称。您也可以选择begin loopend loop来显示循环的范围而不是识别。

© www.soinside.com 2019 - 2024. All rights reserved.