Two dimensional Array Java - java

I have a 2d array:
0 0 0 0 0 0
0 0 0 0 0 0
1 1 0 0 0 0
0 0 0 0 1 1
1 0 1 1 0 0
1 0 0 0 1 1
All blocks take up two adjacent cells either (cells have value =1) horizontally or vertically. Now, I drop all blocks and I get a new array:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 1 0 0 0 0
1 0 0 0 1 1
1 0 1 1 1 1
Here is my Source Code:
package IOJava;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ReadFile {
public static int rows, cols;
public static int[][] cells;
public static void main(String[] args) throws IOException {
try {
File file = new File("input.txt");
Scanner input = new Scanner(file);
int rows = 0; // i chinh la so hang
int cols = 0;
int[][] newArr = new int[100][100];
ArrayList string = new ArrayList();
while (input.hasNextLine()) {
String line = input.nextLine();
line = line.trim();
String[] arrLine = line.split(" ");
cols = arrLine.length;
for (int i = 0; i < arrLine.length; i++) {
newArr[rows][i] = Integer.parseInt(arrLine[i]);
}
rows++;
}
int[][] newCopyArr = twoDimensionalArrayClone(newArr);
for (int i = 0; i <rows; i++) {
for (int j = 0; j <cols; j++) {
if(i+1<rows && j+1<cols){
if(newCopyArr[i][j]==1 && newCopyArr[i][j+1]==1){
if(newCopyArr[i+1][j]==0 && newCopyArr[i+1][j+1]==0){
newCopyArr[i][j]=0 ; newCopyArr[i][j+1]=0;
newCopyArr[i+1][j]=1 ; newCopyArr[i+1][j+1]=1;
}
}
if(newCopyArr[i][j]==1 && newCopyArr[i+1][j]==1){
if(i+2<rows){
if(newCopyArr[i+2][j]==0){
newCopyArr[i][j]=0;
newCopyArr[i+2][j]=1;
}
}
}
// if(newCopyArr[i][j]==1 && newCopyArr[i+1][j]==1 && newCopyArr[i+1][j]==1){
//
// }
//
}
}
}
//sysout
for (int k = 0; k < rows; k++) {
for (int h = 0; h < cols; h++) {
System.out.print(" " + newCopyArr[k][h]);
}
System.out.println();
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static int[][] twoDimensionalArrayClone(int[][] a) {
int[][] b = new int[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
return b;
}
}
But, when I try to execute this code with other 2d array[], it is not right.
Example:
0 0 0 0 0 0
0 1 1 0 0 0
1 1 0 0 0 0
0 0 0 0 1 1
1 0 1 1 0 0
1 0 0 0 1 1

Related

ArrayList of 2 dimensional array int

I'm trying to do an ArrayList of 2 dimensional arrays.
It is the same 2 dim array that I'm adding to the ArrayList, but it has different values each time.
The problem is : when I add the array to the list, it's auto-updating the other versions of the array in the list.
I tried to clone/copy the array just before adding it to the List, but it has no effect.
import java.util.*;
public class Test {
static ArrayList<int[][]> list = new ArrayList<int[][]>();
public static void main(String[] args) {
Lister L = new Lister();
}
public static void add(int[][] array) {
list.add(array);
printArray();
}
public static void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println("Element: " + i);
printDim(list.get(i));
}
System.out.println("--------------------------------");
}
public static void printDim(int[][] array) {
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[0].length; y++) {
System.out.print(array[y][x]+" ");
}
System.out.println();
}
System.out.println("-----------");
}
}
class Lister {
Lister() {
int[][] array1 = new int[5][5];
array1[0][4] = 1;
Test.add(array1);
int[][] array2 = array1.clone();
array2[1][2] = 1;
Test.add(array2);
}
}
Output:
Element: 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
---------------------
Element: 0
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
1 0 0 0 0
-----------
Element: 1
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
1 0 0 0 0
--------------------
Expected Output:
Element: 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
--------------------
Element: 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
-----------
Element: 1
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
1 0 0 0 0
---------------------
A 2D array cannot be shallow copied. Since it's an array of arrays, a shallow copy will give you a new outer array holding references to the same inner arrays as the original.
You need to implement a deep copy instead:
int[][] array2 = array1.clone();
for (int i = 0; i < array2.length; i++) {
array2[i] = array1[i].clone();
}
Please not that this only works for primitive arrays. If you have object arrays, you need to copy each object as well (except you're fine with having the same objects referenced).
It's because you're still using the same 'matrix' of type int. This should be fixed by declaring it again after using the first one.
import java.util.*;
class Test {
static ArrayList<int[][]> list = new ArrayList<int[][]>();
public static void main(String[] args) {
int[][] array1 = new int[5][5];
array1[0][4] = 1;
list.add(array1);
array1 = new int[5][5];
array1[1][2] = 1;
list.add(array1);
printArray();
}
public static void printArray() {
for (int i = 0; i < list.size(); i++) {
printDim(list.get(i));
}
}
public static void printDim(int[][] array) {
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[0].length; y++) {
System.out.print(array[y][x]+" ");
}
System.out.println();
}
System.out.println("--------");
}
}

DFS and BFS with adjacency matrix counted in Java

Currently trying to build a program that can implement both DFS and BFS in Java by taking in an adjacency matrix from a file and printing out the following info: order that vertices are first encountered, order that vertices become dead ends, number of components, and the tree edges.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ProjectDriver {
public static int count;
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> dfsDeadEnd = new ArrayList<Integer>();
ArrayList<Integer> dfsVertices = new ArrayList<Integer>();
ArrayList<Integer> bfsVertices = new ArrayList<Integer>();
int dfsComponents = 0;
int bfsComponents = 0;
Scanner scanner = new Scanner(new File("sample1.txt"));
int n = 8;
int[][] edges = new int[n][n];
boolean[] visited = new boolean[n];
count = 0;
for(int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
edges[i][j] = scanner.nextInt();
}
}
for(int i = 0; i < n; i++){
visited[i] = false;
}
int[][] BFStreeEdgeGraph = new int[n][n];
int[][] DFStreeEdgeGraph = new int[n][n];
int[][] crossGraph = new int[n][n];
for(int i = 0; i <= n-1; i++){
for(int j = 0; j <= n-1; j++){
DFStreeEdgeGraph[i][j] = 0;
BFStreeEdgeGraph[i][j] = 0;
crossGraph[i][j] = 0;
}
}
for(int i = 0; i <= n-1; i++){
if(visited[i] == false){
dfs(edges,i,visited, dfsVertices, dfsDeadEnd, DFStreeEdgeGraph);
dfsDeadEnd.add(i);
dfsComponents++;
}
}
for(int i = 0; i <= n-1; i++) {
if(visited[i] == false) {
bfs(edges, i, visited, bfsVertices, BFStreeEdgeGraph);
bfsComponents++;
}
}
System.out.println();
System.out.println("DFS: Number of Connected Components: " + dfsComponents);
System.out.print("DFS: Order of First Encountered: ");
for(int i : dfsVertices){
System.out.print((i+1) + " ");
}
System.out.println();
System.out.print("DFS: Order of First Dead-Ends: ");
for(int i : dfsDeadEnd){
System.out.print((i+1) + " ");
}
System.out.println();
System.out.println();
System.out.println("Tree edges:");
displayGraph(DFStreeEdgeGraph, n);
System.out.println();
System.out.println();
System.out.println("BFS: Number of Connected Components: " + bfsComponents);
System.out.print("BFS: Order of First encountered: ");
for(int i : bfsVertices){
System.out.print((i+1) + " ");
}
System.out.println();
System.out.println();
}
public static void dfs(int[][] edges, int vertex, boolean[] visited, ArrayList<Integer> dfsVertices, ArrayList<Integer> dfsDeadEnd, int[][] DFStreeEdgeGraph) {
visited[vertex] = true;
dfsVertices.add(count, vertex);
count = count + 1;
for(int w = 0; w <= edges.length-1; w++) {
if(edges[vertex][w] == 1 && !visited[w]) {
DFStreeEdgeGraph[vertex][w] = 1;
dfs(edges, w, visited, dfsVertices, dfsDeadEnd, DFStreeEdgeGraph);
dfsDeadEnd.add(w);
}
}
}
public static void bfs(int[][] edges, int vertex, boolean[] visited, ArrayList<Integer> bfsVertices, int[][] BFStreeEdgeGraph) {
bfsVertices.add(count, vertex);
count = count + 1;
for(int w = 0; w < edges.length; w++) {
if(edges[vertex][w] != 0 && !visited[w]) {
visited[vertex] = true;
}
}
for(int w = bfsVertices.indexOf(vertex) + 1; w < bfsVertices.size(); w++) {
int value = bfsVertices.get(w);
bfs(edges, value, visited, bfsVertices, BFStreeEdgeGraph);
}
}
public static void displayGraph(int[][] graph, int n) {
for(int i = 0; i <= n-1; ++i){
System.out.print(" ");
for(int j = 0; j <= n-1; ++j){
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
}
}
And here is the output from running my code:
Input graph:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
DFS: Number of Connected Components: 1
DFS: Order of First Encountered: 1 2 6 5 7 3 4 8
DFS: Order of First Dead-Ends: 5 6 8 4 3 7 2 1
Tree edges:
0 1 0 0 0 0 0 0
0 0 0 0 0 1 1 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0
BFS: Number of Connected Components: 0
BFS: Order of First encountered:
And here are my issues. For the DFS, my order of first encountered should be 1 2 6 7 4 3 5 8, but this is not what I'm getting. Additionally, my order of dead ends should be 8 7 5 4 1 2 6 3, but this is also off. My tree edges managed to come out correct.
For the BFS, I can't get anything to print, and debugging my DFS and BFS methods hasn't given me the answer yet. I'd be very grateful from some help.

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