Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- import static java.lang.Math.abs;
- import static java.lang.Math.round;
- public class Main {
- public static void main(String[] args) {
- SquareMatrix m = new SquareMatrix(readMatrix());
- System.out.println(round(m.getDeterminant()));
- }
- private static int[][] readMatrix() {
- Scanner scanner = new Scanner(System.in);
- int n = scanner.nextInt();
- int[][] result = new int[n][n];
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++)
- result[i][j] = scanner.nextInt();
- return result;
- }
- }
- class SquareMatrix {
- private Vector[] x;
- private double get(int i, int j) {
- return x[i].get(j);
- }
- private void set(int i, int j, double value) {
- x[i].set(j, value);
- }
- private SquareMatrix() {
- }
- private SquareMatrix(int n) {
- x = new Vector[n];
- for (int i = 0; i < n; i++)
- x[i] = new Vector(n);
- }
- SquareMatrix(int[][] a) {
- this(a.length);
- if (!Arrays.stream(a).allMatch(i -> i.length == x.length))
- throw new RuntimeException("Dimensions are not equal.");
- for (int i = 0; i < x.length; i++)
- for (int j = 0; j < x.length; j++)
- set(i, j, a[i][j]);
- }
- private SquareMatrix deepClone() {
- SquareMatrix result = new SquareMatrix();
- result.x = Arrays.stream(x)
- .map(Vector::deepClone)
- .toArray(Vector[]::new);
- return result;
- }
- double getDeterminant() {
- double result = 1;
- SquareMatrix m = deepClone();
- for (int k = 0; k < m.x.length; k++) {
- if (!m.swapToMaxRow(k))
- return 0;
- for (int i = k + 1; i < m.x.length; i++) {
- double d = m.get(i, k) / m.get(k, k);
- set(i, k, 0);
- for (int j = k + 1; j < m.x.length; j++)
- m.x[i].x[j] -= d * m.get(k, j);
- }
- result *= m.get(k, k);
- }
- return result;
- }
- private boolean swapToMaxRow(int k) {
- int index = k;
- double max = abs(get(k, k));
- for (int j = k + 1; j < x.length; j++) {
- double d = abs(get(j, k));
- if (d > max) {
- max = abs(get(j, k));
- index = j;
- }
- }
- if (max == 0)
- // the matrix is degenerate
- return false;
- if (index != k) {
- negateRow(k);
- swapRows(k, index);
- }
- return true;
- }
- private void swapRows(int i, int j) {
- Vector temp = x[i];
- x[i] = x[j];
- x[j] = temp;
- }
- private void negateRow(int i) {
- x[i].negate();
- }
- }
- class Vector {
- double[] x;
- double get(int i) {
- return x[i];
- }
- void set(int i, double value) {
- x[i] = value;
- }
- Vector(int n) {
- x = new double[n];
- }
- private Vector(double... a) {
- x = a;
- }
- Vector deepClone() {
- return new Vector(x.clone());
- }
- void negate() {
- x = Arrays.stream(x).map(x -> -x).toArray();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement