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