How to print the following sequence satisfying these conditions

It was an interview question. I had to print the following using Java:

9
9 8 9
9 8 7 8 9
9 8 7 6 7 8 9
. . .
. . .

During the interview, I wrote the embarrassing part of the code, but nonetheless worked using an external loop, two internal ones (one for the decrementing sequence and one for the incremental sequence!) And tons of variables. One variable was the length of each line.

The interviewer asked me to rewrite it using

  • only one external and one internal cycle

  • without variable string length.

Note. After looking at the answers, I think that the interviewer did not really mean the second condition. Perhaps he just wanted me to simplify my code, and the second moment just burst out of his mouth.

So, later home, I came to this:

int rowCnt = 5;

for(int i = 1; i <= rowCnt; i++)
{
    int val = 9;
    int delta = -1;
    int rowLen = i * 2 - 1;

    for(int j = 1; j <= rowLen; j++)
    {
        System.out.print(val + " ");

        val += delta;

        if(j >= rowLen / 2) delta = 1;
    }

    System.out.println();
}

. delta, , . .

- . , .

?

, , , .

+5
5

, " ".

, :

countDownInMiddle("", 9, "");

private static void countDownInMiddle(String start, int n, String end) {
    if (n < 0) {
        return;
    }
    System.out.println(start + n + end);
    countDownInMiddle(start + n, n - 1, n + end);
}
+2

:

    int start = 9;
    for (int i = 0; i <= start; i++) {
        StringBuilder sb = new StringBuilder((start - i) + " ");
        for (int j = start - i; j < start; j++) {
            sb.insert(0, (j + 1) + " ");
            sb.append((j + 1) + " ");
        }
        System.out.println(sb.toString());
    }
+2

PHP, Java:

$rowCount = 10;
$startNum = 9;

for ($idx =0; $idx <$rowCount; $idx ++) {

    for ($jdx=0; $jdx < (2*$idx +1); $jdx++) {

        if ($idx < $jdx)
            echo $startNum -(2*$idx) + $jdx.' ';
        else
            echo $startNum - $jdx.' ';
    }
    echo '<br/>';
}
+1
public class Pyramid {
    public static void main(String[] args) {
        int start = 9;
        String left = "";
        String right = "";
        for (int i=start; i>=0; i--) {
            System.out.println(left+i+right);
            left = left+i;
            right = i+right;
        }
    }
}

:

9
989
98789
9876789
987656789
98765456789
9876543456789
987654323456789
98765432123456789
9876543210123456789

This iterative solution is equivalent to a recursive solution. I would prefer to use recursion iteration, since the extra stack memory needed by the recursive solution can be huge when the number of lines increases.

0
source

My non-recursive solution:

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

All Articles