diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF index 02c3d23..75ab88c 100644 --- a/META-INF/MANIFEST.MF +++ b/META-INF/MANIFEST.MF @@ -1,5 +1,5 @@ Program-Name: JMatrix -Version: v0.2.0 -Main-Class: lib.matrix.ExampleMatrix +Version: v1.0.0 +Main-Class: com.mitsuki.jmatrix.Main Created-By: Ryuu Mitsuki -Manifest-Version: 1.0 +Manifest-Version: 1.1 diff --git a/Makefile b/Makefile index c7a6cba..4ec7705 100644 --- a/Makefile +++ b/Makefile @@ -1,24 +1,35 @@ # MAKEFILE FOR JMATRIX # Created by Ryuu Mitsuki +VERSION = v1.0.0 -SRC_DIR = lib/matrix/ -MANIFEST = META-INF/MANIFEST.MF +SRC_DIR = com/mitsuki/jmatrix/ +BIN_DIR = bin/ + +PY = src/python/ +BIN := $(wildcard $(BIN_DIR)$(SRC_DIR)*.class) +SRCTXT = assets/properties/source_files.list -SRC = $(SRC_DIR)*.java -BIN = $(SRC_DIR)*.class +MANIFEST = META-INF/MANIFEST.MF +JAR = jars/jmatrix-$(VERSION).jar -JAR = Matrix.jar -all: $(SRC) +all: $(SRCTXT) $(MANIFEST) $(info Creating jar files...) - javac $(SRC) - jar cvfm $(JAR) $(MANIFEST) $(BIN) + mkdir -p jars/ + python $(PY)get_sources.py + python $(PY)fix_version.py + javac -d $(BIN_DIR) @$< + jar cvfm $(JAR) $(MANIFEST) \ + LICENSE assets/ -C bin/ . + -run: $(JAR) - java -jar $(JAR) +clean-bin: + rm -r $(BIN_DIR) + $(info Cleaning "$(BIN_DIR)" only...) clean: - rm -r $(BIN) $(JAR) + rm -r $(JAR) $(BIN_DIR) + $(info Cleaning "$(JAR)" "$(BIN_DIR)"...) -.PHONY: all run clean +.PHONY: all clean clean-bin diff --git a/README.md b/README.md index 1e7bcfb..fcee55a 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,30 @@ # JMatrix -**Author : Ryuu Mitsuki
** +**Developed by Ryuu Mitsuki
** -> JMatrix is a matrix builder written in Java.
-> Developed by Ryuu Mitsuki.
-> It can create, summarize, subtract, multiply and clear the matrix array.
-> Check `LIST FUNCTION` below to see all functions. +**Operating System: `Linux`
** +**Java version: `openjdk-17`
** +**Python version: `python-3.11.2`** ---- +> **Note** +> JMatrix is a matrix builder written in Java.
+> It can create, operate addition, subtract, multiply and clear the matrix array.
+> +> [See all methods](https://github.com/mitsuki31/jmatrix#list-methodsrocket)  |   +> [See usages](https://github.com/mitsuki31/jmatrix#usage) -Make sure you've `Java` installed in your device:warning:
-If not, download here:
-1. [https://openjdk.org](https://openjdk.org) -2. [https://developers.redhat.com/products/openjdk/download](https://developers.redhat.com/products/openjdk/download) +> **Warning** Make sure you've installed these on your device +> - Java  \[[Download here](https://oracle.com/java/)\] +> - Python  \[[Download here](https://python.org/)\] +> - Make  *(for Windows you need to install Chocolatey)* +> - Chocolatey  \[[Download here](https://chocolatey.org/install)\] -## LIST FUNCTION:rocket: +## LIST METHODS:rocket: ### add() Fill column of matrix array with push method.
-If you attempt to call `add()` function again and you've matrix size 2x3, but you've already call `add()` 2 times (same as total rows), it'll throw `MatrixArrayFullException`.
+> **Note** If you attempt to call `add()` function again and you've matrix size 2x3, but you've already call `add()` 2 times (same as total rows), it'll throw `MatrixArrayFullException`.

+ Function parameters: - void add(int... values) - void add(int value) @@ -28,10 +34,10 @@ Summarize current matrix array with other matrix.

Function parameters: - void sum(Matrix object) -- void sum(int[ ][ ] array) +- void sum(int\[ ]\[ ] array)
-- static int[ ][ ] sum(int[ ][ ] array, int[ ][ ] array) +- static int[ ]\[ ] sum(int\[ ]\[ ] array, int\[ ]\[ ] array) - static Matrix sum(Matrix obj1, Matrix obj2) ### sub() @@ -39,10 +45,10 @@ Subtract current matrix array with other matrix.

Function parameters: - void sub(Matrix obj) -- void sub(int[ ][ ] arr) +- void sub(int\[ ]\[ ] arr)
-- static int[ ][ ] sub(int[ ][ ] arr, int[ ][ ] arr) +- static int\[ ]\[ ] sub(int\[ ]\[ ] arr, int\[ ]\[ ] arr) - static Matrix sub(Matrix obj1, Matrix obj2) ### mult() @@ -50,10 +56,10 @@ Multiply current matrix with other matrix.

Function parameters: - void mult(Matrix obj) -- void mult(int[ ][ ] arr) +- void mult(int\[ ]\[ ] arr)
-- static int[ ][ ] mult(int[ ][ ] arr, int[ ][ ] arr) +- static int\[ ]\[ ] mult(int\[ ]\[ ] arr, int\[ ]\[ ] arr) - static Matrix mult(Matrix obj1, Matrix obj2) ### transpose() @@ -63,7 +69,7 @@ Function parameters: - void transpose()
-- static int[ ][ ] transpose(int[ ][ ] arr) +- static int\[ ]\[ ] transpose(int\[ ]\[ ] arr) - static Matrix transpose(Matrix obj) @@ -77,11 +83,11 @@ Function parametera: Select row matrix by given index.

Function parameters: -- void select() +- Matrix select(int index) ### change() Change values of selected row with given values.
-> Use this together with `select` function.
+> **Note** Use this together with `select` function.
> Example: `matrixA.select().change()`
@@ -100,13 +106,13 @@ Sort all columns inside matrix array.

Function parameters: - void sort() -- static void sort(int[ ][ ] arr) +- static void sort(int\[ ]\[ ] arr) ### getSize() -Return list of matrix size [rows, columns].
+Return list of matrix size \[rows, columns].

Function parameters: -- int[ ] getSize() +- int\[ ] getSize() ### clear() Clear all each column inside matrix array, and change all values with 0.
@@ -122,23 +128,26 @@ Function parameters: - void display(int index)
-- static void display(int[ ][ ] arr) -- static void display(int[ ][ ] arr, int index) +- static void display(int\[ ]\[ ] arr) +- static void display(int\[ ]\[ ] arr, int index)
## USAGE -Compile and create a `JAR` file with `Makefile` -```bash|powershell +### Makefile Options +Compile and create new `JAR` file +```bash make ``` -Run the program -```bash|powershell -make run +Clearing binary files in `bin/` directory and `JAR` file +> **Warning** This will delete `bin/` directory recursively
+> Make sure you don't save any important file(s) to `bin/` directory +```bash +make clean ``` -## EDIT MANIFEST -If you want to change the `Main` file while running the program, -change `Main-Class` in `META-INF/MANIFEST.MF`.
-Default: `lib.matrix.ExampleMatrix` +Clearing binary files only +```bash +make clean-bin +``` diff --git a/assets/configuration/config.xml b/assets/configuration/config.xml new file mode 100644 index 0000000..bc04ba9 --- /dev/null +++ b/assets/configuration/config.xml @@ -0,0 +1,8 @@ + + + + JMatrix + v1.0.0 + com.mitsuki.jmatrix + Ryuu Mitsuki + diff --git a/assets/contents/additional.content b/assets/contents/additional.content new file mode 100644 index 0000000..6394e1e --- /dev/null +++ b/assets/contents/additional.content @@ -0,0 +1,3 @@ +# Don't change this file directly +4A4D6174726978202D20436F707972696768742028432920323032332052797575204D697473756B69 +4D4954204C6963656E7365 diff --git a/assets/contents/help.content b/assets/contents/help.content new file mode 100644 index 0000000..93c6f3b --- /dev/null +++ b/assets/contents/help.content @@ -0,0 +1,10 @@ +Usage: + java -jar [options] + +Options: + -h, help display this help + -cr, copyright print the copyright + -V, ver, version display version number with release type + +JMatrix - com.mitsuki.jmatrix +Developed by Ryuu Mitsuki diff --git a/assets/properties/source_files.list b/assets/properties/source_files.list new file mode 100644 index 0000000..a2fb16c --- /dev/null +++ b/assets/properties/source_files.list @@ -0,0 +1,10 @@ +src/com/mitsuki/jmatrix/IllegalMatrixSizeException.java +src/com/mitsuki/jmatrix/InvalidIndexException.java +src/com/mitsuki/jmatrix/Main.java +src/com/mitsuki/jmatrix/Matrix.java +src/com/mitsuki/jmatrix/MatrixArrayFullException.java +src/com/mitsuki/jmatrix/NullMatrixException.java +src/com/mitsuki/jmatrix/core/JMBaseException.java +src/com/mitsuki/jmatrix/util/OSUtils.java +src/com/mitsuki/jmatrix/util/Options.java +src/com/mitsuki/jmatrix/util/XMLParser.java diff --git a/lib/matrix/ExampleMatrix.java b/lib/matrix/ExampleMatrix.java deleted file mode 100644 index f0ee112..0000000 --- a/lib/matrix/ExampleMatrix.java +++ /dev/null @@ -1,101 +0,0 @@ -// ::-------------------:: // -/* ExampleMatrix */ -// ::-------------------:: // -package lib.matrix; - -import java.util.Arrays; - -import lib.matrix.*; // import all packages in "lib.matrix" - -public class ExampleMatrix -{ - public static void main(String[ ] args) - throws NullMatrixException, IllegalMatrixSizeException, MatrixArrayFullException, InvalidIndexException - { - // Rows and columns size for new Matrix - int rows = 2; - int cols = 3; - - // Values for each row - int[ ] row1 = { 1, 2, 3 }; - int[ ] row2 = { 4, 5, 6 }; - int[ ] row3 = { 7, 8, 9 }; - - int[ ] rowA1 = { -9, -6, -3 }; - int[ ] rowA2 = { -8, -5, -2 }; - int[ ] rowA3 = { -7, -4, -1 }; - - // Create new Matrix object - Matrix matrixA = new Matrix(rows, cols); - Matrix matrixB = new Matrix(rows, cols); - Matrix result = new Matrix(); // null matrix - - // Get the Matrix size - int[ ] matrixSize = matrixA.getSize(); // return [rows, cols] - - // Display matrix size - System.out.println("\nSIZE OF MATRIX A: " + Arrays.toString(matrixSize)); - - // Adding values into Matrix - matrixA.add(row1); - matrixA.add(row2); - - matrixB.add(rowA1); - matrixB.add(rowA2); - - // Display the matrix - System.out.println("\nMATRIX A"); - matrixA.display(); - - System.out.println("\nMATRIX B"); - matrixB.display(); - - System.out.println("\n-------------------------"); - System.out.println(" SUMMATION"); - System.out.println("-------------------------"); - - System.out.println("MATRIX A + MATRIX B\n"); - result = Matrix.sum(matrixA, matrixB); - result.display(); - - System.out.println("\n-------------------------"); - System.out.println(" SUBTRACTION"); - System.out.println("-------------------------"); - - System.out.println("MATRIX A - MATRIX B\n"); - result = Matrix.sub(matrixA, matrixB); - result.display(); - - System.out.println("\n-------------------------"); - System.out.println(" MULTIPLICATION"); - System.out.println("-------------------------"); - - System.out.println("MATRIX A * MATRIX B\n"); - result = Matrix.mult(matrixA, matrixB); - result.display(); - - System.out.println("\n-------------------------"); - System.out.println(" TRANSPOSE"); - System.out.println("-------------------------"); - - System.out.println("TRANSPOSED MATRIX B\n"); - matrixB.transpose(); - matrixB.display(); - - System.out.println("\n-------------------------"); - System.out.println(" CLEARING MATRIX"); - System.out.println("-------------------------"); - - System.out.println("CLEARED MATRIX A\n"); - matrixA.clear(); - matrixA.display(); - - System.out.println("\n-------------------------"); - System.out.println(" COPY MATRIX"); - System.out.println("-------------------------"); - - System.out.println("COPY MATRIX B TO MATRIX A\n"); - matrixA = matrixB.copy(); - matrixA.display(); - } -} diff --git a/lib/matrix/IllegalMatrixSizeException.java b/lib/matrix/IllegalMatrixSizeException.java deleted file mode 100644 index 3e5b7f0..0000000 --- a/lib/matrix/IllegalMatrixSizeException.java +++ /dev/null @@ -1,31 +0,0 @@ -package lib.matrix; - -import java.lang.IllegalArgumentException; - -public class IllegalMatrixSizeException extends IllegalArgumentException -{ - private String message = "The two matrices are not same size"; - - public IllegalMatrixSizeException() { - super(); - } - - public IllegalMatrixSizeException(String message) { - super(message); - this.message = message; - } - - public IllegalMatrixSizeException(Throwable cause) { - super(cause); - } - - @Override - public String getMessage() { - return this.message; - } - - @Override - public String toString() { - return this.message; - } -} diff --git a/lib/matrix/Matrix.java b/lib/matrix/Matrix.java deleted file mode 100644 index 5e965fa..0000000 --- a/lib/matrix/Matrix.java +++ /dev/null @@ -1,827 +0,0 @@ -// :: ------------------ :: // -/* -- MATRIX BUILDER -- */ -// :: ------------------ :: // - -// Author : Ryuu Mitsuki - -/* - --- LIST FUNCTION --- - - Non-static function(s): - - Matrix select(int); - - - Matrix copy(); - - - void add(int...); - - void add(int); - - - void change(int...); - - void change(int); - - - void sum(Matrix); - - void sum(int[ ][ ]); - - - void sub(Matrix); - - void sub(int[ ][ ]); - - - void mult(Matrix); - - void mult(int[ ][ ]); - - - void transpose(); - - - void display(); - - void display(int); - - - void sort(); - - - int[ ] getSize(); - - - void clear(); - - - Static function(s): - - int[ ][ ] sum(int[ ][ ], int[ ][ ]); - - Matrix sum(Matrix, Matrix); - - - int[ ][ ] sub(int[ ][ ], int[ ][ ]); - - Matrix sub(Matrix, Matrix); - - - int[ ][ ] mult(int[ ][ ], int[ ][ ]); - - Matrix mult(Matrix, Matrix); - - - int[ ][ ] transpose(int[ ][ ]); - - Matrix transpose(Matrix); - - - void display(int[ ][ ]); - - void display(int[ ][ ], int); - - - void sort(int[ ][ ]); -*/ - -package lib.matrix; - -// -**- Built-in Package -**- // -import java.util.Arrays; -import java.util.Collections; -import java.lang.Math; - -// -**- Local Package -**- // -import lib.matrix.NullMatrixException; -import lib.matrix.MatrixArrayFullException; -import lib.matrix.IllegalMatrixSizeException; -import lib.matrix.InvalidIndexException; - -// ** MATRIX CLASS ** // -public class Matrix -{ - // - Private attributes - private int[ ][ ] MATRIX = null; // Create null matrix - private int ROWS = 0, // Initialize matrix rows - COLS = 0, // Initialize matrix columns - index = 0, // Index for add() function - selectedIndex = -1; - - private boolean isSquare; // boolean for check a square matrix - - - //// ----------------- //// - // -**- CONSTRUCTOR -**- // - //// ----------------- //// - - // -- Create null Matrix - public Matrix() {} - - /* --- - - Matrix constructor with 2 parameter: - > rows : For size of matrix rows - > cols : For size of matrix columns - --- */ - public Matrix(int rows, int cols) { - this.ROWS = rows; - this.COLS = cols; - this.MATRIX = new int[rows][cols]; - - if (rows != cols) { - this.isSquare = false; - } else { - this.isSquare = true; - } - } - - /* --- - - Matrix constructor with 3 parameter: - > rows : For size of matrix rows - > cols : For size of matrix columns - > val : Value for fill entire elements matrix array - --- */ - public Matrix(int rows, int cols, int val) { - this.ROWS = rows; - this.COLS = cols; - - this.MATRIX = new int[rows][cols]; - - if (rows != cols) { - this.isSquare = false; - } else { - this.isSquare = true; - } - - // Fill all elements inside matrix array with "val" - for (int r = 0; r < rows; r++) { - for (int c = 0; c < cols; c++) { - this.MATRIX[r][c] = val; - } - } - } - //// ----------------------- //// - // -**- [END] CONSTRUCTOR -**- // - //// ----------------------- //// - - - // -- Create new matrix - public void create(int rows, int cols) { - this.ROWS = rows; - this.COLS = cols; - this.MATRIX = new int[rows][cols]; - - this.index = 0; // reset index row - - if (rows != cols) { - this.isSquare = false; - } else { - this.isSquare = true; - } - } - - - // -- Copy the Matrix - public Matrix copy() throws NullMatrixException { - if (this.MATRIX == null) { - throw new NullMatrixException("Matrix is null, can not copy the Matrix"); - } - - // Create new and copy the matrix - Matrix copiedMatrix = new Matrix(this.ROWS, this.COLS); - copiedMatrix.MATRIX = this.MATRIX; - - return copiedMatrix; - } - - - // -- Select index of Matrix rows - public Matrix select(final int index) throws InvalidIndexException { - if (index < 0) { - throw new InvalidIndexException("Index must be positive value"); - } else if (index > this.ROWS - 1) { - throw new InvalidIndexException("Index is too large than total matrix rows"); - } - - this.selectedIndex = index; - - return this; // return self - } - - - //// ---------------- //// - // -**- ADD VALUES -**- // - //// ---------------- //// - - // Fill column with list of Integer(s) - public void add(int... values) - throws NullMatrixException, MatrixArrayFullException, IllegalMatrixSizeException { - // Throw "NullMatrixException" when matrix array is null - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - /** --- - - I've created add() function, that would only fill a row - when index isn't equal to total of matrix rows. - - Throw "MatrixArrayFullException" while attempt to add - new column when index has equal to total matrix rows - --- **/ - else if (this.index >= this.ROWS) { - throw new MatrixArrayFullException(); - } - // Length of values list shouldn't greater than total matrix columns - else if (values.length > this.COLS) { - throw new IllegalMatrixSizeException("Too many arguments; Max column: " + this.COLS); - } - // And shouldn't be less than total matrix columns - else if (values.length < this.COLS) { - throw new IllegalMatrixSizeException("Not enough argument"); - } - - // Iterate values list and fill elements of matrix array - int i = 0; - for (int val : values) { - this.MATRIX[this.index][i++] = val; - } - - this.index++; // increment index row - } - - // Fill column with an Integer value (repeated) - public void add(int value) - throws NullMatrixException, MatrixArrayFullException { - // Throw "NullMatrixException" when matrix array is null - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - /** --- - - Throw "MatrixArrayFullExceotion" while attempt to add - a new column, but the index has equal to total matrix rows - --- **/ - else if (this.index >= this.ROWS) { - throw new MatrixArrayFullException(); - } - - // Create list of repeated value - /** --- - - Example: call add() function with single Integer - with the value 8, then it would create column: - - >> [8, 8, 8, ...] - - - Then created column would be pushed to matrix array - --- **/ - int[ ] values = new int[this.COLS]; // create list with size equal to column length - for (int i = 0; i < values.length; i++) { - values[i] = value; - } - - // Iterate values list and fill elements of matrix array - int i = 0; - for (int val : values) { - this.MATRIX[this.index][i++] = val; - } - - this.index++; // increment index row - } - //// ---------------------- //// - // -**- [END] ADD VALUES -**- // - //// ---------------------- //// - - - /** --- - - Function that change values entire column, - - select column by "selectedIndex" value - --- **/ - public void change(int... values) - throws NullMatrixException, IllegalMatrixSizeException { - // Check for null matrix - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - // Check size of values from argument parameter - else if (values.length > this.COLS) { - throw new IllegalMatrixSizeException("Too many arguments; Max column: " + this.COLS); - } - else if (values.length < this.COLS) { - throw new IllegalMatrixSizeException("Not enough argument"); - } - - for (int i = 0; i < this.COLS; i++) { - this.MATRIX[this.selectedIndex][i] = values[i]; - } - - this.selectedIndex = -1; // reset to default - } - - public void change(int value) - throws NullMatrixException { - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - - // Create new array with same value - int[ ] values = new int[this.COLS]; - for (int i = 0; i < this.COLS; i++) { - values[i] = value; - } - - for (int i = 0; i < this.COLS; i++) { - this.MATRIX[this.selectedIndex][i] = values[i]; - } - - this.selectedIndex = -1; // reset to default - } - - - //// ----------------------- //// - // -**- MATRIX OPERATIONS -**- // - //// ----------------------- //// - - // -- Summation (Matrix object) -- // - public void sum(Matrix other) - throws IllegalMatrixSizeException, NullMatrixException { - // Throw "NullMatrixException" if matrix is null - if (this.MATRIX == null || other.MATRIX == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - // Else throw "IllegalMatrixSizeException" if the matrices are not same size - else if (this.ROWS != other.ROWS || this.COLS != other.COLS) { - throw new IllegalMatrixSizeException(); - } - - // Create new matrix for the result - int[ ][ ] result = new int[this.ROWS][other.COLS]; - - // Iterate over each element of the matrices and add the corresponding values together - for (int i = 0; i < this.ROWS; i++) { - for (int j = 0; j < this.COLS; j++) { - result[i][j] = this.MATRIX[i][j] + other.MATRIX[i][j]; - } - } - - this.MATRIX = result; // copy the result to Matrix - } - - // -- Summation (Integer array) -- // - public void sum(int[ ][ ] matrix) - throws IllegalMatrixSizeException, NullMatrixException { - // Throw "NullMatrixException" if matrix is null - if (this.MATRIX == null || matrix == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - // Else throw "IllegalMatrixSizeException" if the matrices are not same size - else if (this.ROWS != matrix.length || this.COLS != matrix[0].length) { - throw new IllegalMatrixSizeException(); - } - - // Create new matrix for the result - int[ ][ ] result = new int[this.ROWS][matrix[0].length]; - - // Using nested loop for iterate over each element of matrix - for (int i = 0; i < this.ROWS; i++) { - for (int j = 0; j < this.COLS; j++) { - result[i][j] = this.MATRIX[i][j] + matrix[i][j]; - } - } - - this.MATRIX = result; // copy the result to Matrix - } - - // -- Summation [Static] -- / - public static int[ ][ ] sum(int[ ][ ] matrixA, int[ ][ ] matrixB) - throws IllegalMatrixSizeException, NullMatrixException { - // Throw "NullMatrixException" if matrix array is null - if (matrixA == null || matrixB == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - // Else throw "IllegalMatrixSizeException" if the both matrix and are not same size - else if (matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { - throw new IllegalMatrixSizeException(); - } - - // Create a new matrix array - int[ ][ ] result = new int[matrixA.length][matrixB[0].length]; - - for (int i = 0; i < matrixA.length; i++) { - for (int j = 0; j < matrixB[0].length; j++) { - result[i][j] = matrixA[i][j] + matrixB[i][j]; - } - } - - return result; - } - - // -- Summation [Static] (Object) -- // - public static Matrix sum(Matrix matrixA, Matrix matrixB) - throws IllegalMatrixSizeException, NullMatrixException { - if (matrixA.MATRIX == null || matrixB.MATRIX == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - else if (matrixA.MATRIX.length != matrixB.MATRIX.length || - matrixA.MATRIX[0].length != matrixB.MATRIX[0].length) { - throw new IllegalMatrixSizeException(); - } - - // Create new matrix object - Matrix matrixRes = new Matrix(matrixA.MATRIX.length, matrixB.MATRIX[0].length); - - for (int i = 0; i < matrixA.MATRIX.length; i++) { - for (int j = 0; j < matrixB.MATRIX[0].length; j++) { - matrixRes.MATRIX[i][j] = matrixA.MATRIX[i][j] + matrixB.MATRIX[i][j]; - } - } - - return matrixRes; - } - - - - // -- Subtraction (Matrix object) -- // - public void sub(Matrix other) - throws IllegalMatrixSizeException, NullMatrixException { - // Throw "NullMatrixException" if matrix is null - if (this.MATRIX == null || other.MATRIX == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - // Else throw "IllegalMatrixSizeException" if the matrices are not same size - else if (this.ROWS != other.ROWS || this.COLS != other.COLS) { - throw new IllegalMatrixSizeException(); - } - - // Create new matrix for the result - int[ ][ ] result = new int[this.ROWS][other.COLS]; - - // Iterate over each element of all matrices and subtract each values together - for (int i = 0; i < this.ROWS; i++) { - for (int j = 0; j < this.COLS; j++) { - result[i][j] = this.MATRIX[i][j] - other.MATRIX[i][j]; - } - } - - this.MATRIX = result; // copy the result to Matrix - } - - // -- Subtraction (Integer array) -- // - public void sub(int[ ][ ] matrix) - throws IllegalMatrixSizeException, NullMatrixException { - // Throw "NullMatrixException" if matrix is null - if (this.MATRIX == null || matrix == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - // Else throw "IllegalMatrixSizeException" if the matrices are not same size - else if (this.ROWS != matrix.length || this.COLS != matrix[0].length) { - throw new IllegalMatrixSizeException(); - } - - // Create new matrix for the result - int[ ][ ] result = new int[this.ROWS][matrix[0].length]; - - // Iterate over each element of all matrices and subtract each values together - for (int i = 0; i < this.ROWS; i++) { - for (int j = 0; j < this.COLS; j++) { - result[i][j] = this.MATRIX[i][j] - matrix[i][j]; - } - } - - this.MATRIX = result; // copy the result to Matrix - } - - // -- Subtraction [Static] -- / - public static int[ ][ ] sub(int[ ][ ] matrixA, int[ ][ ] matrixB) - throws IllegalMatrixSizeException, NullMatrixException { - // Throw "NullMatrixException" if matrix array is null - if (matrixA == null || matrixB == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - // Else throw "IllegalMatrixSizeException" if the both matrix and are not same size - else if (matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { - throw new IllegalMatrixSizeException(); - } - - // Create a new matrix array - int[ ][ ] result = new int[matrixA.length][matrixB[0].length]; - - for (int i = 0; i < matrixA.length; i++) { - for (int j = 0; j < matrixB[0].length; j++) { - result[i][j] = matrixA[i][j] - matrixB[i][j]; - } - } - - return result; - } - - // -- Subtraction [Static] (Object) -- // - public static Matrix sub(Matrix matrixA, Matrix matrixB) - throws IllegalMatrixSizeException, NullMatrixException { - if (matrixA.MATRIX == null || matrixB.MATRIX == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - else if (matrixA.MATRIX.length != matrixB.MATRIX.length || - matrixA.MATRIX[0].length != matrixB.MATRIX[0].length) { - throw new IllegalMatrixSizeException(); - } - - // Create new matrix object - Matrix matrixRes = new Matrix(matrixA.MATRIX.length, matrixB.MATRIX[0].length); - - for (int i = 0; i < matrixA.MATRIX.length; i++) { - for (int j = 0; j < matrixB.MATRIX[0].length; j++) { - matrixRes.MATRIX[i][j] = matrixA.MATRIX[i][j] - matrixB.MATRIX[i][j]; - } - } - - return matrixRes; - } - - - - // -- Multiply Matrices Cell -- // - private static int multCell(int[ ][ ] matrixA, int[ ][ ] matrixB, int row, int col) { - int result = 0; - for (int i = 0; i < matrixB.length; i++) { - result += matrixA[row][i] * matrixB[i][col]; - } - - return result; - } - - // -- Multiplication (Matrix object) -- // - public void mult(Matrix other) throws NullMatrixException { - if (this.MATRIX == null || other.MATRIX == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - - // Create new matrix array - int[ ][ ] multiplyResult = new int[this.ROWS][other.MATRIX[0].length]; - - // Iterate and multiply each element - for (int r = 0; r < multiplyResult.length; r++) { - for (int c = 0; c < multiplyResult[r].length; c++) { - multiplyResult[r][c] = this.multCell(this.MATRIX, other.MATRIX, r, c); - } - } - - this.MATRIX = multiplyResult; - } - - // -- Multiplication (Integer array) - public void mult(int[ ][ ] matrix) throws NullMatrixException { - if (this.MATRIX == null || matrix == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - - // Create new matrix array - int[ ][ ] multiplyResult = new int[this.ROWS][matrix[0].length]; - - // Iterate and multiply each element - for (int r = 0; r < multiplyResult.length; r++) { - for (int c = 0; c < multiplyResult[r].length; c++) { - multiplyResult[r][c] = this.multCell(this.MATRIX, matrix, r, c); - } - } - - this.MATRIX = multiplyResult; - } - - // -- Multiplication [Static] -- // - public static int[ ][ ] mult(int[ ][ ] matrixA, int[ ][ ] matrixB) - throws NullMatrixException { - if (matrixA == null || matrixB == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - - int[ ][ ] multiplyResult = new int[matrixA.length][matrixB[0].length]; - - for (int r = 0; r < multiplyResult.length; r++) { - for (int c = 0; c < multiplyResult[r].length; c++) { - multiplyResult[r][c] = multCell(matrixA, matrixB, r, c); - } - } - - return multiplyResult; - } - - // -- Multiplication [Static] (Object) -- // - public static Matrix mult(Matrix matrixA, Matrix matrixB) - throws NullMatrixException { - if (matrixA.MATRIX == null || matrixB.MATRIX == null) { - throw new NullMatrixException("Can not iterate null matrix"); - } - - // Create new matrix object - Matrix matrixMultResult = new Matrix(matrixA.MATRIX.length, matrixB.MATRIX[0].length); - - for (int r = 0; r < matrixMultResult.MATRIX.length; r++) { - for (int c = 0; c < matrixMultResult.MATRIX[r].length; c++) { - matrixMultResult.MATRIX[r][c] = multCell(matrixA.MATRIX, matrixB.MATRIX, r, c); - } - } - - return matrixMultResult; - } - - //// ----------------------------- //// - // -**- [END] MATRIX OPERATIONS -**- // - //// ----------------------------- //// - - - // -- Matrix Displayer -- // - /** --- - - Output example: - [ [ n, n, n, ... ] - [ n, n, n, ... ] - [ .. .. .. ... ] ] - --- **/ - public final void display() throws NullMatrixException { - // Throw "NullMatrixException" if matrix array is null - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - - System.out.print("[ "); - for (int r = 0; r < this.ROWS; r++) { - System.out.print(this.toString(this.MATRIX[r])); - if (r != this.ROWS - 1) { - System.out.print("\n "); - } - } - System.out.println(" ]"); - } - - // -- Display specific column - public final void display(int index) - throws NullMatrixException, InvalidIndexException { - // Check whether matrix array is null or not - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - - // Checking index value from argument parameter - if (index < 0) { - throw new InvalidIndexException("Index must be positive value"); - } else if (index > this.ROWS - 1) { - throw new InvalidIndexException("Index is too large than total matrix rows"); - } - - System.out.println(this.toString(this.MATRIX[index])); - } - - public static final void display(int[ ][ ] matrix) - throws NullMatrixException { - // Throw "NullMatrixException" if matrix array is null - if (matrix == null) { - throw new NullMatrixException(); - } - - final int rows = matrix.length; - final int cols = matrix[0].length; - - System.out.print("[ "); - for (int r = 0; r < rows; r++) { - System.out.print(toString(matrix[r])); - if (r != rows - 1) { - System.out.print("\n "); - } - } - System.out.println(" ]"); - } - - public static final void display(int[ ][ ] matrix, int index) - throws NullMatrixException, InvalidIndexException { - if (matrix == null) { - throw new NullMatrixException(); - } - - // Checking index value - if (index < 0) { - throw new InvalidIndexException("Index must be positive value"); - } else if (index > matrix.length - 1) { - throw new InvalidIndexException("Index is too large than total matrix rows"); - } - - System.out.println(toString(matrix[index])); - } - - - // Function to convert Integer arrays to String - private static String toString(int[ ] array) { - final int len = array.length; - String strResult; - - strResult = "[ "; - for (int i = 0; i < len; i++) { - strResult += String.format("%d", array[i]); - if (i != len - 1) strResult += ", "; - } - strResult += " ]"; - - return strResult; - } - - // -- Matrix Transpose -- // - public void transpose() throws NullMatrixException { - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - - int[ ][ ] transposedMatrix; // create null matrix - - if (this.isSquare) { - // Initialize new matrix with same size as MATRIX size - transposedMatrix = new int[this.ROWS][this.COLS]; - - // Iterate over elements and tranpose each element - for (int i = 0; i < this.ROWS; i++) { - for (int j = 0; j < this.COLS; j++) { - transposedMatrix[i][j] = this.MATRIX[j][i]; - } - } - } else { - // Initialize new matrix with inverted size as MATRIX size - /* - - rows = columns - - columns = rows - */ - transposedMatrix = new int[this.COLS][this.ROWS]; - - for (int i = 0; i < this.COLS; i++) { - for (int j = 0; j < this.ROWS; j++) { - transposedMatrix[i][j] = this.MATRIX[j][i]; - } - } - - this.create(this.COLS, this.ROWS); // transpose matrix size - } - - this.MATRIX = transposedMatrix; // assign with transposed matrix - } - - public static int[ ][ ] transpose(int[ ][ ] matrix) - throws NullMatrixException { - if (matrix == null) { - throw new NullMatrixException(); - } - - boolean isSquare; - int[ ][ ] transposedMatrix; - - final int rows = matrix.length, - cols = matrix[0].length; - - if (rows == cols) { - isSquare = true; - } else { - isSquare = false; - } - - if (isSquare) { - transposedMatrix = new int[rows][cols]; - - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - transposedMatrix[i][j] = matrix[j][i]; - } - } - } else { - transposedMatrix = new int[cols][rows]; - - for (int i = 0; i < cols; i++) { - for (int j = 0; j < rows; j++) { - transposedMatrix[i][j] = matrix[j][i]; - } - } - } - - return transposedMatrix; - } - - public static Matrix transpose(Matrix other) - throws NullMatrixException { - if (other == null) { - throw new NullMatrixException(); - } - - Matrix transposedMatrix = new Matrix(other.ROWS, other.COLS); - - transposedMatrix.MATRIX = Matrix.transpose(other.MATRIX); - - return transposedMatrix; - } - - // -- Matrix Cleaner (assign 0 to each element) -- // - public void clear() throws NullMatrixException { - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - - for (int r = 0; r < this.ROWS; r++) { - for (int c = 0; c < this.COLS; c++) { - this.MATRIX[r][c] = 0; - } - } - this.index = 0; // reset the index row - } - - // -- Matrix Sorter -- // - public void sort() throws NullMatrixException { - if (this.MATRIX == null) { - throw new NullMatrixException(); - } - - // Just simply iterate matrix rows, then sort each columns - for (int r = 0; r < this.ROWS; r++) { - Arrays.sort(this.MATRIX[r]); - } - } - - public static void sort(int[ ][ ] matrix) throws NullMatrixException { - if (matrix == null) { - throw new NullMatrixException(); - } - - for (int r = 0; r < matrix.length; r++) { - Arrays.sort(matrix[r]); - } - } - - // -- Matrix Size -- // - public int[ ] getSize() { - // It would return list: [, ] - final int[ ] size = { this.ROWS, this.COLS }; - return size; - } -} diff --git a/lib/matrix/MatrixArrayFullException.java b/lib/matrix/MatrixArrayFullException.java deleted file mode 100644 index f343df9..0000000 --- a/lib/matrix/MatrixArrayFullException.java +++ /dev/null @@ -1,31 +0,0 @@ -package lib.matrix; - -import java.lang.Exception; - -public class MatrixArrayFullException extends Exception -{ - private String message = "Matrix array is full, can not be added anymore"; - - public MatrixArrayFullException() { - super(); - } - - public MatrixArrayFullException(String message) { - super(message); - this.message = message; - } - - public MatrixArrayFullException(Throwable cause) { - super(cause); - } - - @Override - public String getMessage() { - return this.message; - } - - @Override - public String toString() { - return this.message; - } -} diff --git a/lib/matrix/NullMatrixException.java b/lib/matrix/NullMatrixException.java deleted file mode 100644 index 1749cac..0000000 --- a/lib/matrix/NullMatrixException.java +++ /dev/null @@ -1,31 +0,0 @@ -package lib.matrix; - -import java.lang.Exception; - -public class NullMatrixException extends Exception -{ - private String message = "Matrix array is null"; - - public NullMatrixException() { - super(); - } - - public NullMatrixException(String message) { - super(message); - this.message = message; - } - - public NullMatrixException(Throwable cause) { - super(cause); - } - - @Override - public String getMessage() { - return this.message; - } - - @Override - public String toString() { - return this.message; - } -} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..56611db --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +beautifulsoup4>=4.11.1 +lxml>=4.9.1 diff --git a/src/com/mitsuki/jmatrix/Main.java b/src/com/mitsuki/jmatrix/Main.java new file mode 100644 index 0000000..803041c --- /dev/null +++ b/src/com/mitsuki/jmatrix/Main.java @@ -0,0 +1,74 @@ +package com.mitsuki.jmatrix; + +import java.io.IOException; +import java.io.FileNotFoundException; +import java.lang.IllegalArgumentException; +import java.lang.NullPointerException; + +import com.mitsuki.jmatrix.util.Options; +import com.mitsuki.jmatrix.util.OSUtils; +import com.mitsuki.jmatrix.util.XMLParser; + +public class Main +{ + private static int errCode = 0; + + public static void main(String[ ] args) { + String arg1 = null, + arg2 = null; + + XMLParser XML = new XMLParser(XMLParser.XMLType.CONFIG); + + if (args.length >= 1 && args.length < 2) { + arg1 = args[0]; + if (args.length == 2) { + arg2 = args[1]; + } + } + else if (args.length > 1) { + try { + throw new IllegalArgumentException("Too much arguments"); + } catch (final Exception e) { + Options.raiseErrorMsg(e, 0); + System.out.println(Options.getHelpMsg()[0]); + System.out.println(" " + + "java -jar [-h|-V|-cr]"); + return; + } + } + + if (arg1 == null) { + try { + throw new NullPointerException("Null argument"); + } catch (final Exception e) { + String helps[ ] = Options.getHelpMsg(); + Options.raiseErrorMsg(e, 0); + + for (int i = 0; i < helps.length; i++) { + if (i >= 7) break; + System.out.println(helps[i]); + } + return; + } + } + + switch (Options.getOptions(arg1)) { + case VERSION: + System.out.print(XML.getProperty("programName") + " " + + XML.getProperty("version") + "-"); + System.out.print(XML.getProperty("releaseType")); + System.out.printf(" <%s>\n", XML.getProperty("packageName")); + break; + + case HELP: + System.out.println(XML.getProperty("programName") + " " + + XML.getProperty("version")); + for (String s : Options.getHelpMsg()) System.out.println(s); + break; + + case COPYRIGHT: + for (String s : Options.getCopyright()) System.out.println(s); + break; + } + } +} diff --git a/src/com/mitsuki/jmatrix/Matrix.java b/src/com/mitsuki/jmatrix/Matrix.java new file mode 100644 index 0000000..8c1c182 --- /dev/null +++ b/src/com/mitsuki/jmatrix/Matrix.java @@ -0,0 +1,1399 @@ +// :: ------------------- :: // +/* -- JMATRIX BUILDER -- */ +// :: ------------------- :: // + +// Developed by Ryuu Mitsuki + +/* + --- LIST FUNCTION --- + + Non-static function(s): + - Matrix select(int); + + - Matrix copy(); + + - void add(int...); + - void add(int); + + - void change(int...); + - void change(int); + + - void sum(Matrix); + - void sum(int[ ][ ]); + + - void sub(Matrix); + - void sub(int[ ][ ]); + + - void mult(Matrix); + - void mult(int[ ][ ]); + + - void transpose(); + + - void display(); + - void display(int); + + - void sort(); + + - int[ ] getSize(); + + - void clear(); + + + Static function(s): + - int[ ][ ] sum(int[ ][ ], int[ ][ ]); + - Matrix sum(Matrix, Matrix); + + - int[ ][ ] sub(int[ ][ ], int[ ][ ]); + - Matrix sub(Matrix, Matrix); + + - int[ ][ ] mult(int[ ][ ], int[ ][ ]); + - Matrix mult(Matrix, Matrix); + + - int[ ][ ] transpose(int[ ][ ]); + - Matrix transpose(Matrix); + + - void display(int[ ][ ]); + - void display(int[ ][ ], int); + + - void sort(int[ ][ ]); +*/ + +package com.mitsuki.jmatrix; + +// -**- Built-in Package -**- // +import java.util.Arrays; +import java.lang.Math; + +// -**- Local Package -**- // +import com.mitsuki.jmatrix.core.*; +import com.mitsuki.jmatrix.util.Options; + +// ** MATRIX CLASS ** // +public class Matrix +{ + // - Private attributes + private int[ ][ ] MATRIX = null; // Create null matrix + private int ROWS = 0, // Initialize matrix rows + COLS = 0, // Initialize matrix columns + index = 0, // Index for add() function + selectedIndex = -1; + + private boolean isSquare; // boolean for check a square matrix + + + //// ----------------- //// + // -**- CONSTRUCTOR -**- // + //// ----------------- //// + + /* -- Matrix() -- + * Matrix constructor without parameter, would create null matrix + * + * @return Null Matrix object + */ + public Matrix() {} + + + /* -- Matrix() -- + * Matrix constructor with 2 parameters + * + * @param rows - Value size for matrix rows + * @param cols - Value size for matrix columns + * + * @return Create Matrix array with specified rows and columns + */ + public Matrix(int rows, int cols) { + this.ROWS = rows; + this.COLS = cols; + this.MATRIX = new int[rows][cols]; + + if (rows != cols) { + this.isSquare = false; + } else { + this.isSquare = true; + } + } + + + /* -- Matrix() -- + * Matrix constructor with 3 parameter: + * + * @param rows - Value size for matrix rows + * @param cols - Value size for matrix columns + * @param val - Value for fill the entire elements of matrix array + * + * @return Create Matrix array with specified rows and columns, then fill entire elements with specified value + */ + public Matrix(int rows, int cols, int val) { + this.ROWS = rows; + this.COLS = cols; + + this.MATRIX = new int[rows][cols]; + + if (rows != cols) { + this.isSquare = false; + } else { + this.isSquare = true; + } + + // Fill all elements inside matrix array with "val" + for (int r = 0; r < rows; r++) { + for (int c = 0; c < cols; c++) { + this.MATRIX[r][c] = val; + } + } + } + //// ----------------------- //// + // -**- [END] CONSTRUCTOR -**- // + //// ----------------------- //// + + + /* -- Matrix() -- + * Create new Matrix, it can be called even the Matrix object isn't null + * + * @param rows - Size for new Matrix rows + * @param cols - Size for new Matrix columns + * + * @return Create new Matrix array with specified rows and columns + */ + public void create(int rows, int cols) { + this.ROWS = rows; + this.COLS = cols; + this.MATRIX = new int[rows][cols]; + + this.index = 0; // reset index row + + if (rows != cols) { + this.isSquare = false; + } else { + this.isSquare = true; + } + } + + + /* -- copy() -- + * Copy the Matrix object to another Matrix object + * + * @return Copied Matrix object and all attributes + */ + public Matrix copy() { + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Matrix is null, cannot copy matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new and copy the matrix + Matrix copiedMatrix = new Matrix(this.ROWS, this.COLS); + copiedMatrix.MATRIX = this.MATRIX; + + return copiedMatrix; + } + + + /* -- select() -- + * Select index of Matrix rows, this method should be combined with "change()" method. Instead it'll just do nothing + * + * @param index - Index row that want to be selected + * @return Matrix - Return itself + */ + public Matrix select(final int index) { + // Check for null matrix + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Matrix array is null, cannot select matrix row"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Check for negative value + if (index < 0) { + try { + throw new InvalidIndexException("Index must be positive value"); + } catch (final InvalidIndexException iie) { + try { + throw new JMBaseException(iie); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + // Check for given index is greater than total rows + } else if (index > this.ROWS - 1) { + try { + throw new InvalidIndexException("Index is too large than total matrix rows"); + } catch (final InvalidIndexException iie) { + try { + throw new JMBaseException(iie); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + this.selectedIndex = index; + + return this; // return self + } + + + //// ---------------- //// + // -**- ADD VALUES -**- // + //// ---------------- //// + + /* -- add() -- + * Fill column with list of Integer(s) (int...) or Integer array (int[ ]) + * + * @param values - Values to be added into column. It can be Integer array (int[ ]) or you can write the values one by one + */ + public void add(int... values) { + // Throw "NullMatrixException" when matrix array is null + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Matrix array is null, cannot be added values"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + /** --- + - I've created add() function, that would only fill a row + when index isn't equal to total of matrix rows. + - Throw "MatrixArrayFullException" while attempt to add + new column when index has equal to total matrix rows + --- **/ + else if (this.index >= this.ROWS) { + try { + throw new MatrixArrayFullException("Matrix array is already full, cannot add some values anymore"); + } catch (final MatrixArrayFullException mafe) { + try { + throw new JMBaseException(mafe); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Length of values list shouldn't greater than total matrix columns + else if (values.length > this.COLS) { + try { + throw new IllegalMatrixSizeException("Too many arguments; Max column: " + this.COLS); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // And shouldn't be less than total matrix columns + else if (values.length < this.COLS) { + try { + throw new IllegalMatrixSizeException("Not enough argument"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Iterate values list and fill elements of matrix array + int i = 0; + for (int val : values) { + this.MATRIX[this.index][i++] = val; + } + + this.index++; // increment index row + } + + + /* -- add() -- + * Fill column with a repeated single Integer value + * + * @param value - Number value that want to fill out the column + */ + public void add(int value) { + // Throw "NullMatrixException" when matrix array is null + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Matrix array is null, cannot add some values"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + /** --- + - Throw "MatrixArrayFullExceotion" while attempt to add + a new column, but the index has equal to total matrix rows + --- **/ + else if (this.index >= this.ROWS) { + try { + throw new MatrixArrayFullException("Matrix array is already full, cannot add some values anymore"); + } catch (final MatrixArrayFullException mafe) { + try { + throw new JMBaseException(mafe); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create list of repeated value + /** --- + - Example: call add() function with single Integer + with the value 8, then it would create column: + + >> [8, 8, 8, ...] + + - Then created column would be pushed to matrix array + --- **/ + int[ ] values = new int[this.COLS]; // create list with size equal to column length + for (int i = 0; i < values.length; i++) { + values[i] = value; + } + + // Iterate values list and fill elements of matrix array + int i = 0; + for (int val : values) { + this.MATRIX[this.index][i++] = val; + } + + this.index++; // increment index row + } + //// ---------------------- //// + // -**- [END] ADD VALUES -**- // + //// ---------------------- //// + + + //// ------------------- //// + // -**- CHANGE VALUES -**- // + //// ------------------- //// + + /* -- change() -- + * Method that change all values at specified column, combine this method with "select()" method + * + * + * @param values - Values for change the specified column + */ + public void change(int... values) { + // Check size of values from argument parameter + if (values.length > this.COLS) { + try { + throw new IllegalMatrixSizeException("Too many arguments for matrix with total columns " + this.COLS); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + else if (values.length < this.COLS) { + try { + throw new IllegalMatrixSizeException("Not enough argument for matrix with total columns " + this.COLS); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Change values of matrix column with values from argument parameter + for (int i = 0; i < this.COLS; i++) { + this.MATRIX[this.selectedIndex][i] = values[i]; + } + + this.selectedIndex = -1; // reset to default + } + + + /* -- change() -- + * + * @params + * @return: void (None) + */ + public void change(int value) { + // Create new array with same value + int[ ] values = new int[this.COLS]; + for (int i = 0; i < this.COLS; i++) { + values[i] = value; + } + + for (int i = 0; i < this.COLS; i++) { + this.MATRIX[this.selectedIndex][i] = values[i]; + } + + this.selectedIndex = -1; // reset to default + } + //// ------------------------- //// + // -**- [END] CHANGE VALUES -**- // + //// ------------------------- //// + + + //// ----------------------- //// + // -**- MATRIX OPERATIONS -**- // + //// ----------------------- //// + + /* -- sum() -- + * Summarize current matrix with other matrix, + * and both matrices should be same size + * + * @params: other (Matrix class) + * @return: void (None) + */ + public void sum(Matrix other) { + // Throw "NullMatrixException" if matrix is null + if (this.MATRIX == null || other.MATRIX == null) { + try { + throw new NullMatrixException("Cannot summarize null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Else throw "IllegalMatrixSizeException" if the matrices size are not same + else if (this.ROWS != other.ROWS || this.COLS != other.COLS) { + try { + throw new IllegalMatrixSizeException("Cannot summarize two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix for the result + int[ ][ ] result = new int[this.ROWS][other.COLS]; + + // Iterate over each element of the matrices and add the corresponding values together + for (int i = 0; i < this.ROWS; i++) { + for (int j = 0; j < this.COLS; j++) { + result[i][j] = this.MATRIX[i][j] + other.MATRIX[i][j]; + } + } + + this.MATRIX = result; // copy the result to Matrix + } + + + /* -- sum() -- + * Summarize current matrix with list of Integer array, + * both should be same size + * + * @params: matrix (List of Integer array) + * @return: void (None) + */ + public void sum(int[ ][ ] matrix) { + // Throw "NullMatrixException" if matrix is null + if (this.MATRIX == null || matrix == null) { + try { + throw new NullMatrixException("Cannot summarize null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Else throw "IllegalMatrixSizeException" if the matrices are not same size + else if (this.ROWS != matrix.length || this.COLS != matrix[0].length) { + try { + throw new IllegalMatrixSizeException("Cannot summarize two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix for the result + int[ ][ ] result = new int[this.ROWS][matrix[0].length]; + + // Using nested loop for iterate over each element of matrix + for (int i = 0; i < this.ROWS; i++) { + for (int j = 0; j < this.COLS; j++) { + result[i][j] = this.MATRIX[i][j] + matrix[i][j]; + } + } + + this.MATRIX = result; // copy the result to Matrix + } + + + /* -- sum() -- + * Summarize two list of Integer array, + * both should be same size + * + * @params: + * - matrixA (List of Integer array) + * - matrixB (List of Integer array) + * @return: + * int[ ][ ] (List of Integer array) + */ + public static int[ ][ ] sum(int[ ][ ] matrixA, int[ ][ ] matrixB) { + // Throw "NullMatrixException" if matrix array is null + if (matrixA == null || matrixB == null) { + try { + throw new NullMatrixException("Cannot summarize null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Else throw "IllegalMatrixSizeException" if the both matrices and are not same size + else if (matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { + try { + throw new IllegalMatrixSizeException("Cannot summarize two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create a new matrix array + int[ ][ ] result = new int[matrixA.length][matrixB[0].length]; + + for (int i = 0; i < matrixA.length; i++) { + for (int j = 0; j < matrixB[0].length; j++) { + result[i][j] = matrixA[i][j] + matrixB[i][j]; + } + } + + return result; + } + + + /* -- sum() -- + * Summarize two matrices object, + * both matrices should be same size + * + * @params: + * - matrixA (Matrix class) + * - matrixB (Matrix class) + * @return: Matrix (Matrix class) + */ + public static Matrix sum(Matrix matrixA, Matrix matrixB) { + if (matrixA.MATRIX == null || matrixB.MATRIX == null) { + try { + throw new NullMatrixException("Cannot summarize null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + else if (matrixA.MATRIX.length != matrixB.MATRIX.length || + matrixA.MATRIX[0].length != matrixB.MATRIX[0].length) { + try { + throw new IllegalMatrixSizeException("Cannot summarize two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix object + Matrix matrixRes = new Matrix(matrixA.MATRIX.length, matrixB.MATRIX[0].length); + + for (int i = 0; i < matrixA.MATRIX.length; i++) { + for (int j = 0; j < matrixB.MATRIX[0].length; j++) { + matrixRes.MATRIX[i][j] = matrixA.MATRIX[i][j] + matrixB.MATRIX[i][j]; + } + } + + return matrixRes; + } + + + + /* -- sub() -- + * Subtract current matrix with other matrix object, + * both matrices should be same size + * + * @params: other (Matrix class) + * @return: void (None) + */ + public void sub(Matrix other) { + // Throw "NullMatrixException" if matrix is null + if (this.MATRIX == null || other.MATRIX == null) { + try { + throw new NullMatrixException("Cannot subtract null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Else throw "IllegalMatrixSizeException" if the matrices are not same size + else if (this.ROWS != other.ROWS || this.COLS != other.COLS) { + try { + throw new IllegalMatrixSizeException("Cannot subtract two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix for the result + int[ ][ ] result = new int[this.ROWS][other.COLS]; + + // Iterate over each element of all matrices and subtract each values together + for (int i = 0; i < this.ROWS; i++) { + for (int j = 0; j < this.COLS; j++) { + result[i][j] = this.MATRIX[i][j] - other.MATRIX[i][j]; + } + } + + this.MATRIX = result; // copy the result to Matrix + } + + + /* -- sub() -- + * Subtract current matrix with list of Integer array, + * both should be same size + * + * @params: matrix (list of Integer array) + * @return: void (None) + */ + public void sub(int[ ][ ] matrix) { + // Throw "NullMatrixException" if matrix is null + if (this.MATRIX == null || matrix == null) { + try { + throw new NullMatrixException("Cannot subtract null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Else throw "IllegalMatrixSizeException" if the matrices are not same size + else if (this.ROWS != matrix.length || this.COLS != matrix[0].length) { + try { + throw new IllegalMatrixSizeException(); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix for the result + int[ ][ ] result = new int[this.ROWS][matrix[0].length]; + + // Iterate over each element of all matrices and subtract each values together + for (int i = 0; i < this.ROWS; i++) { + for (int j = 0; j < this.COLS; j++) { + result[i][j] = this.MATRIX[i][j] - matrix[i][j]; + } + } + + this.MATRIX = result; // copy the result to Matrix + } + + + /* -- sub() -- + * Subtract two list of Integer array, + * both should be same size + * + * @params: + * - matrixA (List of Integer array) + * - matrixB (List of Integer array) + * @return: int[ ][ ] (List of Integer array) + */ + public static int[ ][ ] sub(int[ ][ ] matrixA, int[ ][ ] matrixB) { + // Throw "NullMatrixException" if matrix array is null + if (matrixA == null || matrixB == null) { + try { + throw new NullMatrixException("Cannot subtract null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + // Else throw "IllegalMatrixSizeException" if the both matrix and are not same size + else if (matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { + try { + throw new IllegalMatrixSizeException("Cannot subtract two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create a new matrix array + int[ ][ ] result = new int[matrixA.length][matrixB[0].length]; + + for (int i = 0; i < matrixA.length; i++) { + for (int j = 0; j < matrixB[0].length; j++) { + result[i][j] = matrixA[i][j] - matrixB[i][j]; + } + } + + return result; + } + + + /* -- sub() -- + * Subtract two matrices object, + * both matrices should be same size + * + * @params: + * - matrixA (Matrix class) + * - matrixB (Matrix class) + * @return: Matrix (Matrix class) + */ + public static Matrix sub(Matrix matrixA, Matrix matrixB) { + if (matrixA.MATRIX == null || matrixB.MATRIX == null) { + try { + throw new NullMatrixException("Cannot subtract null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + else if (matrixA.MATRIX.length != matrixB.MATRIX.length || + matrixA.MATRIX[0].length != matrixB.MATRIX[0].length) { + try { + throw new IllegalMatrixSizeException("Cannot subtract two matrices with different size"); + } catch (final IllegalMatrixSizeException imse) { + try { + throw new JMBaseException(imse); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix object + Matrix matrixRes = new Matrix(matrixA.MATRIX.length, matrixB.MATRIX[0].length); + + for (int i = 0; i < matrixA.MATRIX.length; i++) { + for (int j = 0; j < matrixB.MATRIX[0].length; j++) { + matrixRes.MATRIX[i][j] = matrixA.MATRIX[i][j] - matrixB.MATRIX[i][j]; + } + } + + return matrixRes; + } + + + + /* -- multCell() -- + * + * @params: + * - matrixA (List of Integer array) + * - matrixB (List of Integer array) + * @return: int (Integer) + */ + private static int multCell(int[ ][ ] matrixA, int[ ][ ] matrixB, int row, int col) { + int result = 0; + for (int i = 0; i < matrixB.length; i++) { + result += matrixA[row][i] * matrixB[i][col]; + } + + return result; + } + + + /* -- mult() -- + * Multiply current matrix with other matrix + * + * @params: other (Matrix class) + * @return: void (None) + */ + public void mult(Matrix other) { + if (this.MATRIX == null || other.MATRIX == null) { + try { + throw new NullMatrixException("Cannot multiply null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix array + int[ ][ ] multiplyResult = new int[this.ROWS][other.MATRIX[0].length]; + + // Iterate and multiply each element + for (int r = 0; r < multiplyResult.length; r++) { + for (int c = 0; c < multiplyResult[r].length; c++) { + multiplyResult[r][c] = this.multCell(this.MATRIX, other.MATRIX, r, c); + } + } + + this.MATRIX = multiplyResult; + } + + + /* -- mult() -- + * Multiply current matrix with list of Integer array + * + * @params: matrix (List of Integer array) + * @return: void (None) + */ + public void mult(int[ ][ ] matrix) { + if (this.MATRIX == null || matrix == null) { + try { + throw new NullMatrixException("Cannot multiply null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix array + int[ ][ ] multiplyResult = new int[this.ROWS][matrix[0].length]; + + // Iterate and multiply each element + for (int r = 0; r < multiplyResult.length; r++) { + for (int c = 0; c < multiplyResult[r].length; c++) { + multiplyResult[r][c] = this.multCell(this.MATRIX, matrix, r, c); + } + } + + this.MATRIX = multiplyResult; + } + + + /* -- mult() -- + * Multiply two list of Integer array + * + * @params: + * - matrixA (List of Integer array) + * - matrixB (List of Integer array) + * @return: int[ ][ ] (List of Integer array) + */ + public static int[ ][ ] mult(int[ ][ ] matrixA, int[ ][ ] matrixB) + throws NullMatrixException { + if (matrixA == null || matrixB == null) { + throw new NullMatrixException("Can not iterate null matrix"); + } + + int[ ][ ] multiplyResult = new int[matrixA.length][matrixB[0].length]; + + for (int r = 0; r < multiplyResult.length; r++) { + for (int c = 0; c < multiplyResult[r].length; c++) { + multiplyResult[r][c] = multCell(matrixA, matrixB, r, c); + } + } + + return multiplyResult; + } + + + /* -- mult() -- + * Multiply two matrices object + * + * @params: + * - matrixA (Matrix class) + * - matrixB (Matrix class) + * @return: Matrix (Matrix class) + */ + public static Matrix mult(Matrix matrixA, Matrix matrixB) { + if (matrixA.MATRIX == null || matrixB.MATRIX == null) { + try { + throw new NullMatrixException("Can not iterate null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Create new matrix object + Matrix matrixMultResult = new Matrix(matrixA.MATRIX.length, matrixB.MATRIX[0].length); + + for (int r = 0; r < matrixMultResult.MATRIX.length; r++) { + for (int c = 0; c < matrixMultResult.MATRIX[r].length; c++) { + matrixMultResult.MATRIX[r][c] = multCell(matrixA.MATRIX, matrixB.MATRIX, r, c); + } + } + + return matrixMultResult; + } + + //// ----------------------------- //// + // -**- [END] MATRIX OPERATIONS -**- // + //// ----------------------------- //// + + + + /* -- display() -- + * Method that will print out/display current matrix array + * Output example: + * [ [ n, n, n, ... ] + * [ n, n, n, ... ] + * [ .. .. .. ... ] ] + * + * @params: void (None) + * @return: void (None) + */ + public final void display() { + // Throw "NullMatrixException" if matrix array is null + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Cannot display null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + System.out.print("[ "); + for (int r = 0; r < this.ROWS; r++) { + System.out.print(this.toString(this.MATRIX[r])); + if (r != this.ROWS - 1) { + System.out.print("\n "); + } + } + System.out.println(" ]"); + } + + + /* -- display() -- + * Method that will print out/display specific matrix column + * + * @params: index (Integer) + * @return: void (None) + */ + public final void display(int index) { + // Check whether matrix array is null or not + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Cannot display null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Checking index value from argument parameter + if (index < 0) { + try { + throw new InvalidIndexException("Index must be positive value"); + } catch (final InvalidIndexException iie) { + try { + throw new JMBaseException(iie); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } else if (index > this.ROWS - 1) { + try { + throw new InvalidIndexException("Index is too large than total matrix rows"); + } catch (final InvalidIndexException iie) { + try { + throw new JMBaseException(iie); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + System.out.println(this.toString(this.MATRIX[index])); + } + + + /* -- display() -- + * Method that will print out/display matrix array + * + * @params: matrix (List of Integer array) + * @return: void (None) + */ + public static final void display(int[ ][ ] matrix) { + // Throw "NullMatrixException" if matrix array is null + if (matrix == null) { + try { + throw new NullMatrixException("Cannot display null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + final int rows = matrix.length; + final int cols = matrix[0].length; + + System.out.print("[ "); + for (int r = 0; r < rows; r++) { + System.out.print(toString(matrix[r])); + if (r != rows - 1) { + System.out.print("\n "); + } + } + System.out.println(" ]"); + } + + + /* -- display() -- + * Method that will print out/display specific matrix column + * + * @params: + * - matrix (List of Integer array) + * - index (Integer) + * @return: void (None) + */ + public static final void display(int[ ][ ] matrix, int index) { + if (matrix == null) { + try { + throw new NullMatrixException("Cannot display null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Checking index value + if (index < 0) { + try { + throw new InvalidIndexException("Index must be positive value"); + } catch (final InvalidIndexException iie) { + try { + throw new JMBaseException(iie); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } else if (index > matrix.length - 1) { + try { + throw new InvalidIndexException("Index is too large than total matrix rows"); + } catch (final InvalidIndexException iie) { + try { + throw new JMBaseException(iie); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + System.out.println(toString(matrix[index])); + } + + + /* -- toString() -- + * Method that convert Integer array to String + * + * @params: array (Integer array) + * @return: String + */ + private static String toString(int[ ] array) { + final int len = array.length; + String strResult; + + strResult = "[ "; + for (int i = 0; i < len; i++) { + strResult += String.format("%d", array[i]); + if (i != len - 1) strResult += ", "; + } + strResult += " ]"; + + return strResult; + } + + + /* -- transpose() -- + * Method that will transpose current matrix array + * + * @params: void (None) + * @return: void (None) + */ + public void transpose() { + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Cannot transpose null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + int[ ][ ] transposedMatrix; // create null transposed matrix + + if (this.isSquare) { + // Initialize new matrix with same size as MATRIX size + transposedMatrix = new int[this.ROWS][this.COLS]; + + // Iterate over elements and tranpose each element + for (int i = 0; i < this.ROWS; i++) { + for (int j = 0; j < this.COLS; j++) { + transposedMatrix[i][j] = this.MATRIX[j][i]; + } + } + } else { + // Initialize new matrix with inverted size as MATRIX size + /* + - rows = columns + - columns = rows + */ + transposedMatrix = new int[this.COLS][this.ROWS]; + + for (int i = 0; i < this.COLS; i++) { + for (int j = 0; j < this.ROWS; j++) { + transposedMatrix[i][j] = this.MATRIX[j][i]; + } + } + + this.create(this.COLS, this.ROWS); // transpose matrix size + } + + this.MATRIX = transposedMatrix; // assign with transposed matrix + } + + + /* -- transpose() -- + * Method that will transpose given list of Integer array + * + * @params: matrix (List of Integer array) + * @return: int[ ][ ] (List of Integer array) + */ + public static int[ ][ ] transpose(int[ ][ ] matrix) { + if (matrix == null) { + try { + throw new NullMatrixException("Cannot transpose null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + boolean isSquare; + int[ ][ ] transposedMatrix; // create null transposed matrix + + final int rows = matrix.length, + cols = matrix[0].length; + + // Check for square matrix + if (rows == cols) { + isSquare = true; + } else { + isSquare = false; + } + + /** --- + - If the matrix type is square matrix, then transposed matrix + - size should be same as previous matrix size. + - However, if not a square matrix then the transposed matrix + - size should be inverted + --- **/ + if (isSquare) { + transposedMatrix = new int[rows][cols]; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + transposedMatrix[i][j] = matrix[j][i]; + } + } + } else { + transposedMatrix = new int[cols][rows]; + + for (int i = 0; i < cols; i++) { + for (int j = 0; j < rows; j++) { + transposedMatrix[i][j] = matrix[j][i]; + } + } + } + + return transposedMatrix; + } + + + /* -- transpose() -- + * Method that will transpose given matrix array + * + * @params: other (Matrix class) + * @return: Matrix (Matrix class) + */ + public static Matrix transpose(Matrix other) { + if (other == null) { + try { + throw new NullMatrixException("Cannot transpose null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + Matrix transposedMatrix = new Matrix(other.ROWS, other.COLS); + + transposedMatrix.MATRIX = Matrix.transpose(other.MATRIX); + + return transposedMatrix; + } + + + + /* -- clear() -- + * Method that clearing all values inside current matrix array + * + * @params: void (None) + * @return: void (None) + */ + public void clear() { + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Cannot clearing all values inside null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + for (int r = 0; r < this.ROWS; r++) { + for (int c = 0; c < this.COLS; c++) { + this.MATRIX[r][c] = 0; + } + } + this.index = 0; // reset the index row + } + + + /* -- sort() -- + * Method that will sort each columns matrix + * + * @params: void (None) + * @return: void (None) + */ + public void sort() { + if (this.MATRIX == null) { + try { + throw new NullMatrixException("Cannot sorting values inside null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + // Just simply iterate matrix rows, then sort each columns + for (int r = 0; r < this.ROWS; r++) { + Arrays.sort(this.MATRIX[r]); + } + } + + + /* -- sort() -- + * Method that will sort each columns given matrix + * + * @params: matrix (List of Integer array) + * @return: void (None) + */ + public static void sort(int[ ][ ] matrix) { + if (matrix == null) { + try { + throw new NullMatrixException("Cannot sorting values inside null matrix"); + } catch (final NullMatrixException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + Options.raiseError(jme); + } + } + } + + for (int r = 0; r < matrix.length; r++) { + Arrays.sort(matrix[r]); + } + } + + + /* -- getSize() -- + * Get size of current matrix array + * + * @params: void (None) + * @return: int[ ] (Integer array) + */ + public int[ ] getSize() { + // It would return list: [, ] + final int[ ] size = { this.ROWS, this.COLS }; + return size; + } +} diff --git a/src/com/mitsuki/jmatrix/core/IllegalMatrixSizeException.java b/src/com/mitsuki/jmatrix/core/IllegalMatrixSizeException.java new file mode 100644 index 0000000..c81142e --- /dev/null +++ b/src/com/mitsuki/jmatrix/core/IllegalMatrixSizeException.java @@ -0,0 +1,36 @@ +// :: ---------------------------- :: // +/* -- IllegalMatrixSizeException -- */ +// :: ---------------------------- :: // + +package com.mitsuki.jmatrix.core; + +import com.mitsuki.jmatrix.core.JMBaseException; + +public class IllegalMatrixSizeException extends JMBaseException +{ + private String message = null; + + public IllegalMatrixSizeException() { + super(); + } + + public IllegalMatrixSizeException(String message) { + super(message); + this.message = message; + } + + public IllegalMatrixSizeException(Throwable cause) { + super(cause); + this.message = cause.getMessage(); + } + + @Override + public String getMessage() { + return this.message; + } + + @Override + public String toString() { + return String.format("%s: %s", this.getClass().getName(), this.message); + } +} diff --git a/lib/matrix/InvalidIndexException.java b/src/com/mitsuki/jmatrix/core/InvalidIndexException.java similarity index 67% rename from lib/matrix/InvalidIndexException.java rename to src/com/mitsuki/jmatrix/core/InvalidIndexException.java index 8ec3877..1ab4b31 100644 --- a/lib/matrix/InvalidIndexException.java +++ b/src/com/mitsuki/jmatrix/core/InvalidIndexException.java @@ -2,11 +2,11 @@ /* -- InvalidIndexException -- */ // :: ----------------------- :: // -package lib.matrix; +package com.mitsuki.jmatrix.core; -import java.lang.Exception; +import com.mitsuki.jmatrix.core.JMBaseException; -public class InvalidIndexException extends Exception +public class InvalidIndexException extends JMBaseException { private String message = null; @@ -21,6 +21,7 @@ public InvalidIndexException(String message) { public InvalidIndexException(Throwable cause) { super(cause); + this.message = cause.getMessage(); } @Override @@ -30,6 +31,6 @@ public String getMessage() { @Override public String toString() { - return this.message; + return String.format("%s: %s", this.getClass().getName(), this.message); } } diff --git a/src/com/mitsuki/jmatrix/core/JMBaseException.java b/src/com/mitsuki/jmatrix/core/JMBaseException.java new file mode 100644 index 0000000..216172c --- /dev/null +++ b/src/com/mitsuki/jmatrix/core/JMBaseException.java @@ -0,0 +1,104 @@ +// :: --------------------- :: // +/* -- JMBaseException -- */ +// :: --------------------- :: // + +package com.mitsuki.jmatrix.core; + +import java.lang.RuntimeException; + +public class JMBaseException extends RuntimeException +{ + private StackTraceElement[ ] stackTraceElements = null; + private StackTraceElement[ ] causedStackTraceElements = null; + private String strException = null; + private String message = null; + private boolean isCausedException = false; + + public JMBaseException() { + this.stackTraceElements = this.getStackTrace(); + } + + public JMBaseException(String s) { + super(s); + this.message = s; + this.stackTraceElements = this.getStackTrace(); + } + + public JMBaseException(Throwable exception) { + super(exception); + this.stackTraceElements = this.getStackTrace(); + this.causedStackTraceElements = exception.getStackTrace(); + this.strException = exception.toString(); + this.message = exception.getMessage(); + this.isCausedException = true; + } + + @Override + public void printStackTrace() { + String spc = " "; + String arrow = ">>>>>>>>>>>>>"; + + if (this.isCausedException && this.stackTraceElements.length > 2) { + System.err.printf("/!\\ EXCEPTION%s%s%s", + System.lineSeparator(), + arrow, + System.lineSeparator()); + System.err.println(this.toString()); + + for (int i = this.stackTraceElements.length - 2; i != this.stackTraceElements.length; i++) { + System.err.printf("%sat \"%s.%s\" -> \"%s\": line %d" + System.lineSeparator(), + spc, + this.stackTraceElements[i].getClassName(), + this.stackTraceElements[i].getMethodName(), + this.stackTraceElements[i].getFileName(), + this.stackTraceElements[i].getLineNumber()); + } + } else { + System.err.printf("/!\\ EXCEPTION%s%s%s", + System.lineSeparator(), + arrow, + System.lineSeparator()); + System.err.println(this.toString()); + + for (StackTraceElement ste : this.stackTraceElements) { + System.err.printf("%sat \"%s.%s\" -> \"%s\": line %d" + System.lineSeparator(), + spc, + ste.getClassName(), + ste.getMethodName(), + ste.getFileName(), + ste.getLineNumber()); + } + } + + if (this.isCausedException) { + System.err.printf("%s/!\\ CAUSED BY%s%s%s", + System.lineSeparator(), + System.lineSeparator(), + arrow, + System.lineSeparator()); + System.err.println(this.strException); + + for (StackTraceElement cste : this.causedStackTraceElements) { + System.err.printf("%sat \"%s.%s\" -> \"%s\": line %d" + System.lineSeparator(), + spc, + cste.getClassName(), + cste.getMethodName(), + cste.getFileName(), + cste.getLineNumber()); + } + } + System.err.println(System.lineSeparator() + "[EXCEPTION INFO]"); + System.err.println("Type: " + ((this.isCausedException) ? this.strException.split(":\s")[0] : this.getClass().getName())); + System.err.println("Message: " + this.message); + } + + @Override + public String getMessage() { + return this.message; + } + + @Override + public String toString() { + return String.format("%s: %s", this.getClass().getName(), (this.isCausedException ? this.strException : this.message)); + } +} diff --git a/src/com/mitsuki/jmatrix/core/MatrixArrayFullException.java b/src/com/mitsuki/jmatrix/core/MatrixArrayFullException.java new file mode 100644 index 0000000..4296d3d --- /dev/null +++ b/src/com/mitsuki/jmatrix/core/MatrixArrayFullException.java @@ -0,0 +1,36 @@ +// :: -------------------------- :: // +/* -- MatrixArrayFullException -- */ +// :: -------------------------- :: // + +package com.mitsuki.jmatrix.core; + +import com.mitsuki.jmatrix.core.JMBaseException; + +public class MatrixArrayFullException extends JMBaseException +{ + private String message = null; + + public MatrixArrayFullException() { + super(); + } + + public MatrixArrayFullException(String message) { + super(message); + this.message = message; + } + + public MatrixArrayFullException(Throwable cause) { + super(cause); + this.message = cause.getMessage(); + } + + @Override + public String getMessage() { + return this.message; + } + + @Override + public String toString() { + return String.format("%s: %s", this.getClass().getName(), this.message); + } +} diff --git a/src/com/mitsuki/jmatrix/core/NullMatrixException.java b/src/com/mitsuki/jmatrix/core/NullMatrixException.java new file mode 100644 index 0000000..4aea4fc --- /dev/null +++ b/src/com/mitsuki/jmatrix/core/NullMatrixException.java @@ -0,0 +1,36 @@ +// :: --------------------- :: // +/* -- NullMatrixException -- */ +// :: --------------------- :: // + +package com.mitsuki.jmatrix.core; + +import com.mitsuki.jmatrix.core.JMBaseException; + +public class NullMatrixException extends JMBaseException +{ + private String message = null; + + public NullMatrixException() { + super(); + } + + public NullMatrixException(String message) { + super(message); + this.message = message; + } + + public NullMatrixException(Throwable cause) { + super(cause); + this.message = cause.getMessage(); + } + + @Override + public String getMessage() { + return this.message; + } + + @Override + public String toString() { + return String.format("%s: %s", this.getClass().getName(), this.message); + } +} diff --git a/src/com/mitsuki/jmatrix/util/OSUtils.java b/src/com/mitsuki/jmatrix/util/OSUtils.java new file mode 100644 index 0000000..e80a9b1 --- /dev/null +++ b/src/com/mitsuki/jmatrix/util/OSUtils.java @@ -0,0 +1,78 @@ +// ------------------- // +/* OSUtils */ +// ------------------- // + +// -**- Package -**- // +package com.mitsuki.jmatrix.util; + +// -**- Built-in Package -**- // +import java.io.File; + +/** +* This class provides operating system utilities
+* +* @version 1.0 +* @since 1.0.0 +* @author Ryuu Mitsuki +* +* @see com.mitsuki.jmatrix.util.Options +* @see com.mitsuki.jmatrix.util.XMLParser +*/ +public class OSUtils +{ + /** + * List name of operating system.
+ * Uses {@link OSUtils#getOSName} to gets current operating system.
+ * + * @since 1.0.0 + * @see OSUtils#getOSName + */ + public enum OS { + WINDOWS, LINUX, MAC, SOLARIS, OTHER + }; + + private static OS os = null; + + /** + * Gets path separator determined by operating system.
+ * + * @since 1.0.0 + * @see File#separator + */ + public final static String sep = File.separator; + + /** + * Method that gets current operating system name.
+ * If operating system name not available on {@link #OS}, then it will returns {@code OTHER} value.
+ * + * @return the name of current operating system + * + * @since 1.0.0 + * @see System#getProperty + * @see OSUtils#OS + */ + public static OS getOSName() { + if (os == null) { + final String osName = System.getProperty("os.name").toLowerCase(); + + if (osName.contains("win")) { + os = OS.WINDOWS; + } + else if (osName.contains("nix") || osName.contains("nux") || + osName.contains("aix")) { + os = OS.LINUX; + } + else if (osName.contains("mac")) { + os = OS.MAC; + } + else if (osName.contains("sunos")) { + os = OS.SOLARIS; + } + else { + os = OS.OTHER; // unknown operating system + } + } + + return os; + } +} diff --git a/src/com/mitsuki/jmatrix/util/Options.java b/src/com/mitsuki/jmatrix/util/Options.java new file mode 100644 index 0000000..abefc8b --- /dev/null +++ b/src/com/mitsuki/jmatrix/util/Options.java @@ -0,0 +1,566 @@ +// ------------------- // +/* Options */ +// ------------------- // + +// -**- Package -**- // +package com.mitsuki.jmatrix.util; + +// -**- Built-in Package (java.io) -**- // +import java.io.FileReader; +import java.io.FileWriter; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.FileNotFoundException; + +// -**- Built-in Package (java.lang) -**- // +import java.lang.NullPointerException; +import java.lang.IllegalArgumentException; + +// -**- Built-in Package (java.math) -**- // +import java.math.BigDecimal; +import java.math.BigInteger; + +// -**- Local Package -**- // +import com.mitsuki.jmatrix.core.JMBaseException; +import com.mitsuki.jmatrix.util.OSUtils; +import com.mitsuki.jmatrix.util.XMLParser; + +/** +* This class provides all requirements for {@code JMatrix} package.
+* +* @version 1.0 +* @since 1.0.0 +* @author Ryuu Mitsuki +* +* @see com.mitsuki.jmatrix.util.OSUtils +* @see com.mitsuki.jmatrix.util.XMLParser +*/ +public class Options +{ + /** + * {@link Enum} contains all available options.
+ * + * @since 1.0.0 + * @see #getOptions(String) + */ + public enum OPT { + VERSION, HELP, COPYRIGHT + }; + + // -- Private Attributes + private static XMLParser XML = new XMLParser(XMLParser.XMLType.CONFIG); + private static String PROGNAME = XML.getProperty("programName").toLowerCase(); + private static String PACKAGE = getPackageName(Options.class); + private static String THISCLASS = getClassName(Options.class); + private static String contentsPath = String.format("assets%scontents%s", OSUtils.sep, OSUtils.sep); + + /** + * Method that checks the input argument then returns specific option. + *
+ *
    + *
  • [{@code -V}, {@code ver}, {@code version}] -> returns {@code VERSION} value.
  • + * returns {@code HELP} value. + *
  • [{@code -cr}, {@code copyright}] -> returns {@code COPYRIGHT} value.
  • + *
+ *
+ * + * @param inputOpt the {@link String} that wants to be checked. + * + * @return the {@link Options#OPT} contains specified value. + * + * @since 1.0.0 + * @see Options#OPT + */ + public static OPT getOptions(String inputOpt) { + if (inputOpt != null) { + if (inputOpt.equals("-V") || inputOpt.equals("version") || inputOpt.equals("ver")) { + return OPT.VERSION; + } + else if (inputOpt.equals("-h") || inputOpt.equals("help")) { + return OPT.HELP; + } + else if (inputOpt.equals("-cr") || inputOpt.equals("copyright")) { + return OPT.COPYRIGHT; + } + else { + try { + throw new IllegalArgumentException(String.format("Unknown argument option for input \"%s\"", inputOpt)); + } catch (final Exception e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException ex) { + raiseError(ex, 0); + System.err.println(System.lineSeparator() + getHelpMsg()[0]); + System.err.println(" " + + "java -jar [-h|-V|-cr]"); + System.exit(-1); + } + } + } + } + + return null; + } + + + ///// ---------------------- ///// + /// Class & Packages /// + ///// ---------------------- ///// + + /** + * Gets the package name of specific class. For example: + *
+ * + * Options.getPackageName(MyClass.class); + * + *
+ * + * @param cls a class name to retrieves it's package name. + * + * @return the {@link String} that contains package name of specified class. + * + * @since 1.0.0 + * @see #getClassName(Class) + */ + public static String getPackageName(Class cls) { + return cls.getPackage().getName(); + } + + /** + * Gets the full package name (with class name) of specific class. For example: + *
+ * + * Options.getClassName(MyClass.class); + * + *
+ * + * @param cls a class name to retrieves it's full package name. + * + * @return a {@link String} that contains full package name of specified class. + * + * @since 1.0.0 + * @see #getPackageName(Class) + */ + public static String getClassName(Class cls) { + return cls.getName(); + } + + /** + * Returns the class of the given template object.
+ * + * @param template the template object to retrieve the class. + * @param the type of the template object. + * + * @return the class of the template object. + * + * @since 1.0.0 + * @see #getClassNameFromTemplate(T) + */ + public static Class getClassFromTemplate(T template) { + return (Class) template.getClass(); + } + + /** + * Returns {@code String} contains the name of the class of the given template object.
+ * + * @param template the template object to retrieves the class name from. + * @param the type of the template object. + * + * @return the name of the class of the template object. + * + * @since 1.0.0 + * @see #getClassFromTemplate(T) + */ + public static String getClassNameFromTemplate(T template) { + String fullNameClass = template.getClass().getName(); + int lastIndex = fullNameClass.lastIndexOf('.'); + + if (lastIndex == -1) { + // Return unextracted full name of class, if doesn't contain any dots + return fullNameClass; + } else { + // Extract just the class name from the full name + return fullNameClass.substring(lastIndex + 1); + } + } + + + + ///// -------------------- ///// + /// Files Options /// + ///// -------------------- ///// + + /** + * Returns the total lines of specified file.
+ * + * @param filePath a path to specific file. + * + * @return total lines of specified file. + * + * @since 1.0.0 + * @see #getLinesFile(InputStream) + * @see java.io.FileReader + * @see java.io.BufferedReader + */ + public static long getLinesFile(String filePath) { + long lines = 0; + + try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { + while (br.readLine() != null) lines++; + } catch (final IOException e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException ex) { + raiseError(ex, -1); + } + } + + return lines; + } + + /** + * Returns the total lines of specified file.
+ * + * @param stream a stream that contains path to specific file. + * + * @return total lines of specified file. + * + * @since 1.0.0 + * @see #getLinesFile(String) + * @see java.io.InputStreamReader + * @see java.io.BufferedReader + */ + public static long getLinesFile(InputStream stream) { + long lines = 0; + + try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) { + while (br.readLine() != null) lines++; + } catch (final IOException e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException ex) { + raiseError(ex, -1); + } + } + + return lines; + } + + + /** + * Reads and returns the contents of specified file.
+ * + * @param filePath a path to specific file. + * + * @return the contents of specified file. + * + * @since 1.0.0 + * @see #readFile(InputStream) + * @see java.io.BufferedReader + * @see java.io.FileReader + */ + public static String[ ] readFile(String filePath) { + try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { + return br.lines().toArray(String[ ]::new); + } catch (final IOException e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException ex) { + raiseError(ex, -1); + } + } + + return null; + } + + /** + * Reads and returns the contents of specified file.
+ * + * @param stream a stream that contains path to specific file. + * + * @return the contents of specified file. + * + * @since 1.0.0 + * @see #readFile(String) + * @see java.io.BufferedReader + * @see java.io.InputStreamReader + */ + public static String[ ] readFile(InputStream stream) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) { + return br.lines().toArray(String[ ]::new); + } catch (final IOException e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException ex) { + raiseError(ex, -1); + } + } + + return null; + } + + /** + * Returns the stream of specified file path.
+ * This method is similar to {@link java.lang.ClassLoader#getResourceAsStream(String)}, but this method is a simple way.
+ * + * @param filePath a path to specific file. + * + * @return returns the {@link java.io.InputStream} + * + * @since 1.0.0 + * @see java.lang.ClassLoader + * @see java.lang.InputStream + */ + public static InputStream getFileAsStream(String filePath) { + InputStream stream = null; + try { + ClassLoader cl = Options.class.getClassLoader(); + stream = cl.getResourceAsStream(filePath); + } catch (final NullPointerException nme) { + try { + throw new JMBaseException(nme); + } catch (final JMBaseException jme) { + raiseError(jme, -1); + } + } + + return stream; + } + + /** + * Writes the contents to specific file.
+ * + * @param filePath the {@link String} that contains path to specific file. + * @param contents the contents to be writen into specific file. + * + * @return returns {@code true} if succeed, else return {@code false} + * + * @since 1.0.0 + * @see java.io.FileWriter + */ + public static boolean writeToFile(String filePath, String[ ] contents) { + try (FileWriter fw = new FileWriter(filePath)) { + for (String line : contents) { + fw.write(line + System.lineSeparator()); + } + return true; + } catch (final IOException e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException ex) { + raiseError(ex, -1); + } + } + + return false; + } + + + ///// ------------------ ///// + /// Contents /// + ///// ------------------ ///// + + /** + * Returns the help message contents.
+ * + * @return the contents of help message. + * + * @since 1.0.0 + * @see #readFile + * @see #getFileAsStream(String) + * @see #removeComment(String[]) + */ + public static String[ ] getHelpMsg() { + return removeComment(readFile(getFileAsStream(contentsPath + "help.content"))); + } + + /** + * Returns the copyright contents.
+ * + * @return the contents of copyright. + * + * @since 1.0.0 + * @see #readFile + * @see #getFileAsStream(String) + * @see java.lang.StringBuilder + * @see com.mitsuki.jmatrix.util.XMLParser#getProperty(String) + */ + public static String[ ] getCopyright() { + final String license = readFile(getFileAsStream("LICENSE"))[0]; + final String[ ] contents = readFile(getFileAsStream(contentsPath + "additional.content")); + String[ ] copyright = new String[contents.length]; + + for (int i = 0; i < contents.length; i++) { + // Ignore the comment + if (!contents[i].startsWith("#")) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < contents[i].length(); j += 2) { + String bytes = contents[i].substring(j, j + 2); + sb.append((char) Integer.parseInt(bytes, 16)); + } + copyright[i] = sb.toString(); + } else { + copyright[i] = contents[i]; + } + } + + for (int i = 0, j = 0; i != contents.length; i++) { + if (copyright[i].contains("${PACKAGE_NAME}")) { + copyright[i] = copyright[i].replace("${PACKAGE_NAME}", XML.getProperty("programName")); + } + + if (copyright[i].contains("${AUTHOR}")) { + copyright[i] = copyright[i].replace("${AUTHOR}", XML.getProperty("author")); + } + + if (copyright[i].contains("${LICENSE}")) { + copyright[i] = copyright[i].replace("${LICENSE}", license); + } + } + + return removeComment(copyright); + } + + + /** + * Removes comment lines from an array of strings.
+ * Default set the delimiter to #.
+ * + * @param contents the array of strings containing the content. + * + * @return a new array of strings with all comment lines removed. + * + * @since 1.0.0 + * @see #removeComment(String[], String) + */ + public static String[ ] removeComment(String[ ] contents) { + return removeComment(contents, "#"); + } + + /** + * Removes comment lines that start with a specified delimiter + * from an array of strings.
+ * Most used delimiter is (#, //).
+ * + * @param contents the array of strings containing the content. + * @param del the string that specifies the delimiter. + * + * @return a new array of strings with all comment lines + * that start with the specified delimiter removed. + * + * @since 1.0.0 + * @see #removeComment(String[]) + */ + public static String[ ] removeComment(String[ ] contents, String del) { + String[ ] tmp = contents; // copy the contents + int ct = 0; + + // Count the line of contents that contains the comment + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith(del)) ct++; + } + + // If the contents doesn't contains any comment + if (ct == 0) return contents; + + // Initialize new contents + contents = new String[contents.length - ct]; + for (int i = 0, j = 0; i < tmp.length && j < contents.length; i++) { + if (!tmp[i].startsWith(del)) contents[j++] = tmp[i]; + } + + return contents; + } + + + ///// --------------------- ///// + /// Error Options /// + ///// --------------------- ///// + + /** + * Raises an error or exception and prints the stack trace of the + * input exception object and then exits the program (default exit code: 1).
+ * + * @param ex the {@code Exception} object to be printed. + * + * @since 1.0.0 + * @see #raiseError(Exception, int) + * @see #raiseErrorMsg(Exception) + * @see java.lang.Exception + * @see java.lang.Exception#printStackTrace + */ + public final static void raiseError(final Exception ex) { + ex.printStackTrace(); + System.err.println(System.lineSeparator() + + "Exited with error code: 1"); + System.exit(1); + } + + /** + * Raises an error or exception and prints the stack trace of the + * input exception object and then exits the program with the specified exit code.
+ * Sets the {@code exitStatus} to {@code 0} (zero) if don't want the program to exits.
+ * + * @param ex the {@code Exception} object to be printed. + * @param exitStatus the value that specifies the exit code. + * + * @since 1.0.0 + * @see #raiseError(Exception) + * @see #raiseErrorMsg(Exception, int) + * @see java.lang.Exception + * @see java.lang.Exception#printStackTrace + */ + public final static void raiseError(final Exception ex, final int exitStatus) { + ex.printStackTrace(); + if (exitStatus != 0) { + System.err.printf(System.lineSeparator() + + "Exited with error code: %d%s", exitStatus, System.lineSeparator()); + System.exit(exitStatus); + } + } + + + /** + * Raises an error or exception but only prints the message + * and then exits the program (default exit code: 1).
+ * + * @param ex the {@code Exception} object to prints the message. + * + * @since 1.0.0 + * @see #raiseErrorMsg(Exception, int) + * @see #raiseError(Exception) + * @see java.lang.Exception + * @see java.lang.Exception#printStackTrace + */ + public final static void raiseErrorMsg(final Exception ex) { + System.err.printf("[%s] Error: %s%s", PROGNAME, ex.getMessage(), System.lineSeparator()); + System.err.println(System.lineSeparator() + + "Exited with error code: 1"); + System.exit(1); + } + + /** + * Raises an error or exception but only prints the message + * and then exits the program with the specified exit code.
+ * Sets the {@code exitStatus} to {@code 0} (zero) if don't want the program to exits.
+ * + * @param ex the {@code Exception} object to prints the message. + * @param exitStatus the value that specifies the exit code. + * + * @since 1.0.0 + * @see #raiseErrorMsg(Exception) + * @see #raiseError(Exception, int) + * @see java.lang.Exception + * @see java.lang.Exception#printStackTrace + */ + public final static void raiseErrorMsg(final Exception ex, final int exitStatus) { + System.err.printf("[%s] Error: %s%s", PROGNAME, ex.getMessage(), System.lineSeparator()); + if (exitStatus != 0) { + System.err.printf(System.lineSeparator() + + "Exited with error code: %d%s", exitStatus, System.lineSeparator()); + System.exit(exitStatus); + } + } +} diff --git a/src/com/mitsuki/jmatrix/util/XMLParser.java b/src/com/mitsuki/jmatrix/util/XMLParser.java new file mode 100644 index 0000000..2af9166 --- /dev/null +++ b/src/com/mitsuki/jmatrix/util/XMLParser.java @@ -0,0 +1,237 @@ +///// ----------------- ///// +/// XMLParser /// +///// ----------------- ///// + +// -**- Package -**- // +package com.mitsuki.jmatrix.util; + +// -**- Built-in Package -**- // +import java.io.InputStream; +import java.io.IOException; +import java.io.FileNotFoundException; +import java.util.Scanner; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.w3c.dom.DOMException; + +// -**- Local Package -**- // +import com.mitsuki.jmatrix.core.JMBaseException; +import com.mitsuki.jmatrix.util.Options; + + +/** +* This class will contains data from parsing a config file.
+* +* @since 1.0.0 +* @author Ryuu Mitsuki +*/ +class XMLConfig +{ + static String programName = null; + static String version = null; + static String author = null; + static String packageName = null; + static String releaseType = null; +} + +/** +* This interface for now it just gets the saved config data. +* +* @since 1.0.0 +* @author Ryuu Mitsuki +*/ +interface XMLData +{ + static String getData(final String choice) { + String data = null; + + switch (choice) { + // -- config.xml -- + case "programName": + data = XMLConfig.programName; + break; + case "version": + data = XMLConfig.version; + break; + case "author": + data = XMLConfig.author; + break; + case "packageName": + data = XMLConfig.packageName; + break; + case "releaseType": + data = XMLConfig.releaseType; + break; + + default: + try { + throw new IllegalArgumentException("Cannot retrieve data for input \"" + choice + "\""); + } catch (final IllegalArgumentException iae) { + try { + throw new JMBaseException(iae); + } catch (final JMBaseException jme) { + Options.raiseError(jme, -1); + } + } + } + + return data; + } +} + + +/** +* This class provides requirements to parse XML document. Construct example: +*
+* +* XMLParser cfg = new XMLParser(XMLParser.XMLType.CONFIG); +* +*
+* +* @since 1.0.0 +* @version 1.0 +* @author Ryuu Mitsuki +* +* @see com.mitsuki.jmatrix.util.Options +* @see com.mitsuki.jmatrix.util.OSUtils +*/ +public class XMLParser implements XMLData +{ + /** + * {@code Enum} that contains types of XML document.
+ * + * @since 1.0.0 + * @see #getCurrentType() + */ + public static enum XMLType { + CONFIG + }; + + // -- Private Attributes + private static XMLType xmlType = null; + private final static String configPath = String.format("assets%sconfiguration%sconfig.xml", OSUtils.sep, OSUtils.sep); + private static InputStream configStream = null; + + + // -- Static Block + static { + configStream = XMLParser.class.getClassLoader().getResourceAsStream(configPath); + + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + + Document doc = docBuilder.parse(configStream); + Element xml = doc.getDocumentElement(); + + XMLConfig.programName = xml.getElementsByTagName("program_name").item(0).getTextContent(); + XMLConfig.author = xml.getElementsByTagName("author").item(0).getTextContent(); + XMLConfig.version = xml.getElementsByTagName("version").item(0).getTextContent(); + XMLConfig.releaseType = xml.getElementsByTagName("version").item(0) + .getAttributes().getNamedItem("type").getNodeValue(); + XMLConfig.packageName = xml.getElementsByTagName("package").item(0).getTextContent(); + } catch (final Exception e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException jme) { + Options.raiseError(jme, -1); + } + } + } + + /** + * Creates new {@code XMLParser} object.
+ * + * @param type a chosen XML type. + * + * @since 1.0.0 + */ + public XMLParser(XMLType type) { + switch (type) { + case CONFIG: + xmlType = XMLType.CONFIG; + break; + + default: + try { + throw new IllegalArgumentException("Invalid XML type for input \"" + type + "\""); + } catch (final IllegalArgumentException iae) { + try { + throw new JMBaseException(iae); + } catch (final JMBaseException jme) { + Options.raiseError(jme, -1); + } + } + } + } + + + /** + * This method retrieves the XML data.
+ * + * @param choice the {@code String} to chooses XML property. + * + * @return returns XML data if {@code choice} not {@code null}. + * + * @since 1.0.0 + */ + public String getProperty(final String choice) { + if (choice != null) { + switch (xmlType) { + case CONFIG: + return XMLData.getData(choice); + } + } + + return null; + } + + /** + * Gets current XML type.
+ * + * @return the current XML type. + * + * @since 1.0.0 + * @see XMLParser#XMLType + */ + public XMLType getCurrentType() { + return this.xmlType; + } + + + private static void initializeParser() { + try { + // -- config.xml -- + Document doc = buildToDoc(configStream); + Element xml = doc.getDocumentElement(); + + XMLConfig.programName = xml.getElementsByTagName("program_name").item(0).getTextContent(); + XMLConfig.author = xml.getElementsByTagName("author").item(0).getTextContent(); + XMLConfig.version = xml.getElementsByTagName("version").item(0).getTextContent(); + XMLConfig.releaseType = xml.getElementsByTagName("version").item(0) + .getAttributes().getNamedItem("type").getNodeValue(); + XMLConfig.packageName = xml.getElementsByTagName("package").item(0).getTextContent(); + + } catch (final Exception e) { + try { + throw new JMBaseException(e); + } catch (final JMBaseException jme) { + Options.raiseError(jme, -1); + } + } + } + + private static Document buildToDoc(InputStream stream) + throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(configStream); + + return doc; + } +} diff --git a/src/python/fix_version.py b/src/python/fix_version.py new file mode 100644 index 0000000..d809c68 --- /dev/null +++ b/src/python/fix_version.py @@ -0,0 +1,107 @@ +''' +This program will fix the JMatrix version for specified file(s), +which the real version is taken from 'config.xml'. + +Fix(es): + - MANIFEST.MF + - Makefile + +Created by Ryuu Mitsuki +''' + +import os, sys +from bs4 import BeautifulSoup + +def strtobool(val: str) -> bool: + """Parse the string to the boolean value or raise an exception""" + if isinstance(val, str) and val: + if val.lower() in ('true', 'yes', 't', '1'): + return True + elif val.lower() in ('false', 'no', 'f', '0'): + return False + + raise ValueError("'%s' is not recognized as a boolean value" % (val)) + + +def raise_error(ex: Exception, status: int = 1) -> None: + '''Raise an error message then exit if status not equal zero''' + print('[jmatrix]', e) + sys.exit(status) if status != 0 else None + + +# Files path +pathXML: str = (os.sep).join(['assets', 'configuration', 'config.xml']) +file: str = 'Makefile' +pathManifest: str = (os.sep).join(['META-INF', 'MANIFEST.MF']) + + +'''Get a version number from config.xml''' +data = None +idx: int = 0 + +try: + with open(pathXML, 'r') as XML: + data = XML.read() +except FileNotFoundError as fe: + raise_error(fe, 2) + +BS_dat: BeautifulSoup = BeautifulSoup(data, 'xml') +version: str = BS_dat.find('version').text +release: str = BS_dat.find('version')['type'] + + +'''Fix version for Makefile''' +try: + with open(file, 'r') as make: + data = make.readlines() +except FileNotFoundError as fe: + raise_error(fe, 2) + +Make_ver: str = None +for line in data: + if line.startswith('VERSION'): + idx = data.index(line) + Make_ver = line.split() + break + +if Make_ver[2] != version: + Make_ver[2] = version + data[idx] = ' '.join(Make_ver) + '\n' + + try: + with open(file, 'w') as make: + [make.write(line) for line in data] + except FileNotFoundError as fe: + raise_error(fe, 2) + else: + print('[jmatrix] Successfully changing version at %s' %(file)) + try: + raise Exception('System aborted\n') + except Exception as e: + print('[jmatrix]', e) + sys.exit(-1) + + +'''Fix version for MANIFEST.MF''' +try: + with open(pathManifest, 'r') as manifest: + data = manifest.readlines() +except FileNotFoundError as fe: + raise_error(fe, 2) + +mf_ver: str = None +for line in data: + if line.startswith('Version'): + idx = data.index(line) + mf_ver = line.split() + break + +if mf_ver[1] != version: + mf_ver[1] = version + data[idx] = ' '.join(mf_ver) + '\n' + + try: + with open(pathManifest, 'w') as manifest: + [manifest.write(line) for line in data] + except FileNotFoundError as fe: + raise_error(fe, 2) diff --git a/src/python/get_sources.py b/src/python/get_sources.py new file mode 100644 index 0000000..de952d5 --- /dev/null +++ b/src/python/get_sources.py @@ -0,0 +1,52 @@ +''' +`get_sources.py` created for searching all source files (.java) +in "src/com/mitsuki/jmatrix" directory. +/!\ Make sure you've Python 3.7+ installed + +Created by Ryuu Mitsuki +''' +import os, platform +import re + +def raise_error(ex: Exception, status: int = 1) -> None: + '''Raise an error message then exit if status not equal zero''' + print('[jmatrix]', e) + sys.exit(status) if status != 0 else None + +cmd: str = None +FILE_DEST: str = 'source_files.list' +LIB: str = (os.sep).join(['src', 'com', 'mitsuki', 'jmatrix']) + os.sep +DEST: str = (os.sep).join(['assets', 'properties', FILE_DEST]) + +print('Getting all source files in "%s"...' % LIB) + +if platform.system() in ('Linux', 'Unix'): + cmd = f'find {LIB} -type f -name "*.java" > {DEST}' +else: + cmd = f'dir "{LIB}" /b /s *.java > {DEST}' + +err_code: int = os.system(cmd) + +if err_code != 0: + os.sys.exit(err_code) + +src_list: list = [] +try: + with open(DEST, 'r') as src: + src_list = src.readlines() +except FileNotFoundError as fe: + raise_error(fe, 2) + + +print('\n' + '-' * 15 + ' SOURCE FILES ' + '-' * 15) +[ + print(src, end='' if sorted(src_list).index(src) != (len(sorted(src_list)) - 1) else None) + for src in sorted(src_list) +] + +print('Saved to "%s"' % DEST) +try: + with open(DEST, 'w') as src: + [src.write(s) for s in sorted(src_list)] +except FileNotFoundError as fe: + raise_error(fe, 2)