前后循环成一行


11

我认为这是一个有趣的问题。我们可以以一种方式循环,但可以在同一行中向后循环吗?让我解释一下我的意思。这是一个示例代码:

for(int i = 0; i < 5; i++) { // we all know the output will be 0,1,2,3,4

我在寻找是否有任何解决方法,以便可以打印上述声明0,1,2,3,4,3,2,1,0

java 

Answers:


14
for (int i = -4; i <= 4; i++) {
    System.out.println(4 - Math.abs(i));
}

2

您也可以查看以下内容:

int a=1;
for(int i=0 ; i>-1 ; i+=a){
if (i==4)a=-a;
System.out.print(i +" ");
}

输出:

0 1 2 3 4 3 2 1 0

2

OP要求的所有逻辑都在一行中

  for(int i=0, d=1; i>=0 ;d=(i==4?-1:d), i+=d){
    System.out.print(i +" ");
  }

1
这个答案很棒,比其余的(+1)更通用-您可以在循环条件中将min和max之类的函数参数替换为0和4,然后再替换为通用的!👏
亚历大号

1

借助一点算术,您可以:

for (int i = 0; i < 9; i++) {
    System.out.println(4 - Math.abs(4 - i));
}

但是简单地使用两个for循环就更容易读写。



1
for(int i = 0; i < 9; i++){
     int j = i;
     if(i >= 5)
         j = 8 - i;
     System.out.println(j);
}

1

这样做没有真正简单的方法,但是通过一些修改,您最终可能会遇到一个可以改变方向的循环:

for(int i = 0, direction = 1; 0 <= i && i < 5; direction = (i == 5-1) ? -direction : direction, i += direction)
    System.out.println(i);

0

在Java中(通用,不必介于0和N之间):

public static void forwardAndBack(int min, int max) {
  for (int i = 0; i < (max - min + 0.5) * 2; i++) {
    System.out.println((min + i) > max ? max - (min + i - max) : min + i);
  }
}
forwardAndBack(1, 4);

在JavaScipt中(只是为了您可以观看实时演示):

function forwardAndBack(min, max) {
  for (let i = 0; i < (max - min + 0.5) * 2; i++) {
    console.log(min + i > max ? max - (min + i - max) : min + i);
  }
}
forwardAndBack(1, 4);
.as-console-wrapper { max-height: 100% !important; top: 0; }


0

一个通用的衬板,所有逻辑都在for表达式中。

int start = 0;
int max = 4;
  for(int n= start, asc = start, desc = max * 2 - start;  
       (n = asc < desc ? asc: desc) >= start ; 
       asc++, desc--)
       {
          System.out.print(n+ " ");
       }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.