Created
August 20, 2024 11:30
-
-
Save yahorbarkouski/4e901ebfcb1ce8836f2f2d996f490986 to your computer and use it in GitHub Desktop.
ArrayUtils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArrayUtils { | |
public static int[][] removeRow(int[][] array, int row) { | |
if (array == null || array.length == 0 || row < 0 || row >= array[0].length) { | |
return array; | |
} | |
int[][] newArray = new int[array.length][array[0].length - 1]; | |
for (int i = 0; i < array.length; i++) { | |
for (int j = 0, k = 0; j < array[0].length; j++) { | |
if (j != row) { | |
newArray[i][k++] = array[i][j]; | |
} | |
} | |
} | |
return newArray; | |
} | |
public static int[][] removeColumn(int[][] array, int column) { | |
if (array == null || column < 0 || column >= array.length) { | |
return array; | |
} | |
int[][] newArray = new int[array.length - 1][]; | |
for (int i = 0, j = 0; i < array.length; i++) { | |
if (i != column) { | |
newArray[j++] = array[i]; | |
} | |
} | |
return newArray; | |
} | |
public static int sum(int[][] array) { | |
if (array == null) { | |
return 0; | |
} | |
int totalSum = 0; | |
for (int[] row : array) { | |
for (int value : row) { | |
totalSum += value; | |
} | |
} | |
return totalSum; | |
} | |
public static int[][] multiplyMatrix(int[][] matrix1, int[][] matrix2) { | |
if (matrix1 == null || matrix2 == null || matrix1[0].length != matrix2.length) { | |
return null; | |
} | |
int rows = matrix1.length; | |
int columns = matrix2[0].length; | |
int[][] result = new int[rows][columns]; | |
for (int i = 0; i < rows; i++) { | |
for (int j = 0; j < columns; j++) { | |
for (int k = 0; k < matrix1[0].length; k++) { | |
result[i][j] += matrix1[i][k] * matrix2[k][j]; | |
} | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment