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);
}
}
Related
I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.
How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);
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
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
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