TheAtlasTheory
TheAtlasTheory

Reputation: 13

Basic Java Array - Print a "Pyramid" of Increasing Values

I'm studying for a test in a programming class, and I can't seem to get solve this particular practice problem:

Write a code that constructs an array called pyramid that outputs the following array:

0 0 0 0 0 0 0 0 
0 1 1 1 1 1 1 1
0 1 2 2 2 2 2 2 
0 1 2 3 3 3 3 3 
0 1 2 3 4 4 4 4 
0 1 2 3 4 4 5 5 
0 1 2 3 4 4 5 5 

As you can see, it should be fairly straightforward; assign the row and column number corresponding to that element on their respective index - yet I can't, for the life of me, figure this out.

Here's what I've got so far:

public static void main(String[] args)
{
    int[][] list = new int[7][7];
    pyramid(list);
    for(int row = 0; row < list.length; row++)
    {
        for (int column = 0;column < list[row].length; column++)
        {
            System.out.printf("%2d ", list[row][column]);
        }
        System.out.println();
    }
}
static void pyramid(int[][] input)
{
    for(int r = 0; r < input.length; r++)
    {
        for(int c = 0; c < input[r].length; c++)
        {
            //what should go in here? 
        }
    }
}

placing

input[c][r] = r;

in the body of the second loop gets me ever closer to the desired output - though it still falls short.

Output:

 0  1  2  3  4  5  6 
 0  1  2  3  4  5  6 
 0  1  2  3  4  5  6 
 0  1  2  3  4  5  6 
 0  1  2  3  4  5  6 
 0  1  2  3  4  5  6 
 0  1  2  3  4  5  6  
 //arg!

What next? What should I do from here?

Any help is greatly appreciated!

Upvotes: 1

Views: 1246

Answers (2)

sprinter
sprinter

Reputation: 27966

The value in each cell is the smaller of the row and column number:

input[c][r] = Math.min(c, r);

For your interest, an alternate approach is to write each value directly into the appropriate place in the array:

for (int i = 0; i < pyramid.length; i++) {
    for (int j = i; j < pyramid.length; j++) {
        pyramid[i][j] = i;
        pyramid[j][i] = i;
    }
}

Upvotes: 6

Grekz
Grekz

Reputation: 1591

public class Pyramid {
    public static void main(String[] args) {
        int[][] list= {
                {0,  1,  2,  3,  4,  5,  6},
                {0,  1,  2,  3,  4,  5,  6},
                {0,  1,  2,  3,  4,  5,  6},
                {0,  1,  2,  3,  4,  5,  6},
                {0,  1,  2,  3,  4,  5,  6},
                {0,  1,  2,  3,  4,  5,  6},
                {0,  1,  2,  3,  4,  5,  6}};
        pyramid(list);
    }
    static void pyramid(int[][] arg){
        for (int i = 0; i < arg.length; i++) {
            for (int j = 0; j < arg[i].length; j++) {
                System.out.print(Math.min(i, j));
            }
            System.out.println();
        }
    }

}

Upvotes: 0

Related Questions