【问题标题】:Did I convert this pseudo code correctly?我是否正确转换了这个伪代码?
【发布时间】:2017-11-12 20:54:41
【问题描述】:

我只是想在提交我的作品之前确保我在下面编写的代码被正确翻译。该方法确实有效,但我觉得我可能写错了。

伪代码:

assign i the value 0

WHILE i is less than the length of the array minus 1

let bubbleI be the bubble at index i in the bubbles array

assign j the value i + 1

WHILE bubbleI is not popped AND j is less than the length of the bubbles 
array

let bubbleJ be the bubble at index j in the bubbles array
IF bubbleJ is not popped AND bubbleI is touching bubbleJ
pop both bubbleI and bubbleJ

END IF

increment j by 1

END WHILE

increment i by 1

END WHILE

我的代码:

private void popAll() {

    int i = 0;

    while (i < bubbles.length - 1){

       bubbles[i] = bubbles[i];
       int j = i + 1;

        while (bubbles[i].isPopped() == false && j < bubbles.length){

            bubbles[j] = bubbles[j];

            if (bubbles[j].isPopped() == false && bubbles[i].isTouching(bubbles[j]) == true){

                bubbles[i].pop();
                bubbles[j].pop();             
            }
            j++;          
       }           
       i++;
    } 
} 

【问题讨论】:

    标签: java loops methods parameters


    【解决方案1】:

    我认为“让bubbleI成为bubbles数组中索引i处的泡泡”应该变成Bubble bubbleI = bubbles[i];,而不是实际上没有做任何事情的那个赋值。

    在 if 语句中比较 truefalse 也很不寻常 - foo == truefoo 完全相同,foo == false!foo 完全相同。

    最后,带有初始化和增量的 while 循环正是 for 语句的用途,所以我会这样写:

    private void popAll() {
        for (int i = 0; i < bubbles.length - 1; i++) {
           Bubble bubbleI = bubbles[i];
    
           for (int j = i + 1; !bubbleI.isPopped() && j < bubbles.length; j++) {
                Bubble bubbleJ = bubbles[j];
    
                if (!bubbleJ.isPopped() && bubbleI.isTouching(bubbleJ)) {
                    bubbleI.pop();
                    bubbleJ.pop();             
                }
            }           
        } 
    }
    

    或者,您可以保留 while 循环。目前尚不清楚您是希望按字面意思翻译伪代码,还是尝试编写惯用代码。

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多