How to print a diamond of random numbers? - java

Can someone help me complete this numeric diamond? I have the right side of the diamond printing out, but I'm having trouble printing out the left side of it. If anybody can help I would really appreciate it.
I made some changes to my code. I now need my code to print one column in the middle of the diamond instead of two.
public class NumericDiamond {
public static void main(String[] args) {
/*
1 1
4 3 4 2
4 4 5 7 4 3
5 3 5 4
4 5
*/
int noOfColumns = 1;
int noOfSpaces = 3;
int start = 0;
for (int i = 1; i <= 5; i++) {
for (int j = noOfSpaces; j >= 1; j--) {
System.out.print(" ");
}
for (int j = 1; j <= noOfColumns; j++) {
System.out.print(noOfColumns);
}
if (i < 5) {
start = i;
} else {
start = 8 - i;
}
System.out.print(start + " ");
start--;
System.out.println();
if (i < 3) {
noOfColumns = noOfColumns + 2;
noOfSpaces = noOfSpaces - 1;
} else {
noOfColumns = noOfColumns - 2;
noOfSpaces = noOfSpaces + 1;
}
}
}
}

When you write something out to the screen, think in rows.
In the first and last row, you print 1 random number. In the second and fourth row, you print 3 random numbers. In the middle row, you print 5 random numbers.
You can use tab or spaces to place the numbers to their positions.
Random rnd = new Random();
for(int i = 0; i < 5; i++) {
if(0 == i || 4 == i) System.out.println("\t\t" + (rnd.nextInt(5)+1) + "\t\t\t" + (i+1));
if(1 == i || 3 == i) System.out.println("\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t\t" + (i+1));
if(2 == i) System.out.println((rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (rnd.nextInt(5)+1) + "\t" + (i+1));
}
Something like this.

To print a diamond you can use two nested for loops (or streams) over rows and columns from -n to n. The diamond shape is obtained when n > iAbs + jAbs. The value of a cell depends on its coordinates i and j, or it can be some kind of constant or random value:
int n = 5;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// diamond shape (cell value = iAbs + jAbs)
if (iAbs + jAbs > n) {
System.out.print(" ");
} else {
System.out.print(" " + (iAbs + jAbs));
}
}
System.out.println(" i=" + iAbs);
}
Output:
5 i=5
5 4 5 i=4
5 4 3 4 5 i=3
5 4 3 2 3 4 5 i=2
5 4 3 2 1 2 3 4 5 i=1
5 4 3 2 1 0 1 2 3 4 5 i=0
5 4 3 2 1 2 3 4 5 i=1
5 4 3 2 3 4 5 i=2
5 4 3 4 5 i=3
5 4 5 i=4
5 i=5
Similarly, you can use two nested streams:
int n = 5;
IntStream.rangeClosed(-n, n)
// absolute value of 'i'
.map(Math::abs)
.peek(i -> IntStream.rangeClosed(-n, n)
// absolute value of 'j'
.map(Math::abs)
// diamond shape (cell value = n - i - j)
.mapToObj(j -> i + j > n ? " " : " " + (n - i - j))
.forEach(System.out::print))
.mapToObj(i -> " i=" + i)
.forEach(System.out::println);
Output:
0 i=5
0 1 0 i=4
0 1 2 1 0 i=3
0 1 2 3 2 1 0 i=2
0 1 2 3 4 3 2 1 0 i=1
0 1 2 3 4 5 4 3 2 1 0 i=0
0 1 2 3 4 3 2 1 0 i=1
0 1 2 3 2 1 0 i=2
0 1 2 1 0 i=3
0 1 0 i=4
0 i=5
See also:
• Drawing numeric diamond
• Diamond with nested for loops

Related

Printing a squares triangle. How to mirror numbers?

So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.
However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
For full credit, each column should be 3 characters wide and the values should be right justified.
Now here is what I have written for my code so far:
import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");
// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}
And this is what that code PRINTS when I enter 4:
Enter a number that is between 1 and 9 (inclusive):
4
1
4 1
9 4 1
16 9 4 1
As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.
Answer is:
public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}
Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):
y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
And here is example result for 4:
And 9:
In the outer loop or stream you have to iterate from 1-n to n-1 (inclusive) and take absolute values for negative numbers. The rest is the same.
If n=6, then the triangle looks like this:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
Try it online!
int n = 6;
IntStream.rangeClosed(1 - n, n - 1)
.map(Math::abs)
.peek(i -> IntStream.iterate(n, j -> j > 0, j -> j - 1)
// prepare an element
.mapToObj(j -> i > n - j ? " " : String.format("%3d", j * j))
// print out an element
.forEach(System.out::print))
// start new line
.forEach(i -> System.out.println());
See also: Output an ASCII diamond shape using loops
Another alternative :
public static void main(String args[]) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
int row = rows, increment = -1;
while (row <= rows){
for (int j = rows; j > 0; j--) {
System.out.print(rows - j + 1 < row ? " " : String.format("%3d", j * j));
}
System.out.println();
if(row == 1) {
increment = - increment;
}
row += increment;
}
}
The outer loop from 1-n to n-1 inclusive, and the inner decrementing loop from n to 0. The if condition is the absolute value of i should not be greater than n - j.
Try it online!
int n = 6;
for (int i = 1 - n; i <= n - 1; i++) {
for (int j = n; j > 0; j--)
if (Math.abs(i) > n - j)
System.out.print(" ");
else
System.out.printf("%3d", j * j);
System.out.println();
}
Output:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
See also: Invert incrementing triangle pattern

Formatting matrices to be read left to right

I need my matrices to look exactly like this.
Here are the two matrices, and the result when added:
2 2 7 4 3 4 3 3 5 6 10 7
4 4 8 8 6 8 5 5 10 12 13 13
1 9 3 7 6 8 6 9 7 17 9 16
2 3 2 9 + 4 4 7 1 = 6 7 9 10
2 9 1 1 9 8 2 5 11 17 3 6
6 1 8 4 4 8 2 2 10 9 10 6
Each number should use 4 positions in the output, and the + and = should be in the middle row, but I can not get the + and = signs to stay for smaller arrays. My problem may be with my if (i == 3 && j == 3) statements.
My code for this part is as follows.
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
// Declares 2-dimensional array the same size as one in parameters
int [][]arraySum = new int [array1.length][array1[0].length];
// Arithmetic characters to be printed when asked for
String add = "+";
String subtract = "-";
String multiply = "*";
String divide = "/";
String remainder = "%";
String equals = "=";
// If arithmetic is addition to print matrices and add them to show result
if (arithmetic == '+') {
// Text for two matrices when added
System.out.print("Here are the two matrices, and the result when added:\n");
// For loop to print array1 + array2 = sum with format
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == 3 && j == 3) {
System.out.printf("%2s", add);
}
}
System.out.print("\t");
// For loop to print out array2 and equals string
for (int k = 0; k < arraySum[i].length; k++) {
System.out.printf("%3s", array2[i][k] + " ");
if (i == 3 && k == 3) {
System.out.printf("%2s", equals);
}
}
System.out.print("\t");
// For loop to print out sum of array1 + array2
for (int l = 0; l < arraySum[i].length; l++) {
System.out.printf("%3s", sum[i][l] + " ");
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
Example of what I get for 3x3 arrays. (should still print + or =).
5 3 5 6 7 4 11 10 9
8 2 9 1 5 5 9 7 14
9 7 3 2 5 1 11 12 4
Try if (i == arraySum.length/2 && j == arraySum[i].length-1).
i and j are never 3 if your matrix is 3x3. If you want + and = in the middle then write something like this:
if (i == arraySum.length / 2 && j == arraySum[i].length - 1)
Replace if (i == 3 && j == 3) { with if (i == (array1 / 2) && j == (array1 / 2)) {
Your problem is that in the for loop, you are adding the addition sign and the equals sign in the 4th row (0,1,2,3). When you only have three rows, it won't print. What you can do to make it in the middle is something like this:
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length + 1; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == Math.ceil(arraySum.length/2) && j == arraySum.length) {
System.out.printf("%2s", add);
}
}
It will print the sign in the middle (height) and at the end (lengthwise) of the array. Just to be careful, it also uses the ceiling function to round up to the next integer.

Using Nested for loops to make a doubling then halfing pyramid

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I need to make this pyramid using nested for loops,
so far all I have figured out is that I need three for loops.
I know how for loops work and have a pretty good grasp on the fundamentals of java, but I have no earthly idea on how this works.
Just wrote this without debug but it should produce this pyramid:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
for(int j = 1; j < pyramidHeight*2;j++){
if( j < pyramidHeight - i || j > pyramidHeight + i ){
System.out.print(" ");
}
else{
System.out.print(i - Math.abs(pyramidHeight - j));
}
System.out.print(" ");
}
System.out.println();
}
With two simple changes you should get your pyramid.
This should work! Note that you have each row counting total 2*i+1 elements where i is your current row number.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int lim = 5;
int spaceLim = lim*2;
for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)
String s = "%" + spaceLim + "s";
System.out.printf(s, "");
if (i == 0){
System.out.print(1);
}
else{
for (int j=0; j<i; j++) {
System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
}
for (int j=i; j>=0; j--){
System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
}
}
System.out.println();
spaceLim -= 2;
}
}
}
The demo of working solution is here - http://ideone.com/J2fcQw

Need help in pattern printing

I need to print the following pattern and i almost did with the coding part.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Following is the program I tried
public class MyPattern {
public static void main(String[] args) {
for (int i = 0; i <= 7; i++) {
for (int j = 1; j <= 7 - i; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
int n = (int) Math.pow(2.0D, j);
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
}
for (int j = i - 1; j >= 0; j--) {
int n = (int) Math.pow(2.0D, j);
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
}
System.out.print('\n');
}
}
}
When running the program I got the following output
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
But I need the output aligned to left (as specified first). Please help.
Well it's clearly caused by this part of code:
for (int j = 1; j <= 7 - i; j++) {
System.out.print(" ");
}
Have you tried running it without it?
if (n > 100) {
System.out.print(" " + n);
} else if (n > 10) {
System.out.print(" " + n);
} else {
System.out.print(" " + n);
}
Could also just be, as it does not matter what n is - it will all just do the same.
System.out.print(" " + n);
Comment the line:
//System.out.print(" ");
In the first for loop.
I hope this code helps you understand a few things.
// Make it ready for the loop, no point calling Math.pow() every loop - expensive
import static java.lang.Math.pow;
public class MyPattern {
public void showTree(int treeDepth) {
// Create local method fields, we try to avoid doing this in loops
int depth = treeDepth;
String result = "", sysOutput = "";
// Look the depth of the tree
for( int rowPosition = 0 ; rowPosition < depth ; rowPosition++ ) {
// Reset the row result each time
result = "";
// Build up to the centre (Handle the unique centre value here)
for( int columnPosition = 0 ; columnPosition <= rowPosition ; columnPosition++ )
result += (int) pow(2, columnPosition) + " ";
// Build up from after the centre (reason we -1 from the rowPosition)
for ( int columnPosition = rowPosition - 1 ; columnPosition >= 0 ; columnPosition-- )
result += (int) pow(2, columnPosition) + " ";
// Add the row result to the main output string
sysOutput += result.trim() + "\n";
}
// Output only once, much more efficient
System.out.print( sysOutput );
}
// Good practice to put the main method at the end of the methods
public static void main(String[] args) {
// Good practice to Create Object of itself
MyPattern test = new MyPattern();
// Call method on object (very clear this way)
test.showTree(5);
}
}

How to get the following formatted output?

I wrote the code to get the following formatted output, but when I enter number of rows in double digits, the output format changes. Why? How can I fix this?
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Here is my code:
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
System.out.print(Math.min(k, i * 2 - k) + " ");
}
System.out.println();
}
}
}
It's because the value in double digit will change the whole architecture.The set will shift to right one place. So you can put a condition like this. I have added one extra space between numbers to improve visibility.
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= (numrow - i); j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
int temp = Math.min(k, i * 2 - k);
if (temp > 9) {
System.out.print(temp + " ");
} else {
System.out.print(temp + " ");
}
}
System.out.println();
}
}
}
In this example I counted the digits, and for every digit I add an extra space.
The output of the value is formatted with leading zeros (digit-count).
public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
final int numrow = 100;// sc.nextInt();
final int digits = (int) Math.log10(numrow) + 1;
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
for (int l = 0; l < digits; l++) {
System.out.print(" ");
}
}
for (int k = 1; k < i * 2; k++) {
final int value = Math.min(k, i * 2 - k);
System.out.print(String.format("%0" + digits + "d ", value));
}
System.out.println();
}
}
You can use String.format method:
"%2d" - format as a two-digit number.
"%02d" - format as a two-digit number with leading zeros.
Example:
// int n = 5;
int n = 12;
// number of digits
int digits = String.valueOf(n).length();
// format string
String format = "%" + digits + "d";
// output
System.out.println("n=" + n + ", format=" + format);
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.rangeClosed(-n, i)
.map(Math::abs)
.map(j -> j = i - j)
.filter(j -> j != 0)
.mapToObj(j -> j > 0 ?
String.format(format, j) : " " .repeat(digits))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
Output:
n=5, format=%1d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
n=12, format=%2d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 11 10 9 8 7 6 5 4 3 2 1
See also: Print the sum of the row and column in a 2d array after each row

Categories

Resources