Skip to content
Open
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions src/inr.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
3 3
1+2i -1.5-1.1i 2.12 91+5i
-1+3i 1.2+3.5i -3.3 1+15i
12.31 1.3-5i 12.3i -78.3i
60 changes: 60 additions & 0 deletions src/plan.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
На этой стадии нужно написать программу, которая
1.считывает коэффициенты системы линейных уравнений из файла.
1.1 Первая строка содержит N - число переменных и уравнений.
1.2 Каждая последующая строка - N+1 чисел - N коэффициентов уравнения,
и последнее число - правая часть уравнения - константа.
2.решает систему линейных уравнений
3.записывает ответ в другой файл.
3.1 В файл должны быть записаны только ответы, разделенные "\n".
4.пути к файлам следует передавать как аргументы командной строки.
5.Весь процесс решения/преобразований со строками должен быть выведен на консоль.
6.Постарайтесь создать различные классы такие как: Matrix, Row, LinearEquation.
Пример вывода: The lines which start with > represent the user input.

> java Solver -in in.txt -out out.txt
Start solving the equation.
Rows manipulation:
-2 * R1 + R2 -> R2
-3 * R1 + R3 -> R3
0.5 * R2 -> R2
-3 * R2 + R3 -> R3
-2 * R3 -> R3
3.5 * R3 + R2 -> R2
-2 * R3 + R1 -> R1
-1 * R2 + R1 -> R1
The solution is: (1.0, 2.0, 3.0)
Saved to file out.txt

Алгоритм преобразований.
1.Обнулить все коэффициенты первого столбца кроме первого, он должен стать = 1.
2.Последовательно обнулить все коэффициенты второго и последующего столбцов
пока в последней строке все коэффициенты не обнулятся кроме последнего столбца.
3.Вторая часть алгоритма - обнулять коэффициенты выше диагонали,
начиная с последней строки до первой.
4.После этих преобразований решением уравнений будет правая часть матрицы.
Стадия 4.
Может быть случай, когда коэффициент, на который мы будем умножать будет равен 0.
Поэтому перед операцией умножения нужно проверить, коэффициент на равенство 0.
Если нужно искать ненулевой элемент ниже и правее.
1. Если ненулевой элемент ниже, то нужно переставить строки местами
2. Если ниже все элементы нулевые, то продолжаем искать правее
от элемента. Если находим, переставляем столбцы,строки.
Состояние столбцов/строк до перестановки необходимо запомнить,
чтобы после реализации вернуть все на место в исходном порядке и
вывести решение в нужном порядке. В общей сложности может быть
много перестановок.
Если ненулевой элмент не находится ниже и правее, то ищется
ненулевой элемент по всей левой части матрицы и при нахождении
переставляем соответствущие строки и столбцы.
Если ненулевой элемент не найден, первая часть алгоритма завершается.

После этого проверяем на количество решений.
1. все коэффициенты левой части нулевые, п.ч. ненулевая - нет решений.
2. если количество ненулевых элементов на главной диагонали
совпадает с количеством уравнений (в п.ч. не нули) - одно решение
3. если на главной дигонали есть нулевые элементы + в п.ч.нули
-> бесконечно много решений.
C1,C2,C3(1<->2)C2,C1,C3(1<->3)C3,C1,C2
colMove[1]=3
colMove[2]=1
colMove[3]=2
135 changes: 135 additions & 0 deletions src/solver/ComplexNumber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package solver;

public class ComplexNumber {

public void set(double re, double im) {
this.re = re;
this.im = im;
}

private double re;//действительная часть
private double im;//мнимая часть

public double getRe() {
return re;
}

public double getIm() {
return im;
}

public ComplexNumber(double re, double im) {
this.re = re;
this.im = im;
}

public ComplexNumber(ComplexNumber n){
this.re = n.re;
this.im = n.im;
}

public ComplexNumber(String number) throws ParsingArrayException {
try {
if (number==null) {
this.re = 0;
this.im = 0;
} else if (!number.contains("i")) {
this.re = Double.parseDouble(number);
this.im = 0;
} else {
boolean firstPositive = true;
boolean secondPositive = true;
if (number.charAt(0) == '-') // See if first expr is negative
firstPositive = false;
if (number.substring(1).contains("-"))
secondPositive = false;
String[] split = number.split("[+-]");
if (split[0].equals("")) { // Handle expr beginning with `-`
split[0] = split[1];
if (split[0].contains("i")) {
split[0] = "0";
secondPositive = firstPositive;
}
if (split.length>2) split[1] = split[2];
}
double realPart = 0;
double imgPart = 0;
if (split[0].contains("i")) // Assumes input is not empty
imgPart = Double.parseDouble((firstPositive ? "+" : "-") +
split[0].substring(0,split[0].length() - 1));
else
realPart = Double.parseDouble((firstPositive ? "+" : "-") + split[0]);
if (split.length > 1) { // Parse second part of expr if it exists
if (split[1].contains("i"))
imgPart = Double.parseDouble((secondPositive ? "+" : "-") +
split[1].substring(0,split[1].length() - 1));
else
realPart = Double.parseDouble((secondPositive ? "+" : "-") + split[1]);
}
this.re = realPart;
this.im = imgPart;
}
} catch (NumberFormatException e) {
throw new ParsingArrayException(String.format("The string '%s' cannot be parsed as complex number", number),
e);
}
}

public static ComplexNumber sAdd(ComplexNumber n1, ComplexNumber n2){
return new ComplexNumber(n2.re+n1.re, n1.im+n2.im);
}

public void add(ComplexNumber n){
this.re+=n.re;
this.im+=n.im;
}

public void mult(ComplexNumber n){
//(a+bi)(c+di) = (ac−bd) + (ad+bc)i;
this.re=this.re*n.re-this.im*n.im;
this.im=this.re*n.im+this.im*n.re;
}

public static ComplexNumber mult(ComplexNumber n1, ComplexNumber n2){
//(a+bi)(c+di) = (ac−bd) + (ad+bc)i;
double re;
double im;
re=n1.re*n2.re-n1.im*n2.im;
im=n1.re*n2.im+n1.im*n2.re;
return new ComplexNumber(re,im);
}

public void div(ComplexNumber n){
//a+bi/c+di = (ac+bd)/(c^2+d^2)+(bc-ad)/((c^2+d^2))i
double a= this.re;
double b =this.im;
double c= n.re;
double d= n.im;
this.re = (a*c+b*d)/(c*c+d*d);
this.im = (b*c-a*d)/(c*c+d*d);
}

public static ComplexNumber div(ComplexNumber n1,ComplexNumber n2){
//a+bi/c+di = (ac+bd)/(c^2+d^2)+(bc-ad)/((c^2+d^2))i
double a= n1.re;
double b =n1.im;
double c= n2.re;
double d= n2.im;
double re = (a*c+b*d)/(c*c+d*d);
double im = (b*c-a*d)/((c*c+d*d));
return new ComplexNumber(re, im);
}

@Override
public String toString() {
return (re==0&&im==0)?"0":(re==0?"":String.format("%-5.3f",re))+((im>0&&re!=0)?"+":"")+(im==0?"":String.format("%-5.3fi ",im));
}

public static boolean compareComplex(ComplexNumber n1, ComplexNumber n2){
return Matrix.compareDouble(n1.getRe(),n2.getRe()) && Matrix.compareDouble(n1.getIm(),n2.getIm());
}

public static boolean compareComplexToDouble(ComplexNumber n1, double n2){
return Matrix.compareDouble(n1.getRe(),n2) && Matrix.compareDouble(n1.getIm(),0);
}
}
7 changes: 7 additions & 0 deletions src/solver/InvalidDataFileFormat.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package solver;

public class InvalidDataFileFormat extends Exception{
public InvalidDataFileFormat(String msg, Exception cause) {
super(msg, cause);
}
}
139 changes: 137 additions & 2 deletions src/solver/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,142 @@
package solver;

import java.io.File;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class Main {
public static void main(String[] args) {
System.out.print("Hello world!");
static String inFile;
static String outFile;
public static void main(String[] args) throws InvalidDataFileFormat {
//get_in_file
if (args.length!=4) {
System.out.println("Invalid comand-line arguments");
return;
}

for (int i = 0; i < args.length; i+=2) {
if (args[i].equalsIgnoreCase("-in"))
inFile = args[i+1];
else if (args[i].equalsIgnoreCase("-out"))
outFile = args[i+1];
}
try {
List<String> lines = Files.readAllLines( Paths.get(inFile));
int n=0,v=0;
int k=0;
try {
for (String s:lines.get(0).split("\\s")) {
if (k==0)
n = Integer.parseInt(s);//количество строк - уравнений
else
v = Integer.parseInt(s);//количество столбцов - переменных
k++;
}
if (v==0) v=n;
}
catch (NumberFormatException e){
throw new InvalidDataFileFormat(
//String.format("The string '%s' cannot be parsed as an array of numbers", s),
String.format("Incorrect data file format, '%s' cannot be parsed as two numbers", lines.get(0)),
e);
}
lines.remove(0);
if (lines.size() != n) {
throw new InvalidDataFileFormat("Incorrect data file format, count of data rows isn't equal n", null);
}
System.out.println("Start solving the equation.\n" +
"Rows manipulation:");
Matrix m;
boolean isComplex = false;
for (String s : lines) {
if (s.contains("i")){
isComplex = true;
break;
}
}
if (isComplex) {
Matrix.isComplx = true;
m = new iMatrix(n, v);
}
else
m = new Matrix(n,v);

for (String line : lines) {
m.addRow(lines.indexOf(line), line);
}
String manipulation;
// m.otladka = true;
m.print();
for (int i = 0; i < m.M; i++) {
while (true)
{
//manipulation = m.rows[i].transform1(i);
manipulation = m.getRows(i).transform1(i);
if (!manipulation.equals("")) {
System.out.println(manipulation);
m.print();
if (!manipulation.contains("<->")) break;
} else break;
};

for (int j = i+1; j < m.N; j++) {
// manipulation = m.rows[j].transform0(i, m.rows[i]);
manipulation = m.getRows(j). transform0(i, m.getRows(i));
if (!manipulation.equals("")) {
System.out.println(manipulation);
m.print();
}
}
}
int check = m.checkSolution();

String result="";
switch (check) {
case 0: {
result = "Infinite solutions";
System.out.println(result);
break;
}
case -1: {
result = "No solutions";
System.out.println(result);
break;
}
case 1: {
System.out.println("-------");
for (int i = m.N - 1; i >= 0; i--) {
for (int j = i - 1; j >= 0; j--) {
// manipulation = m.rows[j].transform0(i, m.rows[i]);
manipulation = m.getRows(j).transform0(i, m.getRows(i));
if (!manipulation.equals("")) {
System.out.println(manipulation);
m.print();
}
}
}
result = m.printSolution();
break;
}
default:break;
}
File file = new File(outFile);
try (FileWriter writer = new FileWriter(file)) {
writer.write(result);
System.out.printf("Saved to file %s\n",outFile);
} catch (IOException e) {
System.out.printf("File writing error %s", e.getMessage());
}

}
catch (IOException e){
System.out.println("File reading error: " + inFile);
}
catch (InvalidDataFileFormat | ParsingArrayException e){
System.out.println(e.getMessage());
}
}
}
Loading