5

最小のforループで次の番号パターンを作成する方法。フィボナッチ、パスカルの三角形など、数字のパターンに数学的に付けられた名前はありますか?複雑ですが、forループを使用して可能である他の興味深いパターンはありますか?

予想されるO/Pパターン:

    1
    22
    333
    4444
    55555
    6666
    777
    88
    9 

// forループは1から5までしか印刷せず、正しく印刷され、逆にすると間違った出力が返されます。

for(int i=1; i<10; i++)
{
for(int j=1,k=10; j<=i&&k>5; j++,k--)   
        {
            if(i<=5)
            System.out.print(i);
            else
            if(i>5)
            System.out.print(i);
        }
            System.out.println();
}
4

5 に答える 5

2

より単純なロジックを使用した別のソリューション:

public static void main(String[] args) {
    int input = 5;

    for (int i = 1; i <= 2 * input - 1; i++) {
        for (int j = 0; j < input - Math.abs((input - i)); j++)
            System.out.print(i);
        System.out.println();
    }
}

入力との差の絶対値に関して要素を出力します。入力を別の値に変更しても、これは引き続き機能します。

于 2012-10-07T18:50:28.667 に答える
2

はい、どうぞ:

for (int i = 1, j = 1 ; i < 10 ; i++, j = (i <= 5) ? (j*10 + 1) : (j/10))
    System.out.println(i * j); 
于 2012-10-07T18:30:48.200 に答える
1

これはループのないソリューションです(再帰的)

public class NumberTriangle {        

    public static void print(int top_, int count_, int length_) {
        int top = top_;
        int count = count_;
        int length = length_;
        count++;        

        if (count <= top){
            length++;           
        } else {
            length--;
        }

        if (length == 0) {
            return;
        }       

        String s = String.format(String.format("%%0%dd", length), 0).replace("0",""+count);     
        System.out.println(s);

        NumberTriangle.print(top, count, length);
    }

    public static void main (String args[]){

        NumberTriangle.print(5,0,0);

    }   

}
于 2012-10-07T19:36:35.897 に答える
0

ソリューション:

IntStream.range(MAX * -1, MAX)
            .forEach(i -> IntStream.rangeClosed(1, MAX - Math.abs(i))
                    .mapToObj(j -> j == MAX - Math.abs(i) ? MAX - Math.abs(i) + "\n" : MAX - Math.abs(i) + " ")
                    .forEach(System.out::print)
            ); 
于 2016-05-05T07:11:36.570 に答える
-1

@RandMate この方法で実行できます: このパターンを印刷するには、パターンを 2 つの部分に分割し、ネストされた for ループの 2 つのセットを使用する必要があります。/出力する最初のネストされたループ 1 22 333 4444 55555 / for(i=1;i<=5;i++)
{ for(j=1;j<=i;j++) { System.out.print(i); } System.out.println(); }

/*this is the second nested loop to print
 6666
 777
 88
 9 */
    p=6;
  for(i=4;i>=1;i--)
  {
   for(j=1;j<=i;j++)
   {
    System.out.print(p);
   }
    p=p+1;
   System.out.println();
  }

  Hope it was helpul.
  ALL THE BEST......enjoy!
于 2012-12-29T19:34:35.590 に答える