diff --git a/.gitignore b/.gitignore index 1dc9768..a69deae 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,101 @@ +<<<<<<< HEAD + +# Created by https://www.gitignore.io/api/java,intellij +# Edit at https://www.gitignore.io/?templates=java,intellij + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# IntelliJ IDEA folder +.idea/ + +#module +rujnster.iml + +# Sonarlint plugin +.idea/sonarlint + +### Java ### +# Compiled class file +*.class +======= # Compiled class file *.class out/ +>>>>>>> 1bee331b085ecfea6a7af0e9719010f1626939b0 # Log file *.log @@ -23,8 +118,12 @@ out/ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* +<<<<<<< HEAD +# End of https://www.gitignore.io/api/java,intellij +======= # Git git.properties # IntelliJ IDEA folder .idea/ +>>>>>>> 1bee331b085ecfea6a7af0e9719010f1626939b0 diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index a165cb3..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index a0733a5..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/project.iml b/.idea/project.iml deleted file mode 100644 index 47baa8c..0000000 --- a/.idea/project.iml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/in.txt b/in.txt new file mode 100644 index 0000000..b0bf574 --- /dev/null +++ b/in.txt @@ -0,0 +1,4 @@ +3 +1 1 2 9 +2 4 -3 1 +3 6 -5 0 \ No newline at end of file diff --git a/out.txt b/out.txt new file mode 100644 index 0000000..621678b --- /dev/null +++ b/out.txt @@ -0,0 +1 @@ +1.0 2.0 3.0 \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..17be857 --- /dev/null +++ b/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + hyperskill + ru.jnster + 1.0-SNAPSHOT + + + + junit + junit + 4.12 + test + + + + \ No newline at end of file diff --git a/src/solver/Main.java b/src/solver/Main.java deleted file mode 100644 index 4404714..0000000 --- a/src/solver/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -package solver; - -public class Main { - public static void main(String[] args) { - System.out.print("Hello world!"); - } -} \ No newline at end of file diff --git a/src/solver/java/GaussianElimintation/GaussianElimintation.java b/src/solver/java/GaussianElimintation/GaussianElimintation.java new file mode 100644 index 0000000..64ed364 --- /dev/null +++ b/src/solver/java/GaussianElimintation/GaussianElimintation.java @@ -0,0 +1,96 @@ +package GaussianElimintation; + +/** + * Класс для нахлждения вектора решений системы уравнений методом Гаусса + */ + +public class GaussianElimintation { + private Matrix matrix; + private double result[]; + private int N; + + public GaussianElimintation(double[][] matrix) { + setMatrix(matrix); + } + + public GaussianElimintation(Double[][] matrix) { + setMatrix(matrix); + } + + public GaussianElimintation(Matrix matrix) { + setMatrix(matrix); + } + + public double[] findAnswer() { + double coefficient; + result = new double[N--]; + for (int counter = 0; counter < N; counter++) { + for (int next = counter + 1; next <= N; next++) { + coefficient = matrix.getElement(next, counter) / matrix.getElement(counter, counter) * -1; + matrix.addRow(coefficient, counter, next, counter); + } + } + for (int counter = N; counter >= 0; counter--) { + result[counter] = (matrix.getElement(counter, N + 1) - calculate(counter)) / matrix.getElement(counter, counter); + } + return result; + } + + /** + * Проверяет является ли матрица квадратной. Вектор значение после знака равенства не учитывается. + * + * @param matrix Матрица для проверки, включая столбец значений после знака раменства. + * @return true - матрица квадратная, false - нет + */ + public static boolean isSquareMatrix(Matrix matrix) { + boolean result = true; + int N = matrix.getN(); + for (Row row : matrix.getRows()) { + result &= row.getDoubleList().size() == N + 1; + } + return result; + } + + /** + * Вычисление известной части уравнения + * @param stage индекс после которого происходит расчёт + * @return сумма известных частей полинома + */ + private double calculate(int stage) { + double result = 0.0; + if (stage != N) { + for (int counter = stage + 1; counter <= N; counter++) { + result += matrix.getElement(stage, counter) * this.result[counter]; + } + } + return result; + } + + public void setMatrix(double[][] matrix) { + setMatrix(new Matrix(matrix)); + } + + public void setMatrix(Double[][] matrix) { + setMatrix(new Matrix(matrix)); + } + + public void setMatrix(Matrix matrix) { + try { + if (!isSquareMatrix(matrix)) throw new RuntimeException("This matrix is not square matrix."); + } catch (RuntimeException re) { + re.printStackTrace(); + } + this.matrix = matrix; + N = this.matrix.getN(); + result = null; + } + + public Matrix getMatrix() { + return matrix; + } + + public double[] getResult() { + if (result == null) result = findAnswer(); + return result; + } +} diff --git a/src/solver/java/GaussianElimintation/Main.java b/src/solver/java/GaussianElimintation/Main.java new file mode 100644 index 0000000..cd7cb34 --- /dev/null +++ b/src/solver/java/GaussianElimintation/Main.java @@ -0,0 +1,55 @@ +package GaussianElimintation; + +import java.io.*; + +/** + * Обязательные аргументы запуска это флаги "-in" и "-out", после которых следует имя файла с исходными данными или + * имя файла для вывода значения сооттветственно. + */ + +public class Main { + public static void main(String[] args) { + BufferedReader in = null; + BufferedWriter out = null; + double[][] matrix; + double[] result; + String[] buffer; + int N; + GaussianElimintation gaussianElimintation; + + try { + for (int counter = 0; counter < 4; counter++) { + if (args[counter].equals("-in")) { + in = new BufferedReader(new FileReader(args[++counter])); + } + if (args[counter].equals("-out")) { + out = new BufferedWriter(new FileWriter(args[++counter])); + } + } + + if (in == null || out == null) return; + + buffer = in.readLine().split(" "); + N = Integer.parseInt(buffer[0]); + matrix = new double[N][]; + + for (int row = 0; row < N; row++) { + matrix[row] = new double[N + 1]; + buffer = in.readLine().split(" "); + for (int column = 0; column <= N; column++) { + matrix[row][column] = Double.parseDouble(buffer[column]); + } + } + in.close(); + gaussianElimintation = new GaussianElimintation(matrix); + result = gaussianElimintation.findAnswer(); + for (int counter = 0; counter < N; counter++) { + out.append(Double.toString(result[counter]) + " "); + } + out.close(); + System.out.println("Completed!"); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/solver/java/GaussianElimintation/Matrix.java b/src/solver/java/GaussianElimintation/Matrix.java new file mode 100644 index 0000000..4d50c24 --- /dev/null +++ b/src/solver/java/GaussianElimintation/Matrix.java @@ -0,0 +1,85 @@ +package GaussianElimintation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Класс матрицы, поддерживающий только элементарные преобразования умножения и складывания только со строками матрицы. + */ + +public class Matrix { + private List rows; + private int N; + + public Matrix(double[][] matrix) { + rows = new ArrayList(); + for (double[] row : matrix) { + rows.add(new Row(row)); + } + N = rows.size(); + } + + public Matrix(Double[][] matrix) { + rows = new ArrayList(); + for (Double[] row : matrix) { + rows.add(new Row(row)); + } + N = rows.size(); + } + + public Matrix(Row... rows) { + this.rows = new ArrayList(Arrays.asList(rows)); + N = this.rows.size(); + } + + public Matrix(LinearEquation... linearEquations) { + rows = new ArrayList(); + for (LinearEquation linearEquation : linearEquations) { + rows.add(new Row(linearEquation)); + } + N = rows.size(); + } + + public Matrix addRow(int whatIndex, int toIndex) { + return addRow(1, whatIndex, toIndex, 0); + } + + public Matrix addRow(int whatIndex, int toIndex, int skipFirst) { + return addRow(1, whatIndex, toIndex, skipFirst); + } + + public Matrix addRow(double coefficient, int whatIndex, int toIndex, int skipFirst) { + return addRow(coefficient, rows.get(whatIndex), rows.get(toIndex), skipFirst); + } + + public Matrix addRow(Row what, Row to, int skipFirst) { + return addRow(1, what, to, skipFirst); + } + + public Matrix addRow(Row what, Row to) { + return addRow(1, what, to, 0); + } + + public Matrix addRow(double coefficient, Row what, Row to, int skipFirst) { + to.add(what, coefficient, skipFirst); + return this; + } + + public List getRows() { + return rows; + } + + public Double getElement(int rowIndex, int columnIndex) { + return rows.get(rowIndex).getDouble(columnIndex); + } + + public int getN() { + return N; + } + + public void setRows(List rows) { + this.rows = rows; + N = this.rows.size(); + } +} diff --git a/src/solver/java/GaussianElimintation/Row.java b/src/solver/java/GaussianElimintation/Row.java new file mode 100644 index 0000000..3616243 --- /dev/null +++ b/src/solver/java/GaussianElimintation/Row.java @@ -0,0 +1,64 @@ +package GaussianElimintation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Класс строки матрицы или же представление линейного уравнения через вектор коэффициентов + */ + +public class Row { + private List doubleList; + + public Row(double... array) { + doubleList = new ArrayList(); + for (double one : array) { + doubleList.add(one); + } + } + + public Row(Double... array) { + doubleList = new ArrayList<>(Arrays.asList(array)); + } + + public Row(LinearEquation linearEquation) { + doubleList = new ArrayList<>(linearEquation.coefficients); + doubleList.add(linearEquation.rightSide); + } + + public void add(Row row) { + add(row, 1, 0); + } + + public void add(Row row, double coefficient) { + add(row, coefficient, 0); + } + + public void add(Row row, double coefficient, int skipFirst) { + Double[] to = new Double[doubleList.size()], + what = new Double[row.doubleList.size()]; + to = doubleList.toArray(to); + what = row.doubleList.toArray(what); + for (int counter = skipFirst; counter < doubleList.size(); counter++) { + to[counter] += what[counter] * coefficient; + } + doubleList = new ArrayList<>(Arrays.asList(to)); + } + + public Double getDouble(int index) { + return doubleList.get(index); + } + + public LinearEquation toLinearEquation() { + return new LinearEquation((Double[]) doubleList.toArray()); + } + + public List getDoubleList() { + return doubleList; + } + + public void setDoubleList(List doubleList) { + this.doubleList = doubleList; + } +} diff --git a/src/test/java/GuassianElimintationTest.java b/src/test/java/GuassianElimintationTest.java new file mode 100644 index 0000000..f51e7ee --- /dev/null +++ b/src/test/java/GuassianElimintationTest.java @@ -0,0 +1,16 @@ +import GaussianElimintation.GaussianElimintation; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +public class GuassianElimintationTest { + @Test + public void simpleTest() { + double matrix[][] = {{1.0, 1.0, 2.0, 9.0}, {2.0, 4.0, -3.0, 1.0}, {3.0, 6.0, -5.0, 0.0}}; + double result[] = {1.0, 2.0, 3.0}; + GaussianElimintation gaussianElimintation = new GaussianElimintation(matrix); + Assert.assertTrue(Arrays.equals(result, gaussianElimintation.getResult())); + } + +}