How to print numbers in a triangle pattern? - java

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.

Related

(Java) How to get an input like this

I need a code that reads the number of tests that will be done and then read values on a matrix for each test.
INPUT:
3
Test 1
0 20 10
1 12 34
1 5 6
Test 2
0 22 10
1 10 34
0 0 0
Test 3
0 10 10
0 0 20
0 0 0
My attempt:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Number of tests");
int n = input.nextInt();
String[] name = new String[n];
int test[][] = new int[n][3];
for (int i = 0; i < n; i++) {
System.out.println("Name of the test" + i);
name[i] = input.nextLine();
System.out.println("Values");
for (int j = 0; j < 3; j++) {
test[i][j] = input.nextInt();
}
}
}
You need a 3-D array instead of a 2-D because for each of the test has a 2-D array under it.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
final int ROWS = 3, COLS = 3;
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int test[][][] = new int[n][ROWS][COLS];
for (int i = 0; i < n; i++) {
System.out.println("Test " + (i + 1));
for (int j = 0; j < ROWS; j++) {
for (int k = 0; k < COLS; k++) {
test[i][j][k] = input.nextInt();
}
}
}
// Display
System.out.println("Displaying...");
for (int i = 0; i < n; i++) {
System.out.println("Test " + (i + 1));
for (int j = 0; j < ROWS; j++) {
for (int k = 0; k < COLS; k++) {
System.out.printf("%4d", test[i][j][k]);
}
System.out.println();
}
}
}
}
A sample run:
3
Test 1
0 20 10
1 12 34
1 5 6
Test 2
0 22 10
1 10 34
0 0 0
Test 3
0 10 10
0 0 20
0 0 0
Displaying...
Test 1
0 20 10
1 12 34
1 5 6
Test 2
0 22 10
1 10 34
0 0 0
Test 3
0 10 10
0 0 20
0 0 0

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.

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();
}

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!

Print triangle (Half Pyramid) pattern using 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();
}

Categories

Resources