继续嵌套循环的部分,如果一个循环的条件在开始时不满足。

huangapple go评论63阅读模式
英文:

Continue parts of nested loop if condition of one loop is not met at exactly the beginning

问题

我有一个恰好有3层嵌套的循环。如果输入恰好为0,则应继续执行其他for循环,所以普通的嵌套循环行不通。

我尝试想出解决方法,但我不知道如何使它工作。任何类型的解决方案都可以。

我有3个输入,它们是某种“乘数”。如果值为0,执行仍然应该继续。

示例:

int coni=2, conj=-2, conk=0;
//中间值,用于指示是否为负数
//从起始值计算得出,但我会摆脱这些代码
int ti=1, tj=-1, tk=0;

for(int i=0; i<(int)Math.abs(coni); i++){
    for(int j=0; i<(int)Math.abs(conj); j++){
        for(int k=0; i<(int)Math.abs(conk); k++){
            //永远不会被执行
            function(i*ti, j*tj, k*tk);
        }
    }
}

我想要发生的事情:

function(0, 0, 0);
function(0, -1, 0);
function(1, 0, 0);
function(1, -1, 0);
英文:

I have exactly 3-level nested loop. If an input is exactly 0, the execution of other for loops should continue so normal nested loop won't work
I tried thinking of a workaround but i have no idea how would i make it work. Any kind of solution is welcome

I have 3 inputs that are some kind of "multipliers". If the value is 0, the execution should still continue.

Example:

int coni=2, conj=-2, conk=0;
//intermediate values that tell should it be negative or positive
//calculated from the beginning values, but ill get rid of the code
int ti=1,tj=-1,tk=0;

for(int i=0;i&lt;(int)Math.abs(coni);i++){
    for(int j=0;i&lt;(int)Math.abs(conj);j++){
        for(int k=0;i&lt;(int)Math.abs(conk);k++){
            //will never get executed
            function(i*ti,j*tj,k*tk);
        }
    }
}

What i want to happen:

function(0,0,0);
function(0,-1,0);
function(1,0,0);
function(1,-1,0);

答案1

得分: 1

在你的 for loop 中,将 &lt; 替换为 &lt;= 将帮助你实现你想要的效果。

for(int i=0;i<=(int)Math.abs(coni);i++){
    for(int j=0;i<=(int)Math.abs(conj);j++){
        for(int k=0;i<=(int)Math.abs(conk);k++){
            //永远不会被执行
            function(i*ti,j*tj,k*tk);
        }
    }
}

这将会执行:

function(0,0,0)
英文:

Setting &lt;= instead of &lt; in your for loop will help you achieve what you want.

for(int i=0;i&lt;=(int)Math.abs(coni);i++){
    for(int j=0;i&lt;=(int)Math.abs(conj);j++){
        for(int k=0;i&lt;=(int)Math.abs(conk);k++){
            //will never get executed
            function(i*ti,j*tj,k*tk);
        }
    }
}

This will execute

function(0,0,0)

huangapple
  • 本文由 发表于 2020年10月20日 23:41:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64448631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定