Swapping 2D matrix diagonal with a middle line - java

I have a Java 2D array
String arraylist numberSeq[][];
inside the array list, there is number from 1 to 25,
numberSeq[0][0] = 1, [0][1] = 2, [0][2] = 3 , [0][3] = 4 , [0][4] = 5
numberSeq[1][0] = 6, [1][1] = 7, [1][2] = 8 , [1][3] = 9 , [1][4] = 10
......
numberSeq[4][0] = 21,[4][1] = 22,[4][2] = 23, [4][3] = 24, [4][4] = 25
So the number will be like
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
After doing a diagonals swap, I wish the output to be like
25 20 15 10 5
24 19 14 9 4
23 18 13 8 3
22 17 12 7 2
21 16 11 6 1
How can I achieve that when I can only declare one local variable?
If one local variable is not achievable, how much is the minimum number of local variables I need?

This should help. so yes, a swap with a single local variable is possible.
public swapDiagonally(int[][] mtx) {
for(int i = 0 ;i< mtx.length; i++){
for(int j = 0; j < mtx[0].length - i; j++){
int temp = mtx[i][j];
mtx[j][i]; = mtx[mtx.length-1-i][mtx[0].length-1-j];
mtx[mtx.length-1-i][mtx[0].length-1-j] = temp;
}
}
}
I am essentially traversing 'total rows - N' for every Nth column, thus, helping me travers this structure:
1 2 3 4
1 2 3
1 2
1
for a 4x4 array!!!

the following loop will do the diagonal swap as in your question:
int n=5;
int[][] newmat = new int[5][5];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
newmat[(n-1) - j][(n-1)- i] = matrix[i][j];
}
}

You can do this by making another teo dimensional array, iterating through your first in the right order and post it to a new one.
public class MyClass {
public static void main(String args[]) {
int dimension = 5;
int[][] numberSeq = new int[dimension][dimension];
numberSeq[0][0] = 1; numberSeq[0][1] = 2;numberSeq[0][2] = 3;numberSeq[0][3] = 4;numberSeq[0][4] = 5;
numberSeq[1][0] = 6; numberSeq[1][1] = 7;numberSeq[1][2] = 8;numberSeq[1][3] = 9;numberSeq[1][4] = 10;
numberSeq[2][0] = 11;numberSeq[2][1] = 12;numberSeq[2][2] = 13;numberSeq[2][3] = 14;numberSeq[2][4] = 15;
numberSeq[3][0] = 16;numberSeq[3][1] = 17;numberSeq[3][2] = 18;numberSeq[3][3] = 19;numberSeq[3][4] = 20;
numberSeq[4][0] = 21;numberSeq[4][1] = 22;numberSeq[4][2] = 23;numberSeq[4][3] = 24;numberSeq[4][4] = 25;
int[][] flippedSeq = new int[dimension][dimension];
// This is the flipping part
for(int i = 0; i < dimension; i++)
{
for(int j = 0; j < dimension; j++)
{
flippedSeq[i][j] = numberSeq[dimension-1-j][dimension-1-i];
}
}
PrintMatrix(numberSeq);
System.out.println();
PrintMatrix(flippedSeq);
}
public static void PrintMatrix(int[][] mat)
{
for(int i = 0; i < mat.length; i++)
{
for(int j = 0; j < mat[i].length; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
}
}
I hope thats what you meant by "1 local variable".
Output is:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
25 20 15 10 5
24 19 14 9 4
23 18 13 8 3
22 17 12 7 2
21 16 11 6 1

Related

Printing a snake pattern using an array

I'm having trouble with an assignment where we are required to print out this array:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
My code is somewhat correct but it is not printing 10 and 19 where it should be.
My output:
Choose a number for the rows from 0 to 16.
5
Choose a number for the columns from 0 to 16
5
1 0 10 0 19
2 9 11 18 20
3 8 12 17 21
4 7 13 16 22
5 6 14 15 23
My code:
//snake move with the number
import java.util.Scanner;
public class SnakeMove {
public static void main(String[] args) {
//create Scanner object
Scanner inScan = new Scanner(System.in);
//prompt the user to choose number for the Row from 0 to 16
System.out.println("Choose a number for the rows from 0 to 16.");
//take the input from user with nextInt() method
//use the variable int row
int row = inScan.nextInt();
//prompt the user to choose number for the Col from 0 to 16
System.out.println("Choose a number for the columns from 0 to 16");
//take the input from user with nextInt()
//use the variable int col
int col = inScan.nextInt();
if (row != col) {
System.out.println("Run the program again and choose the same number for Row and Col");
System.exit(0);
}
int[][] arr = move(row, col);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}//main method
static int[][] move(int row, int col) {
boolean flag = true;
int count = 1;
int[][] array = new int[row][col];
for (int j = 0; j < array[0].length; j++) {
if (flag) {
for (int i = 0; i < array.length; i++) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = false;
} else {
//row decrement going up
for (int i = array.length - 1; i > 0; i--) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = true;
}
}//column increment
return array;
}//move method
}//end SnakeMove class
Can anyone detect what is causing the error? Any help would be appreciated.
I believe this is a good alternative and easy to understand. Do comment if you have a simplified version of the same.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SnakePatternProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // *INPUT*
int row = scanner.nextInt();
int col = scanner.nextInt();
int[][] array = new int[row][col];
// Initializing first row of the array with a generalized expression
for (int i = 0; i < col; i++) {
if (i % 2 != 0) array[0][i] = col * (i+1);
else array[0][i] = (col * i) + 1;
}
array[0][0] = 1; // this element is not covered in the above loop.
// Nested loop for incrementing and decrementing as per the first row of elements.
for (int i= 1; i< row; i++){
for (int j=0; j< col; j++){
if(j%2==0) array[i][j] = array[i-1][j] + 1;
else array[i][j] = array[i-1][j] - 1;
}
}
System.out.println(Arrays.deepToString(array)); // *OUTPUT
}
}
Explanation:
Consider first row of 5 x 5 matrix named "arr" with snake pattern:
1 10 11 20 21
The element in the odd column is equivalent to ((currentColumn + 1) * Total_No_Of_columns);
Example: arr[0][1] = (1 + 1)* 5 = 10
The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;
Example: arra[0][2] = (2 * 5) + 1 = 11;
Important Note: element at first row, first column is Zero
arr[0][0] = 1 -> must be declared
Now, the remaining matrix is incrementing or decrementing loop from the first element in that column.
Elements with even column number gets incremented by 1 in each row from the first element of that column.
1 -> First element of column-0
2 -> (1 + 1)
3 -> (2 + 1).... so on
4
5
Elements with odd column number gets decremented by 1 in each row from the first element of that column.
10 -> First element of column - 1
9 -> (10 - 1)
8 -> (9 - 1).... so on
7
6
This will generate the "snaking" pattern you described.
It could be simplified with ternary but this makes it more readable I think
It would be interesting to find a more clever way about it though, if anyone finds a better way pls comment
public static int[][] genArray(int length) {
int[][] arr = new int[length][length];
int counter = 0;
for (int col = 0; col < arr.length; col++) {
if (col % 2 == 0) {
for (int row = 0; row < arr.length; row++) {
arr[row][col] = counter++;
}
} else {
for (int row = arr.length - 1; row >= 0; row--) {
System.out.println("row: " + row + ", col: " + col);
arr[row][col] = counter++;
}
}
}
}
return arr;
}
You can create such an array as follows:
int m = 5;
int n = 4;
int[][] snakeArr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, m)
// even row - straight order,
// odd row - reverse order
.map(j -> (i % 2 == 0 ? j : m - j - 1) + i * m + 1)
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(snakeArr)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
Transposing snake array:
int[][] transposedSA = new int[m][n];
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j ->
transposedSA[i][j] = snakeArr[j][i]));
// output
Arrays.stream(transposedSA)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 10 11 20
2 9 12 19
3 8 13 18
4 7 14 17
5 6 15 16
An easy way to do it is to create a 2-D array as shown below and then print its transpose.
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
It is a 2-D array of the dimension, LEN x LEN, where LEN = 5.
The above pattern goes like this:
The pattern starts with a start value of 1.
When the main loop counter is an even number, the counter, which assigns a value to the array, starts with start value and increases by one, LEN times. Finally, it sets start for the next row to start with final_value_of_the_array_value_assignment_counter - 1 + LEN.
When the main loop counter is an odd number, the counter, which assigns a value to the array, starts with start value and decreases by one LEN times. Finally, it sets start for the next row to start with start + 1.
The transpose of the above matrix will look like:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
In terms of code, we can write it as:
public class Main {
public static void main(String[] args) {
final int LEN = 5;
int[][] arr = new int[LEN][LEN];
int start = 1, j, k, col;
for (int i = 0; i < LEN; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start, col = 0; k <= LEN; j++, k++, col++) {
arr[i][col] = j;
}
start = j - 1 + LEN;
} else {
k = 1;
for (j = start, col = 0; k <= LEN; j--, k++, col++) {
arr[i][col] = j;
}
start++;
}
}
// Print the transpose of the matrix
for (int r = 0; r < LEN; r++) {
for (int c = 0; c < LEN; c++) {
System.out.print(arr[c][r] + "\t");
}
System.out.println();
}
}
}
Output:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
Change the value of LEN to 10 and you will get the following pattern:
1 20 21 40 41 60 61 80 81 100
2 19 22 39 42 59 62 79 82 99
3 18 23 38 43 58 63 78 83 98
4 17 24 37 44 57 64 77 84 97
5 16 25 36 45 56 65 76 85 96
6 15 26 35 46 55 66 75 86 95
7 14 27 34 47 54 67 74 87 94
8 13 28 33 48 53 68 73 88 93
9 12 29 32 49 52 69 72 89 92
10 11 30 31 50 51 70 71 90 91

Pascaline triangle logic not working in java

I am trying to make a java program to print the Pascaline triangle. But it is not working properly. The code is provided below :
int rows=10;
int[] array=new int[10], temp=new int[10];
array[0]=1;
temp[0]=1;
System.out.println(1);
for(int i=1;i<rows;i++)
{
for(int j=1;j<=i;j++)
{
temp[j]=array[j-1]+array[j];
}
for(int term:temp)
{
System.out.print(term+"\t");
}
System.out.println();
array=temp;
}
It is giving the following output :
1
1 1
1 2 3
1 3 5 5
.....
Please tell what's wrong with the code.
Pascaline triangle is not factorial serial
A proposal is (warning I am not a Java programmer, please don't be rude with me if something is stupid / can be improved easily) :
public class Pascaline {
public static void main(String args[]) {
int n = 10, i, j;
int [] f = new int[n];
f[0] = 1;
for (i = 1; i != n; i++)
f[i] = f[i - 1] * i;
for(i = 0; i < n; i++) {
for(j = 0; j <= i; j++)
System.out.print((f[i] / (f[i - j] * f[j])) + " ");
System.out.println();
}
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ javac Pascaline.java
pi#raspberrypi:/tmp $ java Pascaline
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
and to be a little prettier :
public class Pascaline {
public static void main(String args[]) {
int n = 10, i, j;
int [] f = new int[n];
f[0] = 1;
for (i = 1; i != n; i++)
f[i] = f[i - 1] * i;
for(i = 0; i < n; i++) {
for(j = 0; j < n-i; j++)
System.out.print(" ");
for(j = 0; j <= i; j++)
System.out.print((f[i] / (f[i - j] * f[j])) + " ");
System.out.println();
}
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ javac Pascaline.java
pi#raspberrypi:/tmp $ java Pascaline
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

Java Multiplication Table

I'm making a java program that shows the multiplication table that looks like this:
1
But I can only get the results from 1 to 5th column. How do I make the rest appear below ?
The program must only contain one for() nested loop.
This is my code so far:
import java.util.Scanner;
public class Table{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int inputi = s.nextInt();
for(int i = 1 ;i<=10;i++) {
for(int j=1;j<=inputi && j <= 5;j++) {
System.out.print(j + " x " + i + " = " +(i*j) + "\t");
}
System.out.println();
if(i >= 5)
for(int j = 6; j <= inputi && j <= 10; j++){
System.out.print(j + " x " + i + " = " +(i*j) + "\t");
}
}
System.out.println();
System.out.println();
}
}
Can anyone help ?
Thanks.
Edit: Sample input added.
Inputi = 7
Expected output:
Actual output:
I would suggest to
Create separate variable with number of required columns
Calculate how many rows will be printed (see iterations)
Print rows one by one
Please, see the code snippet below:
int inputi = 12;
int columns = 5;
int iterations = inputi / columns + (inputi % columns > 0 ? 1 : 0);
for (int iter = 0; iter < iterations; iter++) {
for (int i = 1; i <= 10; i++) {
for (int j = iter * columns + 1; j <= Math.min(inputi, (iter + 1) * columns); j++) {
System.out.print(j + " x " + i + " = " +(i * j) + "\t\t");
}
System.out.println();
}
System.out.println();
}
Note, in case inputi is huge, you may have to fill outputs with additional spaces, to avoid layout issues, when you have statements like 1 x 1 = 1 and 1 x 10000000 = 1000000
This algorithm with only 2 layers of for loops will give you the correct output.
import java.util.Scanner;
public class Table {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int inputi = s.nextInt();
for(int i = 0; i < Math.ceil(inputi / 5.0) * 10; i++) {
if ( i > 0 && i % 10 == 0 ) System.out.println();
int t = inputi - 5 * (i / 10);
for(int j = 0; j < (t > 5 ? 5 : t); j++) {
int a = 5 * (i / 10) + j + 1;
int b = i % 10 + 1;
System.out.print(a + " x " + b + " = " + (a * b) + "\t");
}
System.out.println();
}
}
}
Here is the sample output for input=11:
1 x 1 = 1 2 x 1 = 2 3 x 1 = 3 4 x 1 = 4 5 x 1 = 5
1 x 2 = 2 2 x 2 = 4 3 x 2 = 6 4 x 2 = 8 5 x 2 = 10
1 x 3 = 3 2 x 3 = 6 3 x 3 = 9 4 x 3 = 12 5 x 3 = 15
1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16 5 x 4 = 20
1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25
1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40
1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45
1 x 10 = 10 2 x 10 = 20 3 x 10 = 30 4 x 10 = 40 5 x 10 = 50
6 x 1 = 6 7 x 1 = 7 8 x 1 = 8 9 x 1 = 9 10 x 1 = 10
6 x 2 = 12 7 x 2 = 14 8 x 2 = 16 9 x 2 = 18 10 x 2 = 20
6 x 3 = 18 7 x 3 = 21 8 x 3 = 24 9 x 3 = 27 10 x 3 = 30
6 x 4 = 24 7 x 4 = 28 8 x 4 = 32 9 x 4 = 36 10 x 4 = 40
6 x 5 = 30 7 x 5 = 35 8 x 5 = 40 9 x 5 = 45 10 x 5 = 50
6 x 6 = 36 7 x 6 = 42 8 x 6 = 48 9 x 6 = 54 10 x 6 = 60
6 x 7 = 42 7 x 7 = 49 8 x 7 = 56 9 x 7 = 63 10 x 7 = 70
6 x 8 = 48 7 x 8 = 56 8 x 8 = 64 9 x 8 = 72 10 x 8 = 80
6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81 10 x 9 = 90
6 x 10 = 60 7 x 10 = 70 8 x 10 = 80 9 x 10 = 90 10 x 10 = 100
11 x 1 = 11
11 x 2 = 22
11 x 3 = 33
11 x 4 = 44
11 x 5 = 55
11 x 6 = 66
11 x 7 = 77
11 x 8 = 88
11 x 9 = 99
11 x 10 = 110
This will give you the desired output:
import java.util.Scanner;
public class Table{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int inputi = s.nextInt();
for(int i = 1 ;i<=10;i++) {
for(int j=1;j<=inputi && j <= 5;j++) {
System.out.print(j + " x " + i + " = " +(i*j) + "\t");
}
System.out.println();
}
System.out.println();
System.out.println();
for(int i = 1 ;i<=10;i++) {
for(int j=6;j<=inputi && j <= 10;j++) {
System.out.print(j + " x " + i + " = " +(i*j) + "\t");
}
System.out.println();
}
}
}

How read array from a file

im trying to create a matrix from a file, the file is like this:
Where my first line has the size of the matrix= 10 x 9
And in the other lines, we have 15 values distributed aleatory.
3 5
4 5 6
12 34 12 12 8
34 23
12 34 34 10 89
With the info size i will define my matriz. I use this method for read:
public static void read(){
String line= "";
int i = 0;
try {
while((line = bf.readLine()) != null){
if (i == 0){
//Call method that get the size and create my global matriz
}else{
String[] list = line.split(" ");
//I need help here, for insert correctly in the array
}
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How i can do for insert orderly in the matrix? My matrix should be like:
4 5 6 12 34
12 12 8 34 23
12 34 34 10 89
Any idea?
This is one way to do it:
String input = "3 5\n" +
"4 5 6\n" +
"12 34 12 12 8\n" +
"34 23\n" +
"12 34 34 10 89\n";
Scanner in = new Scanner(input);
final int rows = in.nextInt();
final int cols = in.nextInt();
int[][] matrix = new int[rows][cols];
int row = 0, col = 0;
for (int i = 0; i < rows * cols; i++) {
matrix[row][col] = in.nextInt();
if (++col == cols) {
row++;
col = 0;
}
}
System.out.println(Arrays.deepToString(matrix));
Output:
[[4, 5, 6, 12, 34], [12, 12, 8, 34, 23], [12, 34, 34, 10, 89]]
It is not necessarily the best way to do it, but I wanted to show the manual increment logic of col and row, where row is incremented when col rolls over.
Using answer by sebenalern, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = in.nextInt();
Using answer by Paul, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows * cols; i++)
matrix[i / 5][i % 5] = in.nextInt();
All 3 versions rely on the Scanner to simply provide all the values in a sequence, regardless of how they were put together on lines.
If you don't want to use Scanner (e.g. because it is slow), and read the input line-by-line, then values on a line, the 1st version would be easier to use. Otherwise the 3rd is the shortest, and the 2nd version is the most straightforward.
Just a hint - I'll leave your homework to you - :
In this case it would be pretty simple to maintain a counter of all values that have been read so far, and map each of these counter-values to a matrix-value like this:
0 = (0 , 0)
1 = (1 , 0)
...
5 = (0 , 1)
6 = (1 , 1)
...
Using something like this:
int row = counter / rowLength;
int col = counter % rowLength;
In your case:
matrix[counter/5][counter%5] = someValue;

Set large array of numbers to designated length per line

int size = 50;
// Generates non-duplicated random numbers
int[] values = new int[51];
int[] list = new int[size];
for( int i = 0; i < 51; i++ )
values[i] = i;
Random rand = new Random();
int listSize = 0;
int myList = 0;
while( true )
{
int value = rand.nextInt(51);
if( values[ value ] == 0 )
continue; // number already used
list[ myList++ ] = value;
values[ value ] = 0;
if( myList == size || myList == 50 )
break;
}
// Displays non-duplicated random generated numbers
for(int element : list)
System.out.print(element + " ");
I would like to set a large array of numbers to a designated length per line to make all the numbers appear as though they're in a block with the left and right sides even like so:
> 1 2 3 4 5 6 7 8 9 10
> 11 12 13 14 15 16 17 18 19 20
> 21 22 23 24 25 26 27 28 29 30
> 31 32 33 34 35 36 37 38 39 40
> 41 42 43 44 45 46 47 48 49 50
How do I accomplish this using an enhanced for loop? Thanks for your help!
Add a new line after read 10 value
for(int i=0; i<list.length; i++){
System.out.printf(" %-2d",list[i]); //Format left justified
if ((i+1)%10==0){
System.out.println(); // Add a new line after 10
}
}

Categories