Creating N by N diagonal matrix using basic logic - java

I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0
Currently I have this method:
public static void drawMatrix(){
for (int line = 0; line < N; line++){
for (int j = 0; j < N; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.

j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:
if (j > line) {
System.out.print((N-line+j)%N + " ");
} else {
System.out.print((line-j+N)%N + " ");
}
Demo.
You can also rewrite it without an if using a conditional expression:
int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");
Demo.

A little change in your code works
public static void drawMatrix() {
for(int line = 0; line < N; line++) {
for(int j = 0; j < N; j++) {
System.out.print(Math.abs(line - j) + " ");
}
System.out.println();
}
}

I would do something like :
int n=6;
for(int row=0;row<n;row++)
{
for(int col = 0;col<n;col++)
{
System.out.print(abs(col-row) +" ");
}
System.out.println();
}
assuming you can use abs().
I hoped that help your purpose.

This also works :
public static void main(String[] args) {
int N = 6;
int column = 0;
for (int row = 0; row < N; row++) {
for (column = row; column >= 0; column--) //prints till row number reaches 0
System.out.print(column + " ");
for (column = 1; column < N - row; column++)//from 1 to N-row
System.out.print(column + " ");
System.out.println();
}
}

Related

Struggles with nested for-loop

I am having problems with my code.
The goal with my code is for a user to enter a number which is then used to form
a multiplication-table. For example, if the user enters the number 4, the program is supposed to print following:**
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
This is my current code. Thankful for any kind of help!
import java.util.Scanner;
public class MultiplicationTable {
public static void main (String[] arg) {
Scanner gt = new Scanner(System.in);
System.out.println("Enter a number for multiplication: ");
int N = gt.nextInt();
for(int i = 1; i < N; i++) {
for(int j = 1; j < N; j++);
int product = i * j;
System.out.print(i +" * " +j +" = " +product );
System.out.println();
}
}
}
There are two tiny errors in your code, otherwise you are good to go.
for(int i = 1; i < N; i++) {
for(int j = 1; j < i; j++); //<-- remove this semicolon
{ // <-- use curly braces here for the loop statements
int product = i * j;
System.out.print(i +" * " +j +" = " +product+" "); //<--add an additional space at the end
}
System.out.println();
}
To get that pyramidal structure, you should change the second loop limit to i :
for(int j = 1; j < i; j++)
And remove the semicolon at the end of the loop.

Printing spaces to align numbers according to my pyramid pattern

It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.

Java using for-loop to produce series of numbers

I am trying to write a collection of for-loops that produce the following series of numbers below. I am trying to accommodate my loops to print each series on the same line, with spaces between each term. I am new to java and got really confused on how exactly I can accomplish it. On the right side are the digits I am increasing the counting by.
1. 4 5 6 7 8 9 10 (+1)
2. 6 5 4 3 2 1 (-1)
3. 2 4 6 8 10 12 14 16 (+2)
4. 19 17 15 13 11 9 7 5 (-2)
5. 7 15 23 31 39 (+8)
6. 2 4 8 16 32 64 (*2)
Here is the code the way I tried to accomplish it. I got the first row to work but I'm wondering weather there's an easy way I can create the rest of them without re-duplicating the program.
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run()
{
{
for(int row = 1; row < 2; row++)
{
print(" " + row + ". ");
for (int col = 4; col < 11; col++)
{
print(row*col + " ");
} //col values
println( );
} //row values
}
}
}
I am new to java and right now going over for-loops and trying to accomplish this in for-loop. If someone could help me out, I would really appreciate it.
Thank you!
Edit:
Here is what happens when I increase the number of rows.
Edit:
Here is the solution of what I had tried accomplishing. Thanks to everyone who helped me.
import acm.program.*;
public class ppLoop extends ConsoleProgram
{
public void run()
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
print(i + ". "); // print row number 1
for (int j = 4; j < 11; j++) // loop for row 1
{
print(j + " ");
}
println( );
print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
print(j + " ");
}
println();
print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
print(j + " ");
}
println();
print((i + 3) + ". ");
for (int j = 19; j > 4; j = j - 2) // loop for row 4
{
print(j + " ");
}
println();
print((i + 4) + ". ");
for (int j = 7; j < 40; j = j + 8) // loop for row 5
{
print(j + " ");
}
println();
print((i + 5) + ". ");
for (int j = 2; j < 65; j = j * 2) // loop for row 6
{
print(j + " ");
}
println();
}
} //close outer loop
} //close public run
} //close console program
You can perform this program with a series of nested loops. I have done the first three rows. I took out your package and used a main method. Also, your indentation was very confusing. Since your increment changes each line, I don't know of a way to make it any shorter than this using for loops.
public class ppLoop{
public static void main(String[] args)
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
System.out.print(i + ". "); // print row number
// you can use the same variable for each inner loop
for (int j = 4; j < 11; j++) // loop for row 1
{
System.out.print(j + " ");
}
System.out.println( );
System.out.print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
System.out.print(j + " ");
}
System.out.println();
System.out.print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
System.out.print(j + " ");
}
}
}
}
}
You could create a method that takes:
1. A start number
2. What math operation to perform (add, subtract, or multiply)
3. What number to increment/decrement or multiply by
4. An end number
It would look similar to this:
public void formattedFor(int startNum, String operation, int num, int endNum) {
if (operation.equals("add")) {
for (int i = startNum; i < endNum; i += num) {
System.out.print(i + " ");
}
}
if (operation.equals("sub")) {
for (int i = startNum; i > endNum; i -= num) {
System.out.print(i + " ");
}
}
else if (operation.equals("mult")) {
for (int i = startNum; i < endNum; i *= num) {
System.out.print(i + " ");
}
}
System.out.println( );
}
If I'm understanding the problem, you want to print six series that each start with a different number and increment/decrement that number by some value. Since I see no relationship between the initial value and the increment/decrement, you're going to have to write six separate for loops.
If you're absolutely averse to this, you can store your initial values, your increments/decrements, and your final values in an array and iterate through them using a for loop, an if statement (to deal with the multiplication) and a while loop. The array would look like this:
int[][] values = new int[][] {
{4, 6, 2, 19, 7, 2},
{1, -1, 2, -2, 8, 2},
{10, 1, 16, 5, 39, 64}
};
I could write up the source based on this, but it's not what you asked for.
I strongly suspect that, if this is a homework assignment and you've modified the problem, there's something you've failed to understand about the problem itself. If this is meant to have an simple solution that uses for loops, there should probably be some logic that binds the rows together, unless you're allowed to use arrays/while loops/for loops/objects and methods.
On another note, you should format your code differently. It's somewhat difficult to read right now. In general, indent things that happen inside loops, classes, or functions. For example:
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run() {
for(int row = 1; row < 2; row++) {
print(" " + row + ". ");
for (int col = 4; col < 11; col++) {
print(row*col + " ");
} //col values
println( );
} //row values
}
}

I have to print a series using for loop

Here is the series :
12345
22345
33345
44445
I tried to solve this but it is not coming correct...
Here is the code :
class q14
{
public static void main ( )
{
int i,j,k;
for (i=1;i<=5;i++)
{
for (j=i;j<=5;j++)
{
for (k=1;k<=i;k++)
{
System.out.print (i + " ");
}
System.out.print (j + " ");
}
System.out.println();
}
}
}
The following block should generate the series as you described it.
int numberOfLines = 4;
int numberOfDigitsPerLine = 5;
for (int i=1; i<numberOfLines+1; i++){
for(int j=1; j<=numberOfDigitsPerLine; j++) {
if(j>=i) {
System.out.print(j);
} else {
System.out.print(i);
}
}
System.out.println();
}
Change numberOfLines and numberOfDigitsPerLine as necessary.
Elaboration:
First you must analyze the series, by the looks of it the first number starts with 1 and goes onward for 5 digits, the second line goes along 5 digits as well up to 5 as previously but it replaces the first digit with 2.
Moving down the numbers we can see a pattern of which the N-th number will have N amount of N digits followed by consecutive digits up to the number 5.
So in my code above I chose max N to be 4 as you described it, and the numbers go up to 5, these are represented by the variables numberOfLines and numberOfDigitsPerLine respectively.
The block itself checks what is N at that point (in my block it is represented by i) and then proceeds to go towards the max number 5, this is done within the j for loop. If j is larger or equal to N then we print j, otherwise we haven't finished printing all of the N's yet so we print N instead.
Here it is:
for (int i = 1; i <= 5; i++)
{
for(int k = 1; k <= i;k++)
System.out.print(i);
for (int j = i + 1; j <= 5; j++)
System.out.print(j);
System.out.print("\n");
}
You dont need a third loop for your series
for (int j=1;j<=5;j++) {
for (int k=1;k<=5;k++){
if(k<=j)
System.out.print (j + " ");
else
System.out.print (k + " ");
}
System.out.println();
}
output
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
Demo
Try this:
for(int i=1;i<=4;i++)
{
for(int j = 1; j<=5;j++)
{
if(i>j)
{
for(int x= 1 ; x<=i;x++)
{
System.out.print(i);
j++;
}
}
System.out.print(j);
}
System.out.println("\n");
}

How to make pattern of numbers in java using only two variables?

#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
this is the required pattern and the code which i used is
public class Test{
public static void main(String[] args) {
int k = 1;
for (int i = 0; i <= 5; i++){
for (int j = 1; j <= i; j++){
System.out.print(k + " ");
k++;
}
System.out.println();
}
}
}
as you can see i used the variable k to print the numbers.
My question is that is there a way to print the exact same pattern without using the third variable k?
I want to print the pattern using only i and j.
Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:
Could you print the sequence if you knew the last number from the prior line? - the answer is trivial: you would need to print priorLine + j
Given i, how would you find the value of the last number printed on i-1 lines? - to find the answer, look up the formula for computing the sum of arithmetic sequence. In your case d=1 and a1=1.
You can use this:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print((i * (i - 1)) / 2 + j + 1 + " ");
}
}
}
Or you can the find the nth term and subtract it each time:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(((i * (i + 1)) / 2) - (i - j) + " ");
// k++;
}
System.out.println(" ");
}
}
You can use
System.out.println((i+j) + " ");
e.g.
i j (i+j)
0 1 1
1 1 2
2 1 3
2 2 4
..........

Categories