I need my matrices to look exactly like this.(with numbers lined up under text)
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
The results I am currently getting look like.
Here are the two matrices, and the result when added:
8 5 6 6 3 8 2 3 11 13 8 9
7 7 4 5 4 9 2 1 11 16 6 6
9 4 4 8 5 1 1 1 14 5 5 9
4 2 7 7 + 7 9 1 3 = 11 11 8 10
4 3 5 3 5 6 8 7 9 9 13 10
4 2 2 1 3 9 5 5 7 11 7 6
As you can see the code for the arrays sum is shifted to the right, and I am not quite sure how to fix this.
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
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 < array1.length; i++) {
// For loop to print out array 1 and add string, if to place +
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%4s", array1[i][j]);
if (i == array1.length / 2 && j == array1[i].length-1) {
System.out.printf("%4s", '+');
}
}
System.out.print("\t");
// For loop to print out array2 and equals string, if to place =
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%2s", array2[i][j] + " ");
if (i == array1.length / 2 && j == array1[i].length-1) {
System.out.printf("%1s", '=');
}
}
System.out.print(" ");
// For loop to print out sum of array1 + array2
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%4s", sum[i][j]);
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
Also a 3x3 array when printed out looks like.
Here are the two matrices, and the result when added:
2 2 7 3 4 3 5 6 8
4 4 8 + 6 8 5 = 7 9 13
1 9 3 6 8 6 7 7
I think this is meant to insure that numbers, when printed, always take up 2 spaces:
System.out.printf("%2s", array2[i][j] + " ");
But because of the added (technically, concatenated) " ", you get a string that is bigger than the %2s field, so there is no padding of short numbers.
Plus, you have code to decide when to print the + & =, but each should be deciding between printing the symbol and printing a space, to keep everything lined up.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
1
2 3
4 5 4
3 2 1 2
3 4 5 4 3
I want to make a triangle like that. I have tried making the triangle and the numbers but the numbers doesn't fit the triangle so the output isn't as expected. Please help.
Example input: n = 5;
1) This is the code to make the triangle.
int k = 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j <= i) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
2) This is the code to make the numbers.
int k = 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i % 2 == 0) {
if (k == 5) {
break;
}
System.out.print(k + " ");
k++;
} else if (i % 2 != 0) {
if (k == 1) {
break;
}
System.out.print(k + " ");
k--;
}
}
}
We need to print a number of rows, with each row printed having the same number of values as the row number. If we were printing *'s, it would be easy:
static void printTriangle(int rowCount) {
for (int row = 1; row <= rowCount; row++) {
for (int i = 0; i < row; i++)
System.out.print("* ");
System.out.println();
}
}
printTriangle(5)
*
* *
* * *
* * * *
* * * * *
Instead of printing *'s, we want the values to come from a repeating sequence of 1 2 3 4 5 4 3 2 ....
The sequence is 8 long, so if we take an ever-increasing number a, starting at 0, and calculate remainder when dividing by 8, i.e. b = a % 8, we get a repeating sequence of 0 1 2 3 4 5 6 7 .... If we then calculate distance from 4, using c = Math.abs(4 - b), we get 4 3 2 1 0 1 2 3 .... If we subtract that from 5, i.e. d = 5 - c, we get 1 2 3 4 5 4 3 2 ..., i.e. the desired sequence.
static void printTriangle(int rowCount) {
int a = 0;
for (int row = 1; row <= rowCount; row++) {
for (int i = 0; i < row; i++) {
int b = a % 8;
int c = Math.abs(4 - b);
int d = 5 - c;
System.out.print(d + " ");
a++;
}
System.out.println();
}
}
The code can be reduced to:
static void printTriangle(int rowCount) {
for (int seq = 0, row = 1; row <= rowCount; row++) {
for (int i = 0; i < row; i++, seq++)
System.out.print((5 - Math.abs(4 - seq % 8)) + " ");
System.out.println();
}
}
printTriangle(10)
1
2 3
4 5 4
3 2 1 2
3 4 5 4 3
2 1 2 3 4 5
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
4 3 2 1 2 3 4 5 4 3
For the advanced version, we can make the max value printed be dynamic too:
static void printTriangle(int rowCount, int maxValue) {
String fmt = "%" + String.valueOf(maxValue).length() + "s ";
for (int row = 1, seq = 0; row <= rowCount; row++) {
for (int i = 0; i < row; i++, seq++)
System.out.printf(fmt, (maxValue - Math.abs(maxValue - 1 - seq % (maxValue * 2 - 2))));
System.out.println();
}
}
printTriangle(5, 5)
1
2 3
4 5 4
3 2 1 2
3 4 5 4 3
printTriangle(20, 14)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 13
12 11 10 9 8 7
6 5 4 3 2 1 2
3 4 5 6 7 8 9 10
11 12 13 14 13 12 11 10 9
8 7 6 5 4 3 2 1 2 3
4 5 6 7 8 9 10 11 12 13 14
13 12 11 10 9 8 7 6 5 4 3 2
1 2 3 4 5 6 7 8 9 10 11 12 13
14 13 12 11 10 9 8 7 6 5 4 3 2 1
2 3 4 5 6 7 8 9 10 11 12 13 14 13 12
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6
7 8 9 10 11 12 13 14 13 12 11 10 9 8 7 6 5
4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 13
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 10 11 12 13 14 13 12 11 10 9 8 7 6 5 4 3 2 1 2
i want devide matrix into four sub-blocks equally by vertically and horizontallty in java (Here, we suppose that m and nare even numbers) .
for example we have matrix:
1 2 3 4 5 6
7 8 9 1 2 8
1 2 3 4 5 6
4 5 6 7 8 9
1 4 7 2 5 8
3 6 9 7 2 5
I want to display the last block that is:
7 8 9
2 5 8
7 2 5
how i can resolve this problem in java.
Iterate over the lower-right part of the matrix. Here is an example for a square matrix. I am sure you will be able to make it more generic for non-square quadrants or to get other quadrants than the lower-right one.
public int[][] getQuadrantOfSquareMatrix(int[][] matrix) {
int newDimension = matrix.length / 2;
int[][] toReturn = new int[newDimension][newDimension];
for (int i = 0; i < newDimension; i++) {
for (int j = 0; j < newDimension; j++) {
toReturn[i][j] = matrix[i + newDimension][j + newDimension];
}
}
return toReturn;
}
I'm trying to write an insertion sort, and I pass several test cases, but I fail one. My code is:
static void insertionSort1(int n, int[] arr) {
int copy = arr[n-1];
int i = n - 1;
while (copy < arr[i-1]){
arr[i] = arr[i-1];
for(int k = 0; k < arr.length; k++){
System.out.print(arr[k] + " ");
}
System.out.println();
i--;
}
arr[i] = copy;
for(int m = 0; m < arr.length; m++){
System.out.print(arr[m] + " ");
}
}
where n is the size of the array, and arr is the array. My algo fails this test case in particular:
10
2 3 4 5 6 7 8 9 10 1
I get index out of bounds on that but not on
5
2 4 6 8 3
or others. what's going on?
That is an index out of bound exception of the array because of minus value of the arr. It is not an algorithm issue but a language.
while (i > 0 && copy < arr[i - 1])
Source:
public class InsertionSort {
static void insertionSort1(int n, int[] arr) {
int copy = arr[n - 1];
int i = n - 1;
while (i > 0 && copy < arr[i - 1]) {
arr[i] = arr[i - 1];
for (int k = 0; k < arr.length; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
i--;
}
arr[i] = copy;
System.out.println("#### RESULT ####");
for (int m = 0; m < arr.length; m++) {
System.out.print(arr[m] + " ");
}
System.out.println("\n#### END ####\n");
}
public static void main(String[] args)
{
//10
//2 3 4 5 6 7 8 9 10 1
int[] arr ={2, 3, 4, 5, 6, 7, 8, 9, 10, 1};
int n = arr.length;
insertionSort1(n, arr);
//5
//2 4 6 8 3
arr= new int[5];
n = arr.length;
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr[3] = 8;
arr[4] = 3;
insertionSort1(n, arr);
}
}
Result:
2 3 4 5 6 7 8 9 10 10
2 3 4 5 6 7 8 9 9 10
2 3 4 5 6 7 8 8 9 10
2 3 4 5 6 7 7 8 9 10
2 3 4 5 6 6 7 8 9 10
2 3 4 5 5 6 7 8 9 10
2 3 4 4 5 6 7 8 9 10
2 3 3 4 5 6 7 8 9 10
2 2 3 4 5 6 7 8 9 10
#### RESULT ####
1 2 3 4 5 6 7 8 9 10
#### END ####
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
#### RESULT ####
2 3 4 6 8
#### END ####
Have a good day.
First, you should review what an insertion sort is. You should be building a sorted list on one end of the array, expanding it one element at a time by "inserting" the next value in the correct place. It should be much like sorting a hand of cards if you are given them one at a time. You will need a nested loop to do it correctly.
Carefully consider what your program is really doing and see why it fails -- a shorter test case that fails in the same way would be [3, 2, 1]. Or [2, 1], for that matter.
I'm working on an assignment that asks a user to input an integer between 1-15 and then displays an integer pyramid for the number of rows they selected.
I have everything working, but if the number enters an integer greater than 10, I'm getting tripped up by the extra space needed for a double digit number. I've attached my code below. If anyone could provide a little help it would be greatly appreciated.
int lines = input.nextInt();
for (int row = 1; row <= lines; row++)
{
for (int column = 1; column <= lines - row; column++)
{
System.out.print(" ");
}
for (int num = row; num >= 1; num--)
{
System.out.print((num>=10)?+num:" "+num);
}
for (int num = 2; num <= row; num++)
{
System.out.print((num>=10)?+num:" "+num);
}
System.out.println();
}
With my current code, if the user entered 13, it would produce the following output:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 910
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
I just need to figure out how to get the extra space for the double digit integers. The desired output would be:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
It looks like you have chosen to do this the (slightly) harder way.
The easy way would be to reserve three spaces for each number (so that single digit numbers would have two spaces between them).
What you have chosen to do is variable spacing depending on the actual length of the numbers in each column. The first step is to change your output statements to the following:
System.out.print(" "+num);
So you will always print one space between numbers on each row. If you run that, you'll notice that it almost works except the top part of the triangle is misaligned. To fix that, you'll have to adjust your
System.out.print(" ");
statement so that the number of spaces it prints in each column depends on the value of the number that will appear in each column later on. To do this, you'll have to work out some arithmetic involving column and lines, to choose between " " (two spaces) and " " (three spaces). It's straightforward but I'll let you work out the details.
It is possible to further extend this idea to support 100 lines or more, but it's not clear that you need that capability.
I was interested in solving this, so wrote a simple solution for your task. Seems to work for any lines value.
public static void main(String[] args) {
int lines = 100;
for (int row = 1; row <= lines; row++) {
for (int i = 0; i < calculateOffset(row, lines); i++) {
System.out.print(" ");
}
System.out.print(row);
for (int num = row-1; num >= 1; num--) {
System.out.print(" " + num);
}
for (int num = 2; num <= row; num++) {
System.out.print(" " + num);
}
System.out.println();
}
}
private static int calculateOffset(int row, int totalRows) {
return calculateSpace(totalRows) - calculateSpace(row);
}
private static int calculateSpace(int columnsCount) {
int categoryLowest = 1;
int categoryHighest = 9;
int categoryDigits = 1;
int charactersUsed = 0;
while (categoryLowest <= columnsCount) {
int categoryItems = Math.min(categoryHighest, columnsCount) - categoryLowest + 1;
int numbersCharacters = categoryDigits * categoryItems;
int spacesCharacters = (categoryItems - 1);
boolean previousCategoryIncluded = categoryLowest > 1;
int spaceBetweenCategoriesPresent = previousCategoryIncluded ? 1 : 0;
charactersUsed += numbersCharacters + spacesCharacters + spaceBetweenCategoriesPresent;
categoryHighest = categoryHighest * 10 + 9;
categoryLowest *= 10;
categoryDigits++;
}
return charactersUsed;
}
No idea why you chose the logic like that. However, intuitively, this is what I am going to do:
1 find mid point location (you can simply contruct the last line and find the mid-point)
2 a function to construct a line, by simply do (psuedo-code):
String getLine(int num) {
String result = "";
for (int i = num; i > 0; i--) {
result = result + i + " ";
}
for (int i = 2; i <= num; i++) {
result = result + i + (i == num? "" : " ");
}
return result;
}
3 do a loop to print each line:
int midPoint = .....; //
for (i=0; i < num; i++) {
String line = getLine(i+1);
print (midPoint - mid point of line) spaces;
print line
}
Update:
Have briefly tested, looks good to me:
public static String getLine(int num) {
String result = "";
for (int i = num; i > 0; --i) {
result = result + i + " ";
}
for (int i = 2; i <= num; ++i) {
result = result + i + (i == num ? "" : " ");
}
return result;
}
public static void main(String[] args) {
int num = 15;
int midPoint = getLine(num).length()/2 + 1;
for (int i = 0; i < num; ++i) {
String line = getLine(i+1);
int noPrefix = midPoint - (line.length()+1)/2 ;
for (int j = 0; j < noPrefix; ++j) {
System.out.print(" ");
}
System.out.println(line);
}
}
result :
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Late to the party, but here's a solution using StringBuilder and printing it out only at the end.
The idea is to calculate the amount of padding required based on the String equivalent of the current value.
Note: The solution is not efficient (with all the conversion to String), but it can be used for any input value.
Working Example:
import java.util.Scanner;
public class IntegerPyramid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter # of lines: ");
int numLines = sc.nextInt();
StringBuilder sb = new StringBuilder();
System.out.println();
for(int row = 1; row <= numLines; row++) {
for(int num = -numLines; num <= numLines; num++) {
if(num == -1 || num == 0)
continue;
int value = Math.abs(num);
int padding = String.valueOf(value).length() + 1;
if(value <= row) {
// Print numbers
sb.append(String.format(("%" + padding + "d"), value));
}
else {
// Print spaces
sb.append(String.format(("%" + padding + "s"), ""));
}
}
sb.append("\n");
}
System.out.println(sb.toString());
sc.close();
}
}
Output:
Enter # of lines: 6
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Enter # of lines: 15
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
You've got the conditional backwards, believe it should be
System.out.print((num >= 10) ? " " + num : num)
Easier to understand
System.out.print((num < 10) ? num : num : " " + num)
How do I make this table?
This is what should be the outcome:
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 0
2 3 4 5 6 7 8 9 0 1
3 4 5 6 7 8 9 0 1 2
4 5 6 7 8 9 0 1 2 3
5 6 7 8 9 0 1 2 3 4
6 7 8 9 0 1 2 3 4 5
7 8 9 0 1 2 3 4 5 6
8 9 0 1 2 3 4 5 6 7
9 0 1 2 3 4 5 6 7 8
And this is the best I could come up with:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++) {
if (i + j < 10) {
System.out.print(i + j);
} else
System.out.print("x");
}
System.out.println();
}
}
}
I simply can't find a solution how to get numbers running again past 9 with the beginning of 0,1,2,3 etc. My code would generate next:
0123456789
123456789x
23456789xx
3456789xxx
456789xxxx
56789xxxxx
6789xxxxxx
789xxxxxxx
89xxxxxxxx
9xxxxxxxxx
You can do:
System.out.print((i + j) % 10);
To turn 10 into 0, 11 into 1, etc.
Try this:
for (int i=0; i<10; i++) {
for (int j=i; j<i+10; j++) {
System.out.print(j%10);
}
System.out.println();
}
The key here is to use %(modulo) operator.