From 65503cc92a4ba659eca0afcd89081db3e3c2b74b Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Mon, 18 Feb 2019 15:18:04 +0300 Subject: [PATCH 01/12] adding new files --- .idea/misc.xml | 2 +- src/in.txt | 4 ++++ src/plan.txt | 23 +++++++++++++++++++++++ src/stage1.java | 11 +++++++++++ src/stage2.java | 19 +++++++++++++++++++ 5 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/in.txt create mode 100644 src/plan.txt create mode 100644 src/stage1.java create mode 100644 src/stage2.java diff --git a/.idea/misc.xml b/.idea/misc.xml index a165cb3..df60b67 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/src/in.txt b/src/in.txt new file mode 100644 index 0000000..b0bf574 --- /dev/null +++ b/src/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/src/plan.txt b/src/plan.txt new file mode 100644 index 0000000..b85c099 --- /dev/null +++ b/src/plan.txt @@ -0,0 +1,23 @@ +На этой стадии нужно написать программу, которая +1.считывает коэффициенты системы линейных уравнений из файла. +2.решает систему линейных уравнений +3.записывает ответ в другой файл. +3.1 +4.пути к файлам следует передвать как аргументы командной строки. +In this stage, you need to write a program that reads coefficients from a file, +solves the system of linear equations and writes the answer to another file. +You should pass paths to files using command-line arguments. +Write to the file only answers separated by "\n". +Output all the steps only to the console, not in the file. + +The first line of the file should contain the number N - a number of variables +being also a number of equations. +Every other N lines contain N+1 numbers - +N coefficients of the current row +and a constant as the last number in this line. +The program also should output all rows manipulation +it is doing during solving the system of linear equations. + +Try to create a various classes +like Matrix, Row, LinearEquation. +With these, the code would be more readable and easier to program. diff --git a/src/stage1.java b/src/stage1.java new file mode 100644 index 0000000..f62be6f --- /dev/null +++ b/src/stage1.java @@ -0,0 +1,11 @@ +import java.util.Scanner; + +public class stage1 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + double a = sc.nextDouble(); + double b = sc.nextDouble(); + //a * x = b + System.out.println(b / a); + } +} diff --git a/src/stage2.java b/src/stage2.java new file mode 100644 index 0000000..9e15f4f --- /dev/null +++ b/src/stage2.java @@ -0,0 +1,19 @@ +import java.util.Scanner; + +public class stage2 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + double a = sc.nextDouble(); + double b = sc.nextDouble(); + double c = sc.nextDouble(); + double d = sc.nextDouble(); + double e = sc.nextDouble(); + double f = sc.nextDouble(); + //a * x + b *y = c + //d * x + e *y = d + double x,y; + y = (f - c*d/a)/(e-b*d/a); + x = (c - b*y)/a; + System.out.println(x+" "+y); + } +} From 0a5bb2307cda92ba1761afe9a03799a326e3d5f8 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Mon, 18 Feb 2019 15:39:50 +0300 Subject: [PATCH 02/12] adding new files --- src/plan.txt | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/src/plan.txt b/src/plan.txt index b85c099..4082be3 100644 --- a/src/plan.txt +++ b/src/plan.txt @@ -1,23 +1,34 @@ На этой стадии нужно написать программу, которая 1.считывает коэффициенты системы линейных уравнений из файла. +1.1 Первая строка содержит N - число переменных и уравнений. +1.2 Каждая последующая строка - N+1 чисел - N коэффициентов уравнения, + и последнее число - правая часть уравнения - константа. 2.решает систему линейных уравнений 3.записывает ответ в другой файл. -3.1 -4.пути к файлам следует передвать как аргументы командной строки. -In this stage, you need to write a program that reads coefficients from a file, -solves the system of linear equations and writes the answer to another file. -You should pass paths to files using command-line arguments. -Write to the file only answers separated by "\n". -Output all the steps only to the console, not in the file. +3.1 В файл должны быть записаны только ответы, разделенные "\n". +4.пути к файлам следует передавать как аргументы командной строки. +5.Весь процесс решения/преобразований со строками должен быть выведен на консоль. +6.Постарайтесь создать различные классы такие как: Matrix, Row, LinearEquation. +Пример вывода: The lines which start with > represent the user input. -The first line of the file should contain the number N - a number of variables -being also a number of equations. -Every other N lines contain N+1 numbers - -N coefficients of the current row -and a constant as the last number in this line. -The program also should output all rows manipulation -it is doing during solving the system of linear equations. +> java Solver -in in.txt -out out.txt +Start solving the equation. +Rows manipulation: +-2 * R1 + R2 -> R2 +-3 * R3 + 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 -Try to create a various classes -like Matrix, Row, LinearEquation. -With these, the code would be more readable and easier to program. +Алгоритм преобразований. +1.Обнулить все коэффициенты первого столбца кроме первого, он должен стать = 1. +2.Последовательно обнулить все коэффициенты второго и последующего столбцов +пока в последней строке все коэффициенты не обнулятся кроме последнего столбца. +3.Вторая часть алгоритма - обнулять коэффициенты выше диагонали, +начиная с последней строки до первой. +4.После этих преобразований решением уравнений будет правая часть матрицы. \ No newline at end of file From 1315eba88ee522fae1ac94f58be275edcf5463de Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Mon, 18 Feb 2019 21:56:02 +0300 Subject: [PATCH 03/12] adding new files --- src/solver/Main.java | 14 ++++++- src/solver/ParsingArrayException.java | 7 ++++ src/solver/Row.java | 56 +++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 src/solver/ParsingArrayException.java create mode 100644 src/solver/Row.java diff --git a/src/solver/Main.java b/src/solver/Main.java index 4404714..5561b27 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -1,7 +1,19 @@ package solver; +import java.io.File; + +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!"); + //System.out.print("Hello world!"); + //get_in_file + + List lines = Files.readAllLines( Paths.get(FILE_NAME)); + for(String line: lines){ + System.out.println(line); + } } } \ No newline at end of file diff --git a/src/solver/ParsingArrayException.java b/src/solver/ParsingArrayException.java new file mode 100644 index 0000000..21393f1 --- /dev/null +++ b/src/solver/ParsingArrayException.java @@ -0,0 +1,7 @@ +package solver; + +public class ParsingArrayException extends Exception{ + public ParsingArrayException(String msg, Exception cause) { + super(msg, cause); + } +} diff --git a/src/solver/Row.java b/src/solver/Row.java new file mode 100644 index 0000000..ac8c9d8 --- /dev/null +++ b/src/solver/Row.java @@ -0,0 +1,56 @@ +package solver; + +public class Row { + private int rowNum; + private double[] data; + public Row(int rowNum, double[] data){ + this.rowNum = rowNum; + this.data = data; + } + + public String getName() { + return "R"+rowNum; + } + public void mult(double koef){ + for (int i = 0; i < data.length; i++) { + data[i]*=koef; + } + } + /*public void divide(double koef){ + for (int i = 0; i < data.length; i++) { + data[i]*=1/koef; + } + }*/ + public void add(Row r){ + for (int i = 0; i < data.length; i++) { + data[i]+=r.data[i]; + } + } + //преобразуем строку, чтобы элемент с индексом index стал = 1 + //возвращаем строку с манипуляцией + public String transform1(int index){ + double koef = 1/this.data[index]; + this.mult(koef); + this.data[index] = 1; + return koef +" * "+this.getName()+" -> "+this.getName(); + } + + public String transform0(int index, Row r){ + double koef = -1 * this.data[index]; + this.data[index] = 0; + return (-1 * koef) + " * "+ r.getName() + " + "+ this.getName()+" -> "+this.getName(); + } + + public void fillRow(String s) throws ParsingArrayException { + String[] str = s.split("\\s+"); + try { + for (int i = 0; i < str.length; i++) { + this.data[i] = Double.parseDouble(str[i]); + } + } catch(NumberFormatException e){ + throw new ParsingArrayException( + String.format("The string '%s' cannot be parsed as an array of numbers", s), + e); + } + } +} From a6d4c3935c090d92368e3598f333ed2736d63572 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Tue, 19 Feb 2019 14:02:13 +0300 Subject: [PATCH 04/12] adding new files --- src/in.txt | 4 --- src/solver/InvalidDataFileFormat.java | 7 ++++ src/solver/Main.java | 46 ++++++++++++++++++++++++--- src/solver/Matrix.java | 26 +++++++++++++++ src/solver/ParsingArrayException.java | 4 +++ src/solver/Row.java | 16 ++++++++-- src/stage1.java | 11 ------- src/stage2.java | 19 ----------- 8 files changed, 92 insertions(+), 41 deletions(-) delete mode 100644 src/in.txt create mode 100644 src/solver/InvalidDataFileFormat.java create mode 100644 src/solver/Matrix.java delete mode 100644 src/stage1.java delete mode 100644 src/stage2.java diff --git a/src/in.txt b/src/in.txt deleted file mode 100644 index b0bf574..0000000 --- a/src/in.txt +++ /dev/null @@ -1,4 +0,0 @@ -3 -1 1 2 9 -2 4 -3 1 -3 6 -5 0 \ No newline at end of file diff --git a/src/solver/InvalidDataFileFormat.java b/src/solver/InvalidDataFileFormat.java new file mode 100644 index 0000000..589a023 --- /dev/null +++ b/src/solver/InvalidDataFileFormat.java @@ -0,0 +1,7 @@ +package solver; + +public class InvalidDataFileFormat extends Exception{ + public InvalidDataFileFormat(String msg, Exception cause) { + super(msg, cause); + } +} diff --git a/src/solver/Main.java b/src/solver/Main.java index 5561b27..99975d5 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -2,18 +2,54 @@ import java.io.File; +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; + } - List lines = Files.readAllLines( Paths.get(FILE_NAME)); - for(String line: lines){ - System.out.println(line); + 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 lines = Files.readAllLines( Paths.get(inFile)); + int n; + try { + n = Integer.parseInt(lines.get(0)); + } + 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 number", lines.get(0)), + e); + } + lines.remove(0); + if (lines.size() != n) { + throw new InvalidDataFileFormat("Incorrect data file format", null); + } + Matrix m = new Matrix(n); + for (String line : lines) { + m.addRow(lines.indexOf(line), line); + } + m.print(); + } + catch (IOException e){ + System.out.println("File reading error: " + inFile); + } + catch (InvalidDataFileFormat | ParsingArrayException e){ + System.out.println(e.getMessage()); } } } \ No newline at end of file diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java new file mode 100644 index 0000000..fdcb4d7 --- /dev/null +++ b/src/solver/Matrix.java @@ -0,0 +1,26 @@ +package solver; + +public class Matrix { + int N;//количество строк и столбцов + Row[] rows; + + public Matrix(int n) { + N = n; + rows = new Row[n]; + } + + public void addRow(int index, String str) throws ParsingArrayException { + this.rows[index] = new Row(index+1, N+1); + this.rows[index].fillRow(str); + } + + public void print(){ + for (Row r:this.rows) { + System.out.println(r.asString()); + } + } + + public double[] getColumn(int index){ + return null; + } +} diff --git a/src/solver/ParsingArrayException.java b/src/solver/ParsingArrayException.java index 21393f1..94c0cfc 100644 --- a/src/solver/ParsingArrayException.java +++ b/src/solver/ParsingArrayException.java @@ -4,4 +4,8 @@ public class ParsingArrayException extends Exception{ public ParsingArrayException(String msg, Exception cause) { super(msg, cause); } + + public ParsingArrayException(String msg) { + super(msg); + } } diff --git a/src/solver/Row.java b/src/solver/Row.java index ac8c9d8..43ed8e4 100644 --- a/src/solver/Row.java +++ b/src/solver/Row.java @@ -1,11 +1,14 @@ package solver; +import java.util.Arrays; + public class Row { private int rowNum; + private int colCnt; private double[] data; - public Row(int rowNum, double[] data){ + public Row(int rowNum, int colCnt/*double[] data*/){ this.rowNum = rowNum; - this.data = data; + this.data = new double[colCnt]; } public String getName() { @@ -53,4 +56,13 @@ public void fillRow(String s) throws ParsingArrayException { e); } } + + + public String asString() { + String s=""; + for (double d:this.data) { + s +=d+" "; + }; + return this.getName()+": "+ s.trim(); + } } diff --git a/src/stage1.java b/src/stage1.java deleted file mode 100644 index f62be6f..0000000 --- a/src/stage1.java +++ /dev/null @@ -1,11 +0,0 @@ -import java.util.Scanner; - -public class stage1 { - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - double a = sc.nextDouble(); - double b = sc.nextDouble(); - //a * x = b - System.out.println(b / a); - } -} diff --git a/src/stage2.java b/src/stage2.java deleted file mode 100644 index 9e15f4f..0000000 --- a/src/stage2.java +++ /dev/null @@ -1,19 +0,0 @@ -import java.util.Scanner; - -public class stage2 { - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - double a = sc.nextDouble(); - double b = sc.nextDouble(); - double c = sc.nextDouble(); - double d = sc.nextDouble(); - double e = sc.nextDouble(); - double f = sc.nextDouble(); - //a * x + b *y = c - //d * x + e *y = d - double x,y; - y = (f - c*d/a)/(e-b*d/a); - x = (c - b*y)/a; - System.out.println(x+" "+y); - } -} From d8c762974a869afdd5e29be51c64f6df748efb36 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Tue, 19 Feb 2019 20:18:30 +0300 Subject: [PATCH 05/12] adding new files --- src/plan.txt | 2 +- src/solver/Main.java | 8 ++++++++ src/solver/Matrix.java | 8 +++++--- src/solver/Row.java | 20 +++++++++++--------- 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/src/plan.txt b/src/plan.txt index 4082be3..ba6b24e 100644 --- a/src/plan.txt +++ b/src/plan.txt @@ -15,7 +15,7 @@ Start solving the equation. Rows manipulation: -2 * R1 + R2 -> R2 --3 * R3 + R3 -> R3 +-3 * R1 + R3 -> R3 0.5 * R2 -> R2 -3 * R2 + R3 -> R3 -2 * R3 -> R3 diff --git a/src/solver/Main.java b/src/solver/Main.java index 99975d5..78dc65f 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -39,11 +39,19 @@ else if (args[i].equalsIgnoreCase("-out")) if (lines.size() != n) { throw new InvalidDataFileFormat("Incorrect data file format", null); } + System.out.println("Start solving the equation.\n" + + "Rows manipulation:"); Matrix m = new Matrix(n); for (String line : lines) { m.addRow(lines.indexOf(line), line); } m.print(); + System.out.println(m.rows[1].transform1(0)); + //System.out.println(m.rows[1].asString()); + m.print(); + System.out.println(m.rows[1].transform0(0, m.rows[0])); + m.print(); + } catch (IOException e){ System.out.println("File reading error: " + inFile); diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java index fdcb4d7..2ebef91 100644 --- a/src/solver/Matrix.java +++ b/src/solver/Matrix.java @@ -20,7 +20,9 @@ public void print(){ } } - public double[] getColumn(int index){ - return null; - } + /*public void printSolution(){ + for (Row r:this.rows) { + System.out.println(r.asString()); + } + }*/ } diff --git a/src/solver/Row.java b/src/solver/Row.java index 43ed8e4..ced9126 100644 --- a/src/solver/Row.java +++ b/src/solver/Row.java @@ -1,7 +1,5 @@ package solver; -import java.util.Arrays; - public class Row { private int rowNum; private int colCnt; @@ -19,19 +17,22 @@ public void mult(double koef){ data[i]*=koef; } } - /*public void divide(double koef){ - for (int i = 0; i < data.length; i++) { - data[i]*=1/koef; - } - }*/ + public void add(Row r){ for (int i = 0; i < data.length; i++) { data[i]+=r.data[i]; } } + + public void add1(Row r, double koef){ + for (int i = 0; i < data.length; i++) { + data[i]+=koef*r.data[i]; + } + } //преобразуем строку, чтобы элемент с индексом index стал = 1 //возвращаем строку с манипуляцией public String transform1(int index){ + if (this.data[index]==1) return "already transformed1"; double koef = 1/this.data[index]; this.mult(koef); this.data[index] = 1; @@ -39,9 +40,11 @@ public String transform1(int index){ } public String transform0(int index, Row r){ + if (this.data[index]==0) return "already transformed0"; double koef = -1 * this.data[index]; + this.add1(r,koef); this.data[index] = 0; - return (-1 * koef) + " * "+ r.getName() + " + "+ this.getName()+" -> "+this.getName(); + return koef + " * "+ r.getName() + " + "+ this.getName()+" -> "+this.getName(); } public void fillRow(String s) throws ParsingArrayException { @@ -57,7 +60,6 @@ public void fillRow(String s) throws ParsingArrayException { } } - public String asString() { String s=""; for (double d:this.data) { From 612bd3fdecf268efc7cd24ec967f16724502ae11 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Tue, 19 Feb 2019 23:26:19 +0300 Subject: [PATCH 06/12] adding new files --- src/solver/Main.java | 32 ++++++++++++++++++++++++++------ src/solver/Matrix.java | 14 +++++++++++--- src/solver/Row.java | 8 ++++++-- 3 files changed, 43 insertions(+), 11 deletions(-) diff --git a/src/solver/Main.java b/src/solver/Main.java index 78dc65f..92ac477 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -2,6 +2,7 @@ import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -45,13 +46,32 @@ else if (args[i].equalsIgnoreCase("-out")) for (String line : lines) { m.addRow(lines.indexOf(line), line); } - m.print(); - System.out.println(m.rows[1].transform1(0)); - //System.out.println(m.rows[1].asString()); - m.print(); - System.out.println(m.rows[1].transform0(0, m.rows[0])); - m.print(); + //m.print(); + for (int i = 0; i < m.N; i++) { + System.out.println(m.rows[i].transform1(i)); + //m.print(); + for (int j = i+1; j < m.N; j++) { + System.out.println(m.rows[j].transform0(i, m.rows[i])); + //m.print(); + } + } + //System.out.println("-------"); + for (int i = m.N-1; i >= 0; i--) { + for (int j = i-1; j >= 0; j--) { + System.out.println(m.rows[j].transform0(i, m.rows[i])); + //m.print(); + } + } + String result = m.printSolution(); + + 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); diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java index 2ebef91..8de179e 100644 --- a/src/solver/Matrix.java +++ b/src/solver/Matrix.java @@ -20,9 +20,17 @@ public void print(){ } } - /*public void printSolution(){ + public String printSolution(){ + String sOut = "The solution is: ("; + String result=""; + double s; for (Row r:this.rows) { - System.out.println(r.asString()); + s =r.getCol(this.N); + result+=s+"\n"; + sOut += s+", "; } - }*/ + System.out.println(sOut.replaceAll(",\\s$", ")")); + return result; + } + } diff --git a/src/solver/Row.java b/src/solver/Row.java index ced9126..bd0bffb 100644 --- a/src/solver/Row.java +++ b/src/solver/Row.java @@ -32,7 +32,7 @@ public void add1(Row r, double koef){ //преобразуем строку, чтобы элемент с индексом index стал = 1 //возвращаем строку с манипуляцией public String transform1(int index){ - if (this.data[index]==1) return "already transformed1"; + if (this.data[index]==1) return "";//"already transformed1"; double koef = 1/this.data[index]; this.mult(koef); this.data[index] = 1; @@ -40,13 +40,17 @@ public String transform1(int index){ } public String transform0(int index, Row r){ - if (this.data[index]==0) return "already transformed0"; + if (this.data[index]==0) return "";//"already transformed0"; double koef = -1 * this.data[index]; this.add1(r,koef); this.data[index] = 0; return koef + " * "+ r.getName() + " + "+ this.getName()+" -> "+this.getName(); } + public double getCol(int index){ + return this.data[index]; + } + public void fillRow(String s) throws ParsingArrayException { String[] str = s.split("\\s+"); try { From 912edb82c2ca9184b09f48e3608722ae2a58fc44 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Tue, 19 Feb 2019 23:58:16 +0300 Subject: [PATCH 07/12] adding new files --- src/solver/Main.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/solver/Main.java b/src/solver/Main.java index 92ac477..794885d 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -47,19 +47,22 @@ else if (args[i].equalsIgnoreCase("-out")) m.addRow(lines.indexOf(line), line); } //m.print(); - + String manipulation; for (int i = 0; i < m.N; i++) { - System.out.println(m.rows[i].transform1(i)); + manipulation = m.rows[i].transform1(i); + if (!manipulation.equals("")) System.out.println(manipulation); //m.print(); for (int j = i+1; j < m.N; j++) { - System.out.println(m.rows[j].transform0(i, m.rows[i])); + manipulation = m.rows[j].transform0(i, m.rows[i]); + if (!manipulation.equals("")) System.out.println(manipulation); //m.print(); } } //System.out.println("-------"); for (int i = m.N-1; i >= 0; i--) { for (int j = i-1; j >= 0; j--) { - System.out.println(m.rows[j].transform0(i, m.rows[i])); + manipulation = m.rows[j].transform0(i, m.rows[i]); + if (!manipulation.equals("")) System.out.println(manipulation); //m.print(); } } From a0039e9b6e56b55ba1046002f84c812780431082 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Wed, 20 Feb 2019 15:29:18 +0300 Subject: [PATCH 08/12] stage 4 --- src/plan.txt | 24 +++++++++++++++++++++++- src/solver/Main.java | 29 +++++++++++++++++++---------- src/solver/Matrix.java | 13 +++++++++---- 3 files changed, 51 insertions(+), 15 deletions(-) diff --git a/src/plan.txt b/src/plan.txt index ba6b24e..3c96c20 100644 --- a/src/plan.txt +++ b/src/plan.txt @@ -31,4 +31,26 @@ Saved to file out.txt пока в последней строке все коэффициенты не обнулятся кроме последнего столбца. 3.Вторая часть алгоритма - обнулять коэффициенты выше диагонали, начиная с последней строки до первой. -4.После этих преобразований решением уравнений будет правая часть матрицы. \ No newline at end of file +4.После этих преобразований решением уравнений будет правая часть матрицы. +Стадия 4. +Может быть случай, когда коэффициент, на который мы будем умножать будет равен 0. +Поэтому перед операцией умножения нужно проверить, коэффициент на равенство 0. +Если нужно искать ненулевой элемент ниже и правее. +1. Если ненулевой элемент ниже, то нужно переставить строки местами +2. Если ниже все элементы нулевые, то продолжаем искать правее +от элемента. Если находим, переставляем столбцы. +Состояние столбцов/строк до перестановки необходимо запомнить, +чтобы после реализации вернуть все на место в исходном порядке и +вывести решение в нужном порядке. В общей сложности может быть +много перестановок. +Если ненулевой элмент не находится ниже и правее, то ищется +ненулевой элемент по всей левой части матрицы и при нахождении +переставляем соответствущие строки и столбцы. +Если ненулевой элемент не найден, первая часть алгоритма завершается. + +После этого проверяем на количество решений. +1. все коэффициенты левой части нулевые, п.ч. ненулевая - нет решений. +2. если количество ненулевых элементов на главной диагонали +совпадает с количеством уравнений (в п.ч. не нули) - одно решение +3. если на главной дигонали есть нулевые элементы + в п.ч.нули +-> бесконечно много решений. diff --git a/src/solver/Main.java b/src/solver/Main.java index 794885d..bac8a2d 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -26,14 +26,22 @@ else if (args[i].equalsIgnoreCase("-out")) } try { List lines = Files.readAllLines( Paths.get(inFile)); - int n; + int n=0,v=0; + int k=0; try { - n = Integer.parseInt(lines.get(0)); + 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 number", lines.get(0)), + String.format("Incorrect data file format, '%s' cannot be parsed as two numbers", lines.get(0)), e); } lines.remove(0); @@ -42,28 +50,28 @@ else if (args[i].equalsIgnoreCase("-out")) } System.out.println("Start solving the equation.\n" + "Rows manipulation:"); - Matrix m = new Matrix(n); + Matrix m = new Matrix(n,v); for (String line : lines) { m.addRow(lines.indexOf(line), line); } - //m.print(); + m.print(); String manipulation; - for (int i = 0; i < m.N; i++) { + for (int i = 0; i < m.M; i++) { manipulation = m.rows[i].transform1(i); if (!manipulation.equals("")) System.out.println(manipulation); - //m.print(); + m.print(); for (int j = i+1; j < m.N; j++) { manipulation = m.rows[j].transform0(i, m.rows[i]); if (!manipulation.equals("")) System.out.println(manipulation); - //m.print(); + m.print(); } } - //System.out.println("-------"); + /*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]); if (!manipulation.equals("")) System.out.println(manipulation); - //m.print(); + m.print(); } } String result = m.printSolution(); @@ -75,6 +83,7 @@ else if (args[i].equalsIgnoreCase("-out")) } catch (IOException e) { System.out.printf("File writing error %s", e.getMessage()); } + */ } catch (IOException e){ System.out.println("File reading error: " + inFile); diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java index 8de179e..79328a0 100644 --- a/src/solver/Matrix.java +++ b/src/solver/Matrix.java @@ -1,16 +1,18 @@ package solver; public class Matrix { - int N;//количество строк и столбцов + int N;//количество строк + int M;//количество столбцов Row[] rows; - public Matrix(int n) { + public Matrix(int n, int m) { N = n; + M = m; rows = new Row[n]; } public void addRow(int index, String str) throws ParsingArrayException { - this.rows[index] = new Row(index+1, N+1); + this.rows[index] = new Row(index+1, M+1); this.rows[index].fillRow(str); } @@ -25,7 +27,7 @@ public String printSolution(){ String result=""; double s; for (Row r:this.rows) { - s =r.getCol(this.N); + s =r.getCol(this.M); result+=s+"\n"; sOut += s+", "; } @@ -33,4 +35,7 @@ public String printSolution(){ return result; } + public String swapRows(int src, int dest){ + return null; + } } From 492e7704bf651ea33abbd753b3e0ff1949abf75c Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Wed, 20 Feb 2019 15:38:29 +0300 Subject: [PATCH 09/12] stage 4 --- src/solver/Row.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/solver/Row.java b/src/solver/Row.java index bd0bffb..cc7db65 100644 --- a/src/solver/Row.java +++ b/src/solver/Row.java @@ -3,10 +3,14 @@ public class Row { private int rowNum; private int colCnt; + private int oldRowNum; private double[] data; + public boolean isMoved; public Row(int rowNum, int colCnt/*double[] data*/){ this.rowNum = rowNum; + this.oldRowNum = rowNum; this.data = new double[colCnt]; + this.isMoved = false; } public String getName() { From d24aff1efba336175199f14e53225cb4b8525cfa Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Wed, 20 Feb 2019 23:00:17 +0300 Subject: [PATCH 10/12] stage 4 --- src/plan.txt | 6 +++- src/solver/Main.java | 1 - src/solver/Matrix.java | 62 +++++++++++++++++++++++++++++++++++++++++- src/solver/Row.java | 42 ++++++++++++++++++++++++++-- 4 files changed, 106 insertions(+), 5 deletions(-) diff --git a/src/plan.txt b/src/plan.txt index 3c96c20..1a17dd1 100644 --- a/src/plan.txt +++ b/src/plan.txt @@ -38,7 +38,7 @@ Saved to file out.txt Если нужно искать ненулевой элемент ниже и правее. 1. Если ненулевой элемент ниже, то нужно переставить строки местами 2. Если ниже все элементы нулевые, то продолжаем искать правее -от элемента. Если находим, переставляем столбцы. +от элемента. Если находим, переставляем столбцы,строки. Состояние столбцов/строк до перестановки необходимо запомнить, чтобы после реализации вернуть все на место в исходном порядке и вывести решение в нужном порядке. В общей сложности может быть @@ -54,3 +54,7 @@ Saved to file out.txt совпадает с количеством уравнений (в п.ч. не нули) - одно решение 3. если на главной дигонали есть нулевые элементы + в п.ч.нули -> бесконечно много решений. +C1,C2,C3(1<->2)C2,C1,C3(1<->3)C3,C1,C2 +colMove[1]=3 +colMove[2]=1 +colMove[3]=2 diff --git a/src/solver/Main.java b/src/solver/Main.java index bac8a2d..1e08f3d 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -54,7 +54,6 @@ else if (args[i].equalsIgnoreCase("-out")) for (String line : lines) { m.addRow(lines.indexOf(line), line); } - m.print(); String manipulation; for (int i = 0; i < m.M; i++) { manipulation = m.rows[i].transform1(i); diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java index 79328a0..8c160da 100644 --- a/src/solver/Matrix.java +++ b/src/solver/Matrix.java @@ -1,18 +1,34 @@ package solver; +import java.util.Arrays; + +class Pos{ + int x; + int y; + + public Pos(int x, int y) { + this.x = x; + this.y = y; + } +} + public class Matrix { int N;//количество строк int M;//количество столбцов Row[] rows; + int[] colMove; public Matrix(int n, int m) { N = n; M = m; rows = new Row[n]; + colMove = new int[m];//сюда будем записывать перемещения столбов + for (int i = 0; i < M; i++) + this.colMove[i] = i; } public void addRow(int index, String str) throws ParsingArrayException { - this.rows[index] = new Row(index+1, M+1); + this.rows[index] = new Row(index+1, M+1, this); this.rows[index].fillRow(str); } @@ -36,6 +52,50 @@ public String printSolution(){ } public String swapRows(int src, int dest){ + Row r1 = this.rows[src]; + Row r2 = this.rows[dest]; + String result = r1.getName()+"<->"+r2.getName(); + Row tmp; + tmp = this.rows[dest]; + this.rows[dest] = this.rows[src]; + this.rows[src] = tmp; + this.rows[src].setMoved(true,src+1); + this.rows[dest].setMoved(true,dest+1); + return result; + } + + + public String swapColumns(int src, int dest){ + for (Row r:this.rows) { + r.swapCells(src,dest); + } + int tmp =this.colMove[dest]; + this.colMove[dest] = this.colMove[src]; + this.colMove[src] = tmp; + System.out.println(Arrays.toString(this.colMove)); + return String.format("C%d<->C%d",src,dest); + } + + public int findNonZeroBelow(int col, Row rowBelow){ + for (int i = rowBelow.getRowNum()/*-1+1*/; i < N; i++) { + if (this.rows[i].getCol(col)!=0) return i; + } + return -1; + } + + public int findNonZeroRighter(int colAfterIndex, Row row){ + for (int j = colAfterIndex+1; j < M; j++) { + if (row.getCol(j)!=0) return j; + } + return -1; + } + + public Pos findNonZeroEverywere(){ + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + if (this.rows[i].getCol(j)!=0) return new Pos(i,j); + } + } return null; } } diff --git a/src/solver/Row.java b/src/solver/Row.java index cc7db65..43741f0 100644 --- a/src/solver/Row.java +++ b/src/solver/Row.java @@ -5,12 +5,19 @@ public class Row { private int colCnt; private int oldRowNum; private double[] data; - public boolean isMoved; - public Row(int rowNum, int colCnt/*double[] data*/){ + private boolean isMoved; + private Matrix owner; + public Row(int rowNum, int colCnt, Matrix owner/*double[] data*/){ this.rowNum = rowNum; this.oldRowNum = rowNum; this.data = new double[colCnt]; + this.isMoved = false; + this.owner = owner; + } + + public int getRowNum() { + return rowNum; } public String getName() { @@ -37,6 +44,19 @@ public void add1(Row r, double koef){ //возвращаем строку с манипуляцией public String transform1(int index){ if (this.data[index]==1) return "";//"already transformed1"; + if (this.data[index]==0){ + int nonZeroInd = this.owner.findNonZeroBelow(index,this); + if (nonZeroInd >= -1) + return this.owner.swapRows(this.rowNum-1,nonZeroInd); + nonZeroInd = this.owner.findNonZeroRighter(index,this); + if (nonZeroInd >= -1) + return this.owner.swapColumns(index,nonZeroInd); + //поиск по всей матрице + Pos pos = this.owner.findNonZeroEverywere(); + if (pos == null) return ""; + return this.owner.swapColumns(index,pos.y)+";"+ + this.owner.swapRows(this.rowNum-1, pos.x); + } double koef = 1/this.data[index]; this.mult(koef); this.data[index] = 1; @@ -75,4 +95,22 @@ public String asString() { }; return this.getName()+": "+ s.trim(); } + + public boolean isMoved() { + return isMoved; + } + + public void setMoved(boolean moved, int newRow) { + isMoved = moved; + if (moved) { + this.oldRowNum = rowNum; + this.rowNum = newRow; + } + } + public void swapCells(int src, int dest){ + double tmp; + tmp = this.data[dest]; + this.data[dest] = this.data[src]; + this.data[src] = tmp; + } } From a7bddd28e381d8415da9e3f07b5b6fdb6f9c6cb4 Mon Sep 17 00:00:00 2001 From: Grokholskaya Date: Wed, 20 Feb 2019 23:49:32 +0300 Subject: [PATCH 11/12] stage 4 --- src/solver/Main.java | 50 +++++++++++++++++++++++++++++++----------- src/solver/Matrix.java | 33 ++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 13 deletions(-) diff --git a/src/solver/Main.java b/src/solver/Main.java index 1e08f3d..80062b6 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -55,26 +55,50 @@ else if (args[i].equalsIgnoreCase("-out")) m.addRow(lines.indexOf(line), line); } String manipulation; + m.otladka = false; for (int i = 0; i < m.M; i++) { manipulation = m.rows[i].transform1(i); - if (!manipulation.equals("")) System.out.println(manipulation); - m.print(); + if (!manipulation.equals("")) { + System.out.println(manipulation); + m.print(); + } for (int j = i+1; j < m.N; j++) { manipulation = m.rows[j].transform0(i, m.rows[i]); - if (!manipulation.equals("")) System.out.println(manipulation); - m.print(); + if (!manipulation.equals("")) { + System.out.println(manipulation); + m.print(); + } } } - /*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]); - 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]); + if (!manipulation.equals("")) { + System.out.println(manipulation); + m.print(); + } + } + } + result = m.printSolution(); + break; + } + default:break; } - String result = m.printSolution(); - File file = new File(outFile); try (FileWriter writer = new FileWriter(file)) { writer.write(result); @@ -82,7 +106,7 @@ else if (args[i].equalsIgnoreCase("-out")) } catch (IOException e) { System.out.printf("File writing error %s", e.getMessage()); } - */ + } catch (IOException e){ System.out.println("File reading error: " + inFile); diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java index 8c160da..326862e 100644 --- a/src/solver/Matrix.java +++ b/src/solver/Matrix.java @@ -10,6 +10,9 @@ public Pos(int x, int y) { this.x = x; this.y = y; } + public String asString(){ + return this.x+","+this.y; + } } public class Matrix { @@ -17,6 +20,7 @@ public class Matrix { int M;//количество столбцов Row[] rows; int[] colMove; + public boolean otladka = false; public Matrix(int n, int m) { N = n; @@ -33,6 +37,7 @@ public void addRow(int index, String str) throws ParsingArrayException { } public void print(){ + if (!otladka) return; for (Row r:this.rows) { System.out.println(r.asString()); } @@ -98,4 +103,32 @@ public Pos findNonZeroEverywere(){ } return null; } + + public Pos getNumberOfZeroRows(){ + //в ч запишем количество нулевых строк, + //в y количество нулевых строк с ненулевой правой частью + Pos result= new Pos(0,0); + int cnt0 =0, cnt1 =0; + for (Row r:this.rows) { + cnt0=0; + for (int i = 0; i < M+1; i++) { + if (r.getCol(i)!=0) { + if (i==M) result.y++; + break; + } + cnt0++; + } + if (cnt0==M) result.x++; + } + return result; + } + + public int checkSolution(){ + Pos zeroRowsCnt = this.getNumberOfZeroRows(); + if (zeroRowsCnt.y>0) return -1;//no solutions + int cntEq = this.N-zeroRowsCnt.y;//количество ненулевых уравнений + if (cntEq==this.M) return 1;//one solution + if (cntEq Date: Thu, 21 Feb 2019 21:39:44 +0300 Subject: [PATCH 12/12] stage 4 --- src/solver/Main.java | 21 +++++++---- src/solver/Matrix.java | 84 +++++++++++++++++++++++++++++++----------- src/solver/Row.java | 49 +++++++++++++++++------- 3 files changed, 113 insertions(+), 41 deletions(-) diff --git a/src/solver/Main.java b/src/solver/Main.java index 80062b6..5c8706d 100644 --- a/src/solver/Main.java +++ b/src/solver/Main.java @@ -46,7 +46,7 @@ else if (args[i].equalsIgnoreCase("-out")) } lines.remove(0); if (lines.size() != n) { - throw new InvalidDataFileFormat("Incorrect data file format", null); + 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:"); @@ -55,13 +55,19 @@ else if (args[i].equalsIgnoreCase("-out")) m.addRow(lines.indexOf(line), line); } String manipulation; - m.otladka = false; + //m.otladka = true; + m.print(); for (int i = 0; i < m.M; i++) { - manipulation = m.rows[i].transform1(i); - if (!manipulation.equals("")) { - System.out.println(manipulation); - m.print(); - } + while (true) + { + manipulation = m.rows[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]); if (!manipulation.equals("")) { @@ -71,6 +77,7 @@ else if (args[i].equalsIgnoreCase("-out")) } } int check = m.checkSolution(); + String result=""; switch (check) { case 0: { diff --git a/src/solver/Matrix.java b/src/solver/Matrix.java index 326862e..5ef9a70 100644 --- a/src/solver/Matrix.java +++ b/src/solver/Matrix.java @@ -2,6 +2,7 @@ import java.util.Arrays; +//import java.util.Arrays; class Pos{ int x; int y; @@ -16,12 +17,20 @@ public String asString(){ } public class Matrix { + public static final double threshold = 0.000001; int N;//количество строк int M;//количество столбцов Row[] rows; int[] colMove; + int iteration = 0; + private boolean colsSwaped = false; + public boolean otladka = false; + public static boolean compareDouble(double d1, double d2){ + return (Math.abs(d1 - d2) < threshold); + } + public Matrix(int n, int m) { N = n; M = m; @@ -44,6 +53,7 @@ public void print(){ } public String printSolution(){ + if (colsSwaped) return printSolution1(); String sOut = "The solution is: ("; String result=""; double s; @@ -56,19 +66,41 @@ public String printSolution(){ return result; } - public String swapRows(int src, int dest){ - Row r1 = this.rows[src]; - Row r2 = this.rows[dest]; - String result = r1.getName()+"<->"+r2.getName(); - Row tmp; - tmp = this.rows[dest]; - this.rows[dest] = this.rows[src]; - this.rows[src] = tmp; - this.rows[src].setMoved(true,src+1); - this.rows[dest].setMoved(true,dest+1); + private String printSolution1(){ + String sOut = "The solution is: ("; + double[] d= new double[colMove.length]; + String result=""; + for (int i = 0; i < colMove.length; i++) { + d[colMove[i]]=this.rows[i].getCol(this.M); + } + for (int i = 0; i < colMove.length; i++) { + result+=d[i]+"\n"; + sOut += d[i]+", "; + } + System.out.println(sOut.replaceAll(",\\s$", ")")); return result; } + public String swapRows(int src, int dest){ + try { + Row r1 = this.rows[src]; + Row r2 = this.rows[dest]; + iteration++; + String result = String.format("%d: %s<->%s", iteration, r1.getName(), r2.getName()); + Row tmp; + tmp = this.rows[dest]; + this.rows[dest] = this.rows[src]; + this.rows[src] = tmp; + this.rows[src].setMoved(true, src + 1); + this.rows[dest].setMoved(true, dest + 1); + return result; + } + catch (Exception e){ + System.out.println(String.format("SwapRow(src=%d,dest=%d)",src,dest)); + throw e; + } + } + public String swapColumns(int src, int dest){ for (Row r:this.rows) { @@ -77,28 +109,35 @@ public String swapColumns(int src, int dest){ int tmp =this.colMove[dest]; this.colMove[dest] = this.colMove[src]; this.colMove[src] = tmp; - System.out.println(Arrays.toString(this.colMove)); - return String.format("C%d<->C%d",src,dest); + iteration++; + colsSwaped = true; + return String.format("%d; C%d<->C%d",iteration, src,dest); } public int findNonZeroBelow(int col, Row rowBelow){ for (int i = rowBelow.getRowNum()/*-1+1*/; i < N; i++) { - if (this.rows[i].getCol(col)!=0) return i; + //if (this.rows[i].getCol(col)!=0) return i; + if (!compareDouble(this.rows[i].getCol(col),0)) return i; } return -1; } public int findNonZeroRighter(int colAfterIndex, Row row){ for (int j = colAfterIndex+1; j < M; j++) { - if (row.getCol(j)!=0) return j; +// if (row.getCol(j)!=0) return j; + if (!compareDouble(row.getCol(j),0)) return j; } return -1; } - public Pos findNonZeroEverywere(){ - for (int i = 0; i < N; i++) { - for (int j = 0; j < M; j++) { - if (this.rows[i].getCol(j)!=0) return new Pos(i,j); + public Pos findNonZeroEverywhere(int colAfterIndex, Row rowBelow){ + int fromRow=0; + if (rowBelow == null) fromRow = 0; + else fromRow = rowBelow.getRowNum(); + for (int i = fromRow; i < N; i++) { + for (int j = colAfterIndex+1; j < M; j++) { +// if (this.rows[i].getCol(j)!=0) return new Pos(i,j); + if (!compareDouble(this.rows[i].getCol(j),0)) return new Pos(i,j); } } return null; @@ -112,21 +151,24 @@ public Pos getNumberOfZeroRows(){ for (Row r:this.rows) { cnt0=0; for (int i = 0; i < M+1; i++) { - if (r.getCol(i)!=0) { + //if (r.getCol(i)!=0) { + if (!compareDouble(r.getCol(i),0)){ if (i==M) result.y++; break; } cnt0++; } - if (cnt0==M) result.x++; + if (cnt0==M+1) result.x++; } return result; } public int checkSolution(){ Pos zeroRowsCnt = this.getNumberOfZeroRows(); + if (otladka) + System.out.println(zeroRowsCnt.asString()); if (zeroRowsCnt.y>0) return -1;//no solutions - int cntEq = this.N-zeroRowsCnt.y;//количество ненулевых уравнений + int cntEq = this.N-zeroRowsCnt.x;//количество ненулевых уравнений if (cntEq==this.M) return 1;//one solution if (cntEq= -1) + if (nonZeroInd > -1) return this.owner.swapRows(this.rowNum-1,nonZeroInd); nonZeroInd = this.owner.findNonZeroRighter(index,this); - if (nonZeroInd >= -1) + if (nonZeroInd > -1) return this.owner.swapColumns(index,nonZeroInd); //поиск по всей матрице - Pos pos = this.owner.findNonZeroEverywere(); + Pos pos = this.owner.findNonZeroEverywhere(index,this); if (pos == null) return ""; return this.owner.swapColumns(index,pos.y)+";"+ this.owner.swapRows(this.rowNum-1, pos.x); @@ -60,15 +67,18 @@ public String transform1(int index){ double koef = 1/this.data[index]; this.mult(koef); this.data[index] = 1; - return koef +" * "+this.getName()+" -> "+this.getName(); +// return String.format("%-8.2f %n",koef) +" * "+this.getName()+" -> "+this.getName(); + return String.format("%d: %.2f * %s -> %s",++this.owner.iteration, koef,this.getName(),this.getName()); } public String transform0(int index, Row r){ - if (this.data[index]==0) return "";//"already transformed0"; + if (Matrix.compareDouble(this.data[index],0)) return "";//"already transformed0"; double koef = -1 * this.data[index]; this.add1(r,koef); this.data[index] = 0; - return koef + " * "+ r.getName() + " + "+ this.getName()+" -> "+this.getName(); + this.owner.iteration++; +// return koef + " * "+ r.getName() + " + "+ this.getName()+" -> "+this.getName(); + return String.format("%d: %.3f * %s -> %s",this.owner.iteration, koef,r.getName(),this.getName()); } public double getCol(int index){ @@ -78,6 +88,10 @@ public double getCol(int index){ public void fillRow(String s) throws ParsingArrayException { String[] str = s.split("\\s+"); try { + if (str.length!=this.colCnt) + throw new ParsingArrayException( + String.format("The string '%s' cannot be parsed correctly. It has to contain %d numbers", s, this.colCnt+1), + null); for (int i = 0; i < str.length; i++) { this.data[i] = Double.parseDouble(str[i]); } @@ -86,14 +100,20 @@ public void fillRow(String s) throws ParsingArrayException { String.format("The string '%s' cannot be parsed as an array of numbers", s), e); } + catch (ArrayIndexOutOfBoundsException e){ + throw new ParsingArrayException( + String.format("The string '%s' cannot be parsed correctly, count of numbers is incorrect", s), + e); + } } public String asString() { String s=""; for (double d:this.data) { - s +=d+" "; + s +=String.format("%-10.3f ",d); + //s +=String.format("%.3f ",d); }; - return this.getName()+": "+ s.trim(); + return this.getName()+((this.getOldRowNum()!=this.getRowNum())?String.format("(%d)",this.getOldRowNum()):"")+": "+ s.trim(); } public boolean isMoved() { @@ -103,9 +123,12 @@ public boolean isMoved() { public void setMoved(boolean moved, int newRow) { isMoved = moved; if (moved) { - this.oldRowNum = rowNum; + /*if (this.oldRowNum == this.rowNum) { + this.oldRowNum = rowNum; + }*/ this.rowNum = newRow; } + if (this.rowNum == this.oldRowNum) isMoved = false; } public void swapCells(int src, int dest){ double tmp;