Print triangle (Half Pyramid) pattern using Java - java

I have to print a triangle pattern (Half Pyramid) like
1
0 1
1 0 1
0 1 0 1
I tried with this program
class tri{
public static void main(String arg[]){
int i,j,a = 1, b =0, c=0;
for(i=1; i<=4; i++){
for(j=1; j<=i; j++){
System.out.print(a+ " ");
c = a;
a = b;
b = c;
}
System.out.println();
}
}
}
but this prints pattern as shown in image
please if some one could help me editing that code to bring the pattern

The shortest form would be
String str = "";
for (int i = 1; i <= 4; i++) {
str = (i % 2) + " " + str;
System.out.println(str);
}
This will give output as you desired
1
0 1
1 0 1
0 1 0 1

You need to set starting values correctly. Because what you are doing is continuously swapping
Say row two 0 1
last element = 1, (a = 1, b = 0) and on swapping (a = 0, b = 1) for next row first element.
However this is incorrect as it was supposed to start with (a = 1) and not (a = 0) from previous state.
int i,j,a = 1, b =0, c=0;
for (i = 1; i <= 4; i++){
if (i % 2 == 0) {
a = 0;
b = 1;
} else {
a = 1;
b = 0;
}
for(j=1; j<=i; j++) {
System.out.print(a+ " ");
c = a;
a = b;
b = c;
}
System.out.println();
}
You can also switch between 0 and 1 using XOR :
int i, j, a = 1;
for (i = 1; i <= 4; i++){
a = i % 2;
for(j=1; j<=i; j++) {
System.out.print(a+ " ");
a = a ^ 1;
}
System.out.println();
}
However Shorter solution would be :
String str = "";
for (int i = 1; i <= 4; i++) {
str = (i % 2) + " " + str;
System.out.println(str);
}
output :
1
0 1
1 0 1
0 1 0 1

You can use boolean flag for this to check if you are current starting at 1 or 0;
sample:
boolean flag = true;
for(int i=1; i<=4; i++){
for(int j=1; j<=i; j++){
if(flag)
System.out.print("1 ");
else
System.out.print("0 ");
flag = !flag;
}
if((i % 2) == 0)
flag = true;
else
flag = false;
System.out.println();
}
result:
1
0 1
1 0 1
0 1 0 1

int x=1,y=1;
for(int i=1;i<8;i++){
for(int k=0;k<i;k++){
y=(k==0) ? x:y;
System.out.print(y+" ");
y=(y==1) ? 0:1;
}
System.out.println("");
x=(x==1) ? 0:1;
}
output---

write my anwser here, seen #sujithvm solution is more short and efficient.
int sideLength = 4;
for(int i = 0 ; i < sideLength ; i++)
{
for(int j = 0 ; j <= i ; j++)
{
System.out.print((i + j + 1) % 2 + " ");
}
System.out.println();
}

Complete Java program for beginners:
public class PrintPattern15
{
public static void main(String args[])
{
int n = 5;
PrintPattern15 d = new PrintPattern15();
d.printPattern(n);
}
public void printPattern(int noOfRows)
{
for(int i = 1; i <= noOfRows; i++ )
{
printRows(i);
}
}
public void printRows(int startPt)
{
for(int i = startPt ; i >= 1; i--)
{
System.out.print(i%2);
}
System.out.println();
}
}

This Works for me:
public class DrawPattern {
public static void main(String[] args) {
int i, j;
int num = 7;
for (i = 0; i <num; i++) {
for (j = 0; j < i; j++) {
if (isConditionMatch(num, i, j)) {
System.out.print("0");
} else {
System.out.print("1");
}
}
System.out.println();
}
}
private static boolean isConditionMatch(int num, int i, int j) {
return (i%2 != 0 && j%2 !=0 || (i%2 == 0 && j%2==0));
}
}
Output:
1
01
101
0101
10101
010101

Code
public class pra1 {
public static void main(String[] args) {
int space, rows=11, k=0;
// Scanner scan = new Scanner(System.in);
// System.out.print("Enter Number of Rows : ");
// rows = scan.nextInt();
// rowa=6;
for(int i=1; i<=rows; i++)
{
for(space=1; space<=(rows-i); space++)
{
System.out.print(" ");
}
while(k != (2*i-1))
{ // int p=k;
if(k%2==0)
{
System.out.print("1 ");
// System.out.print(" ");
}if(k%2!=0 )
{
System.out.print("0 ");
// System.out.print(" ");
}
else{
System.out.print("");
}
// p--;
k++;
}
k = 0;
System.out.println();
}
}
}
Output
1
1 0 1
1 0 1 0 1
1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

This is how I solved the problem:
int k = 0;
for (i = 1; i <= 4; i++){
k = (i%2 == 0)? 1:0;
for(j=1; j<=i; j++) {
System.out.print(k+ " ");
k = k==0?1:0;
}
System.out.println();
}

Related

Drawing a diamond of numbers in a 2d array Java

I've been solving some coding questions to get myself prepared for a coding interview, and found out a question that seemed kind of puzzling. I solved the question after spending some time on it; however, the code looks hardcoded and has no style. So, I was wondering if I could get some feedbacks on styling the code, or perhaps getting an better idea of approaching the problem.
The question basically asks you to draw a diamond of numbers with a pattern in 2d array.
It gives a coordinate of 'x' and range of x. From the x, the numbers spread one by one until the range. So, there are 4 different inputs, N (the size of an array), X, Y (the coordinate of 'x' as (rows, cols)), and R (range).
If they were given a size of 8, coordinate of (4,5) with a range of 3, the result would be like,
0 0 0 0 3 0 0 0
0 0 0 3 2 3 0 0
0 0 3 2 1 2 3 0
0 3 2 1 x 1 2 3
0 0 3 2 1 2 3 0
0 0 0 3 2 3 0 0
0 0 0 0 3 0 0 0
0 0 0 0 0 0 0 0
And the below is what I have,
int n = sc.nextInt();
char[][] arr = new char[n][n];
int r = sc.nextInt() - 1;
int c = sc.nextInt() - 1;
int range = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = '0';
}
}
arr[r][c] = 'x';
int num = 1;
for (int i = 0; i < range; i++) {
//Cross
if (c-num > -1) {
arr[r][c - num] = (char) (num + '0');
}
if (c+num < n) {
arr[r][c + num] = (char) (num + '0');
}
if (r-num > -1) {
arr[r - num][c] = (char) (num + '0');
}
if (r+num < n) {
arr[r + num][c] = (char) (num + '0');
}
//Diagonal
if (i > 0) {
int sum = num - 1, delta = 1;
while (sum != 0) {
if (r-sum > -1 && c+delta < n) {
arr[r - sum][c + delta] = (char) (num + '0');
}
sum--;
delta++;
}
sum = num - 1; delta = 1;
while (sum != 0) {
if (r+sum < n && c-delta > -1) {
arr[r + sum][c - delta] = (char) (num + '0');
}
sum--;
delta++;
}
sum = num - 1; delta = 1;
while (sum != 0) {
if (r-sum > -1 && c-delta > -1) {
arr[r - sum][c - delta] = (char) (num + '0');
}
sum--;
delta++;
}
sum = num - 1; delta = 1;
while (sum != 0) {
if (r+sum < n && c+delta > -1) {
arr[r + sum][c + delta] = (char) (num + '0');
}
sum--;
delta++;
}
}
num++;
}
I could not figure out any other way to take care of the diagonal numbers other than using four different while-loops. I would appreciate any kind of feedback. Thanks in advance!
You can just loop over the array once, and set the values based on the relative distance of the current location (i, j) to the fixed coordinate (x, j).
Your code could look like this:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// variables
int n = 8;
int x = 4 - 1; // coordinates are one-based
int y = 5 - 1; // coordinates are one-based
int r = 3;
char[][] array = new char[n][n];
// logic
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int dist = Math.abs(x - i) + Math.abs(y - j); // calculate distance
if(dist == 0) { // at x,y
array[i][j] = 'x';
} else if (dist <= r) { // distance to x,y is within range
array[i][j] = (char) (dist + '0');
} else { // distance to x,y is outside of range
array[i][j] = '0';
}
}
}
// dump output
System.out.println(Arrays.deepToString(array)
.replace("], ", "]\n")
.replace("[", "")
.replace("]", "")
.replace(", ", " "));
}
}
Which yields the following output:
0 0 0 0 3 0 0 0
0 0 0 3 2 3 0 0
0 0 3 2 1 2 3 0
0 3 2 1 x 1 2 3
0 0 3 2 1 2 3 0
0 0 0 3 2 3 0 0
0 0 0 0 3 0 0 0
0 0 0 0 0 0 0 0
If you want to be even more concise, you can replace the branched if… else if… else statement with ternary operators:
array[i][j] = dist == 0 ? 'x' : dist <= r ? (char) (dist + '0') : '0';
Here's a fairly compact method. On each iteration i we fill a single-character wide i+1 by i+1 diamond-shaped ring, centered on (row, col), with value i. To avoid filling the interior of the diamond we check that the manhattan distance to (row, col) is equal to i - this is only true for cells on the boundary of the diamond.
static char[][] buildDiamond(int n, int row, int col, int range)
{
char[][] arr = new char[n][n];
for(char[] a : arr) Arrays.fill(a, '0');
arr[row][col] = 'x';
for(int i=1; i<=range; i++)
for(int j=0; j<=i; j++)
for(int k=0; k<=i; k++)
if(Math.abs(k-j) + Math.abs(k+j-i) == i)
arr[row+k-j][col+k+j-i] += i;
return arr;
}
Test:
public static void main(String[] args)
{
for(char[] a : buildDiamond(7, 3, 3, 3))
System.out.println(new String(a).replaceAll(".", "$0 "));
}
Output:
0 0 0 3 0 0 0
0 0 3 2 3 0 0
0 3 2 1 2 3 0
3 2 1 x 1 2 3
0 3 2 1 2 3 0
0 0 3 2 3 0 0
0 0 0 3 0 0 0
You can try using floodfill, although depending on your level it might be a bit far.
https://en.wikipedia.org/wiki/Flood_fill
EDIT: Robby Cornelissen's code looks much cleaner and simpler than mine so you should probably check out his. However, floodfill is a pretty important concept for later on so might as well check it out.
The article is pretty long, but the GIF in the article is the most important part.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class test {
public static void main(String[] args) throws IOException {
//Get inputs (I used BufferedReader, Scanner works fine as well)
//My inputs are formatted as 'N X Y R' (ex. '8 4 5 3')
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int N = Integer.parseInt(st.nextToken());
int R = Integer.parseInt(st.nextToken()) - 1;
int C = Integer.parseInt(st.nextToken()) - 1;
int range = Integer.parseInt(st.nextToken());
char[][] arr = new char[N][N];
//Make everything in array '0'
for (int i = 0; i < N; i++) {
Arrays.fill(arr[i], '0');
}
//Floodfill using BFS
//FYI: this BFS is iterative, not recursive
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{0, R, C});
while (!q.isEmpty()) {
int[] current = q.remove();
if (arr[current[1]][current[2]] == '0' && current[0] <= range) {
arr[current[1]][current[2]] = (current[0]+"").charAt(0);
if(current[1]+1 < N) q.add(new int[]{current[0]+1, current[1]+1, current[2]});
if(current[1]-1>= 0) q.add(new int[]{current[0]+1, current[1]-1, current[2]});
if(current[2]+1 < N) q.add(new int[]{current[0]+1, current[1], current[2]+1});
if(current[2]-1>= 0) q.add(new int[]{current[0]+1, current[1], current[2]-1});
}
}
arr[R][C] = 'x';
//Print out the final grid
for (int i = 0; i < N; i++) {
for (int j = 0; j< N; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

Java Multidimensional Array Outprint

I dont understand, why these numbers are printed out. Shouldn't it just out print 3 2 1? Instead, it prints:
3
0
0
0
2
0
0
0
1
Thank you for your help :)
public static void main(String[] args) {
int i, j, n = 3;
int[][] polje = new int[n][n];
polje[0][0] = 3;
polje[1][1] = 2;
polje[2][2] = 1;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(polje[i][j] + " ");
System.out.println();
}
}
}
you have set likewise,
3 0 0
0 2 0
0 0 1
so obviously you get, 3 0 0 0 2 0 0 0 1
if you want to print only 3 2 1 then made this changes only,
if(i == j){
System.out.print(polje[i][j] + " ");
System.out.println();
}

Conway's Game of Life New Values

The question revolves around Conway's Game of Life and how to implement all the rules at the same time for the new generations. The game follows three rules for new generations, which are: a dead cell with exactly three live neighbors becomes live, a live cell with exactly one live neighbor becomes dead, and a live cell with more than three live neighbors becomes dead. The original generation is random. I think my problem, which is that my new generations are implementing the rules one at a time instead of all at once, is in this method:
public static int[][] nextgeneration(int[][] lastgen){
int[][] nextgen = new int[lastgen.length][lastgen[0].length];
for(int i = 0; i < lastgen.length; i++){
for(int j = 0; j < lastgen[i].length; j++){
if(aliveneighbors(lastgen, i, j) == 3){
nextgen[i][j] = 1;
}
else if(aliveneighbors(lastgen, i, j) == 1){
nextgen[i][j] = 0;
}
else if(aliveneighbors(lastgen, i, j) > 3){
nextgen[i][j] = 0;
}
else nextgen[i][j] = lastgen[i][j];
}
}
return nextgen;
Here's my full code just in case the problem was not in that method:
import java.util.Random;
public class Life {
public static int[][] origin(int a, int b) {
int[][] randomMatrix = new int [a][b];
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
Random random = new Random();
int abc = random.nextInt(2);
randomMatrix[i][j] = abc;
}
}
return randomMatrix;
}
public static void print(int[][] a) {
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a.length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public static void show(int[][] b) {
int N = b.length;
StdDraw.setXscale(0, N-1);
StdDraw.setYscale(0, N-1);
for(int i = 0; i < b.length; i++){
for(int j = 0; j < b.length; j++){
if(b[i][j] == 1){
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledSquare(j, N-i-1, .5);
}
else if(b[i][j] == 0){
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledSquare((double)j, (double)-i, .5);
}
}
}
}
public static int[][] nextgeneration(int[][] lastgen){
int[][] nextgen = new int[lastgen.length][lastgen[0].length];
for(int i = 0; i < lastgen.length; i++){
for(int j = 0; j < lastgen[i].length; j++){
if(aliveneighbors(lastgen, i, j) == 3){
nextgen[i][j] = 1;
}
else if(aliveneighbors(lastgen, i, j) == 1){
nextgen[i][j] = 0;
}
else if(aliveneighbors(lastgen, i, j) > 3){
nextgen[i][j] = 0;
}
else nextgen[i][j] = lastgen[i][j];
}
}
return nextgen;
}
public static int aliveneighbors(int[][] board, int x, int y){
int count = 0;
int up;
int down;
int left;
int right;
{
if(x > 0)
up = x - 1;
else
up = board.length - 1;
if(x < (board.length - 1))
down = x + 1;
else
down = 0;
if(y > 0)
left = y - 1;
else
left = board[x].length - 1;
if(y < (board[x].length - 1))
right = y + 1;
else
right = 0;
//Count the live neighbors
if(board[up][left] == 1)
count++;
if(board[up][y] == 1)
count++;
if(board[up][right] == 1)
count++;
if(board[x][left] == 1)
count++;
if(board[x][right] == 1)
count++;
if(board[down][left] == 1)
count++;
if(board[down][y] == 1)
count++;
if(board[down][right] == 1)
count++;
return count;
}
}
public static void main(String[] args) {
int[][] b = origin(5, 5);
int gens = 5;
for (int i = 0; i < gens; i++) {
System.out.println();
int nextboard[][] = nextgeneration(b);
b = nextboard; //I feel like this could be a problem as well
System.out.println("Generation " + i + ":");
print(nextgeneration(b));
show(nextgeneration(b)); //This line of code seems useless
//print(b); This one also seems useless and makes output confusing
show(b);
}
}
}
Here is what my output is:
Generation 0:
0 1 1 0 0
0 1 1 0 0
0 0 0 1 1
1 1 0 1 1
1 0 0 0 0
Generation 1:
1 0 1 0 0
1 1 0 0 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Generation 2:
1 0 1 0 1
1 1 0 0 0
1 0 0 0 0
0 0 1 1 0
0 0 0 1 1
Generation 3:
0 0 1 0 0
0 0 0 0 0
1 0 1 0 1
0 0 1 1 0
1 1 0 0 0
Generation 4:
0 1 0 0 0
0 1 0 1 0
0 1 1 0 1
0 0 1 1 0
0 1 0 1 0
I expect something like this:
Generation 0:
0 1 1 0 0
0 1 1 0 0
0 0 0 1 1
1 1 0 1 1
1 0 0 0 0
Generation 1:
0 1 1 0 0
0 1 0 0 0
1 0 0 0 1
1 1 1 1 1
1 1 0 0 0
Generation 2:
0 1 1 0 0
1 1 1 0 0
1 0 0 0 1
0 0 1 1 1
1 0 0 1 0
Also on my animation of the game the alive cells stay alive in the animation, which should not be happening. That's not my main problem, but if you know how to fix that it would also be helpful.
Your output looks fine to me. Pay attention, that you actually do "wrap-around" of the borders, so this
Generation 0:
0 1 1 0 0
has this as a upper border:
1 0 0 0 0
and a left border:
0
0
1
1
0
For calculations it looks like:
0 1 0 0 0 0
0 0 1 1 0 0
0 0 1 1 0 0
So this output:
Generation 1:
1 0 1 0 0
1 1 0 0 0
Is correct for the wrap-around.
From the expected result, however, it looks you want to treat it as a actual border. I mean:
010
000
with x=1, y=0, has only 5 neighbours.
In that case you need something like this:
public static int aliveneighbors(int[][] board, int x, int y){
int width = board.length;
int height = board[0].length;
int count = 0;
boolean isNotLower = (y-1) >= 0;
boolean isNotUpper = (y+1) < height;
if (x-1 >= 0) {
if( isNotLower && (board[x-1][y-1] == 1) )
count++;
if(board[x-1][y] == 1)
count++;
if(isNotUpper && (board[x-1][y+1] == 1) )
count++;
}
if (x+1 < width) {
if( isNotLower && (board[x+1][y-1] == 1) )
count++;
if(board[x+1][y] == 1)
count++;
if( isNotUpper && (board[x+1][y+1] == 1) )
count++;
}
if( isNotUpper && (board[x][y+1] == 1) )
count++;
if(isNotLower && (board[x][y-1] == 1) )
count++;
return count;
}

DFS in adjacency matrix

I am having trouble with my DFS it is giving out the wrong traversal. I also need to get the first encounter of the DFS and save it so it can be printed for later. The first encounter would be 1 2 6 7 4 3 5 8
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
public class DFS {
private Stack<Integer> stack;
String line;
int row = 0;
static int size = 0;
public DFS(){
stack = new Stack<Integer>();
}
public void dfs(int adjMatrix[][], int vert)
{
int number_of_nodes = adjMatrix[vert].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = vert;
int i = vert;
System.out.println(element + "\t");
visited[vert] = 1;
stack.push(vert);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjMatrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + "\t");
continue;
}
i++;
}
stack.pop();
}
}
public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {
int[][] matrix = null;
BufferedReader buffer = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
int size = 0;
while ((line = buffer.readLine()) != null) {
String[] vals = line.trim().split(" ");
// Lazy instantiation.
if (matrix == null) {
size = vals.length;
matrix = new int[size+1][size+1];
}
for (int col = 0; col < size; col++) {
matrix[row][col] = Integer.parseInt(vals[col]);
}
row++;
}
return matrix;
}
public static void printMatrix(int[][] matrix) {
String str = "";
int size = matrix.length;
if (matrix != null) {
for (int row = 0; row < size; row++) {
str += " ";
for (int col = 0; col < size; col++) {
str += String.format("%2d", matrix[row][col]);
if (col < size - 1) {
str += " ";
}
}
if (row < size - 1) {
str += "\n";
for (int col = 0; col < size; col++) {
for (int i = 0; i < 4; i++) {
// str += " ";
}
if (col < size - 1) {
//str += "+";
}
}
str += "\n";
} else {
str += "\n";
}
}
}
System.out.println(str);
}
public static void main(String[] args)
{
int[][] matrix = null;
try {
matrix = create2DIntMatrixFromFile("sample.txt");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("The DFS Traversal for the graph is given by ");
DFS dfs = new DFS();
dfs.dfs(matrix, size);
System.out.println(" ");
printMatrix(matrix);
}
}
The output for this is
The DFS Traversal for the graph is given by
0
1 5 4 6 2 3 7
0 1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0 0
0 0 0 1 0 0 1 0 0
0 0 1 0 0 0 0 1 0
1 0 0 0 0 1 0 0 0
1 1 0 0 1 0 0 0 0
0 1 1 0 0 0 0 1 0
0 0 0 1 0 0 1 0 0
0 0 0 0 0 0 0 0 0
The traversal is suppose to be
1 2 6 5 7 3 4 8
Thanks in advance for your help!

How to print numbers in a triangle pattern?

Below is the pattern I would like to print in the console:
1
2 0 2
3 0 0 0 3
And below is the code I have right now. Each number should have 5 spaces between each other.
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
System.out.println("Input the number of lines you want to print.");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int[] row = new int[0];
for(int i=0 ; i < n ; i++){
row = nextRow(row);
for(int j=0;j < n-i;j++){
//Padding For Triangle
System.out.print(" ");
}
//Output the values
for(int j=0 ; j < row.length ; j++){
System.out.print(row[j]+" ");
}
//Start New Line
System.out.println();
}
}
/*Find Values Of Next Row*/
public static int[] nextRow(int row[]){
int nextRow[] = new int [row.length+1];
nextRow[0] = row.length+1;
nextRow[nextRow.length-1] =row.length+1;
for(int i=1 ; i < nextRow.length-1 ; i++){
nextRow[i] = 0;
}
return nextRow;
}
}
Can anyone help me with this?
Here is some modified code. Its not complete and still something need to update your code to get desired result. That part I am leaving it for you. I also left hint in code so that you could modify.
1.
// Padding For Triangle
System.out.print(" "); // 6 white space
2.
System.out.print(row[k]);
System.out.print(" "); // 5 white space
3.
/* Find Values Of Next Row */
#SuppressWarnings("null")
public static int[] nextRow(int row[]) {
int nextRow[] = null;
if (row.length == 0) {
nextRow = new int[1];
nextRow[0] = 1;
} else {
// count++; // Hint
nextRow = new int[row.length + 2];
for (int i = 0; i < nextRow.length; i++) {
if ((i == 0 || i == nextRow.length - 1)) {
nextRow[i] = nextRow.length - 2;
// nextRow[i] = count;
} else {
nextRow[i] = 0;
}
}
}
return nextRow;
}
If you have any questions, just ask. Good Luck.
You first have to identify the pattern that the output expects, which in your case is:
Row0, columns 1
Row1, columns 3
Row2, columns 5
Row3, columns 7
which is, rowNum*2+1
Based, on this, I modified your code and here is the working solution:
import java.util.Scanner;
public class Triangle{
public static void main(String args[]) {
System.out.println("Input the number of lines you want to print.");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int[] row = null;
for(int i=0 ; i < n ; i++){
row = nextRow(i);
for(int j=0;j < n-i;j++){
//Padding For Triangle
System.out.print(" ");
}
//Output the values
for(int j=0 ; j < row.length ; j++){
System.out.print(row[j]+" ");
}
//Start New Line
System.out.println();
}
}
/*Find Values Of Next Row*/
public static int[] nextRow(int rowNum){
int nextRow[] = new int [rowNum*2+1];
nextRow[0] = rowNum+1;//-rowNum/2;
nextRow[nextRow.length-1] = nextRow[0];
for(int i=1 ; i < nextRow.length-1 ; i++){
nextRow[i] = 0;
}
return nextRow;
}
}
And here is some output:
2:
1
2 0 2
5:
1
2 0 2
3 0 0 0 3
4 0 0 0 0 0 4
5 0 0 0 0 0 0 0 5
10:
1
2 0 2
3 0 0 0 3
4 0 0 0 0 0 4
5 0 0 0 0 0 0 0 5
6 0 0 0 0 0 0 0 0 0 6
7 0 0 0 0 0 0 0 0 0 0 0 7
8 0 0 0 0 0 0 0 0 0 0 0 0 0 8
9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9
10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10
i saw your code, i think that we can do this, follow is my modified code:
public class Triangle {
public static void main(String args[]) {
System.out.println("Input the number of lines you want to print.");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int [] row = new int[0];
for (int i = 0; i < n; i++) {
row = nextRow(row);
for (int j = 0; j < n - i; j++) {
// Padding For Triangle
System.out.print(" ");
}
// Output the values
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " ");
}
// Start New Line
System.out.println();
}
}
/* set space between each other. */
public static String printSpace(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += " ";// 5 space
}
return result;
}
/* Find Values Of Next Row */
public static int [] nextRow(int row[]) {
int nextRow[] = new int[row.length + 1];
nextRow[0] = row.length + 1;
nextRow[nextRow.length - 1] = row.length + 1;
for (int i = 1; i < nextRow.length - 1; i++) {
nextRow[i] = 0;
}
return nextRow;
}
}
may be this is answer what you want.
Look up the arithmetic sequence for printing out the zeros, the rest should be trivial.

Categories

Resources