Switching rows with columns in 2D array - java

So I am trying to figure out how to swap an ith row with the jth column. I have searched everywhere and still cant find a solution similar to what im looking for. (Pretty much switching the first row with the second column) I assume that i am going to have to create a temp to hold the value then swap it, but i can only do it for swapping out a row with another row or column with another column. At this point i am just completely lost. Any suggestions would be appreciated.
what it might look like for better clarification
Input:
2 3 4
1 2 3
4 5 6
Output:
3 2 5
1 3 3
4 4 6
Code :
private int n;
private int [][] Matrix = new int[n][n];
public void switchRowColumn(int i, int j)
{
for(int i=0; i< Matrix.length; i++)
{

I found this working, see if it works for you ...
public class Swap{
public static void main(String[]args){
int [][] array = {
{2,3,4},
{1,2,3},
{4,5,6}
};
swap(array, 0 , 1);
}
public static void swap ( int [][] array, int row, int col){
int [] temprow = new int [array[0].length];
int [] tempcol = new int [array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if(i == row){
temprow = array[i]; // TEMP ROW
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if(j == col){
tempcol[i] = array[i][j];
}
}
}
for (int i = 0; i < tempcol.length; i++) {
System.out.print(tempcol[i]); /// COLS
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if(i == row){
array[i] = tempcol;
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if(j == col){
array[i][j] = temprow[i];
}
}
}
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}

Related

Sudoku check subboxes for duplicates

i have to check the validity of a sudoku as a homework. the rows and cols were no big deal, but i'm stuck at checking the boxes.
i want to loop through the 3x3 sub-boxes and check them for duplicates, with copying the numbers into a smaller 3x3 array, flattening it and then checking it for duplicates.
my while loop doesn't seem to make sense tho, the first iteration works but the second one writes wrong values into my new array. i just don't know where to add my boxcount.
i feel like a noob, if someone can help i'd be thankful
private static boolean isValidSudokuSolution(int[][] sudokuField) {
// TODO: Implementieren Sie hier Ihre Lösung für die Methode
//rows
int row = 0;
while (row < sudokuField.length) {
for (int i = 0; i < sudokuField[row].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[row][i] == sudokuField[row][j]) {
return false;
}
}
}
row++;
}
//cols
int col = 0;
while (col < sudokuField.length) {
for (int i = 0; i < sudokuField[col].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[i][col] == sudokuField[j][col]) {
return false;
}
}
}
col++;
}
//box
int boxCount = 0;
while (boxCount < sudokuField.length) {
//create box array
int[][] box = new int[3][3];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
box[i][j] = sudokuField[i + boxCount][j];
}
}
//flatten box
int[] flattenedBox = new int[sSize];
int counter = 0;
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int num = box[i][j];
flattenedBox[counter + j] = num;
}
counter += 3;
}
//look for duplicates
for (int i = 0; i < flattenedBox.length; i++) {
for (int j = 0; j < i; j++) {
if (flattenedBox[i] == flattenedBox[j]) {
return false;
}
}
}
boxCount += 3;
}
return true;
}

ArrayIndexOutOfBound Exception when reversing array order with multidimensional arrays:

So I'm currently playing around with multidimensional arrays (2D) and I'm trying to reverse the order of each array in a 2-d array.
So I have a 2D-array set as:
int firstArray[][] = {{5,6,7,8,9,10}, {11,12,13,14,15,16}}
I have manually looked through the issue to see where I may have went wrong, to see which part of my code would end up going out of bounds in regards to my for-loops. The -1 part also caught me off guard.
I have began doing reverses on a regular 1-d array, and tried to apply the same concept to multidimensional arrays.
class Test2 {
public static void main (String[] args) {
int firstArray[][] = {{5,6,7,8,9,10}, {10,11, 12, 13, 14, 15}};
System.out.println("FIRST ARRAY");
display(firstArray);
}
public void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num.length-1-j];
num[i][num.length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
}
I want the output using my display method to basically be a reverse of the arrays in my 2-d array:
10 9 8 7 6 5
15 14 13 12 11 10
The issue that I'm getting is an
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
ArrayIndexOutOfBoundsException: -1
at Test2.display(Test2.java:30)
at Test2.main(Test2.java:20)
You are using the length of the wrong dimension.
With num.length you are using the number of rows and not the number of columns of the current row.
You need to change that to num[i].length.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
Notice you wrote num[i][num.length-1-j];
num.length-1-j is basically 2 - 1 -j.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2 ; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}

Matrix multiply in Java

I created a function to multiply a matrix by itself which gets 2 parameters, one is the matrix, the other one is an int n. The problem is that I cant figure out where should I use the n in my code so that it multiplies the matrix by itself an n number of times (in other words matrix^n). At current stage it only does matrix^2;
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * array[x][j];
}
newArray[i][j] = sum;
}
}
return newArray;
}
Add a third for loop that goes from 1 < k < n . You will need to remain array untouched in order to maintain the values of the initial matrix, will also need a matrix newArray to keep the values of the previous multiplication and a temporary matrix tmp that just hold values during the multiplication itself and then is copied to newArray.
Take a look in the sample below.
FULL CODE
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Just holds values during multiplication between two matrices
int[][] tmp = new int[array.length][array.length];
// Initialize newArray to be equal to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
// Outer loop that multiplies as many times as you want
for (int k = 1; k < n; k++) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
tmp[i][j] = sum;
}
}
// Copy the result from multiplication to newArray and restart tmp
System.arraycopy(tmp, 0, newArray, 0, tmp.length);
tmp = new int[array.length][array.length];
}
return newArray;
}
Hope it helped!
You can create two methods for clarity: the first to multiply a square matrix, and the second to call the first n number of times.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = array;
for (int i = 0; i < n; i++) {
newArray = squareMatrixMultiplication(newArray);
}
return newArray;
}
public static int[][] squareMatrixMultiplication(int[][] array) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
for (int x = 0; x < array.length; x++) {
newArray[i][j] += array[i][x] * array[x][j];
}
}
}
return newArray;
}
Initialize newArray to be equal to array, then
add a loop around the matrix multiplication and use newArray in your nested loops: multiply newArray by array.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Add loops to initialize newArray to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
for (int j = 0; j < n; j++) { // Add this loop
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
newArray[i][j] = sum;
}
}
} // and this
return newArray;
}
public class MyClass {
public static void main(String args[]) {
int array[][] = new int[2][2];
array[0][0] = 1;
array[0][1] = 2;
array[1][0] = 3;
array[1][1] = 4;
int newArray[][] = new int[2][2];
//initialize array with these elements
newArray[0][0] = 1;
newArray[0][1] = 0;
newArray[1][0] = 0;
newArray[1][1] = 1;
int n = 5;
for (int i = 0; i < n; i++) {
newArray = lungimeDrumuri(array, newArray, i);
}
}
public static int[][] lungimeDrumuri(int[][] array, int newArray[][], int n) {
int newArray1[][] = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * newArray[x][j];
}
newArray1[i][j] = sum;
}
}
return newArray1;
}
}
Hope this one will help you.

Filling a ragged array with a loop in java

I was wondering how it was possible to fill a ragged array with a loop in Java.
In my example I want to put Pascals Triangle in the Array. When I try to do it ragged, (
// int [][] hako = new int [n][]; -> as I understand it; it gives a java.lang.NullPointerException.
Thanks
int n = 12, r = 1;
int [][] hako = new int [n][];
for(int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
hako[i][j] = newton(i, j);
}
r++;
}
static int factorial(int n){
int k = 1;
if(n == 0)
return 1;
while(n>1){
k*=n;
n--;
}
return k;
}
static int newton(int i, int j){
return factorial(i)/((factorial(j))*(factorial(i-j)));
}
You need to initialize hako[i] as an array before you can assign a variable to an index within it i.e. hako[i][j].
int n = 12, r = 1;
int [][] hako = new int [n][];
for(int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
// need to initialize hako[i]
hako[i] = new int[r];
hako[i][j] = newton(i, j);
}
r++;
}
your hako, is a matrix, but you initialize only one dimension thus your NullPointerException
to fix it try
for(int i = 0; i < n; i++){
hako[i] = new int[r];
for(int j = 0; j < r; j++){
hako[i][j] = newton(i, j);
}
r++;
}
public static void main(String[] args) {
int y[][] = new int[4][];
int four =4;
for (int row = 0; row < y.length; row++) {
y[row] = new int[four--];
}
RaggedArray(y);
for (int row = 0; row < y.length; row++) {
for (int column = 0; column < y[row].length; column++) {
System.out.print(y[row][column] + " ");
}
System.out.println();
}
}
public static void RaggedArray(int x[][]) {
int j;
for (int i = 0; i < x.length; i++) {
int k=1;
for (j = 0;j<x[i].length ; j++) {
x[i][j] = k++;
}
}
}}
You can change the size and fill it with any data. I wish it will be useful for u and anyone see this code.

sorting elements in a row in a 2D array

I have to sort elements in each row and then display the array.
For example, if the input array is:
5 1 3 1 3 5
INPUT: 7 6 4 OUTPUT: 4 6 7
9 8 2 2 8 9
My code for that was:
for (int i = 0; i < size; i++) { //"size" is the size of the square matrix
for (int j = 0; j < size; j++) {
for (int k = 0; k < size - 1; k++) {
for (int l = 0; l < size - k - 1; l++) {
if (arr[i][j] > arr[i][j+1]) { //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
}
}
}
Any suggestions?
for (int i = 0; i < size; i++){ //"size" is the size of the square matrix
for (int j = 0; j < size; j++){
for (int k = j+1; k < size; k++){
if (arr[i][j] > arr[i][k]){ //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][k];
arr[i][k] = temp;
}
}
}
}
I don't think you need 4th loop
I would do it simpler
for(int[] r : arr){
Arrays.sort(r);
}
I would create a method to sort rows, and then just iterate through the rows in the matrix and sort them one at a time. For example:
public static int[] sortRow(int[] row) // selection sort
{
for (int i = 0; i < row.length - 1; i++) {
for (int j = i + 1; j < row.length; j++) {
if (row[i] > row[j]) {
int temp = row[i];
row[i] = row[j];
row[j] = temp;
}
}
}
return row;
}
public static void main(String args[])
{
int[][] arr = {{5, 1, 3}, {7,6,4}, {9,8,2}};
for (int r = 0; r < arr.length; r++) { // for every row in the matrix
arr[r] = sortRow(arr[r]); // set the row to be the sorted row
}
// print out the array to the console
for (int r[] : arr) {
for (int c : r)
System.out.print(c + " ");
System.out.println();
}
}
Output:
1 3 5
4 6 7
2 8 9

Categories