Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package project;
- import java.util.Vector;
- public class Matrix {
- // Det=a11*(-1)^(1+1)*DetA11+a12*(-1)^(1+2)*DetA12 ...
- // +a1n*(-1)^(1+n)*DetA1n
- // valueInParent is a1n*(-1)^(1+n)
- public double valueInParent = 1;
- // how many threads we can have
- public static int threadMax = 1;
- // all the elements in the matrix.
- // it's supposed to be a 2 dimensional array, but this works the same
- public double[] elements;
- // reference to the parent of this submatrix.
- // only the first matrix doesn't have a parent
- public Matrix parent;
- // how many rows/columns this matrix has
- int size;
- // reference to the thread that's calculating this matrix.
- // necessary in order to clear the que of that thread
- public ThreadedMatrix thread;
- // a[x,y]=val
- public void SetElement(double val, int x, int y) {
- elements[size * y + x] = val;
- }
- // constructor
- public Matrix(int _size) {
- size = _size;
- elements = new double[size * size];
- }
- // return a[x,y]
- public double Get(int x, int y) {
- return elements[x + y * size];
- }
- // reference to all the threads.
- // each of them needs to know if the others are finished
- public static Vector<ThreadedMatrix> threadedMatrices = new Vector<ThreadedMatrix>();
- // function that calculates the determinant of this matrix
- // if the size of this matrix is 3 or bigger, it will return 0 and will push
- // the submatrices into the thread
- public double Determinant(boolean quiet) {
- //remove this matrix from the thread que
- thread.Pop(this);
- if (size == 1) {// shouldn't really happen unless someone specifically
- // enters a 1 sized matrix
- return elements[0];
- } else if (size == 2) {
- //calculate result if this is the lowest level submatrix
- return elements[0] * elements[3] - elements[1] * elements[2];
- } else {
- //create submatrices for every element in the first row
- for (int i = 0; i < size; i++) {
- Matrix sub = new Matrix(size - 1);
- //for a11 the submatrix valueInParent will be (-1)^(i+2)*1*a11=a11
- sub.valueInParent = Math.pow(-1, i + 2) * Get(i, 0) * valueInParent;
- sub.parent = this;
- //set the elements of the submatrix
- for (int x = 0; x < size; x++) {
- if (x != i) {
- for (int y = 1; y < size; y++) {
- sub.SetElement(Get(x, y), (x > i ? x - 1 : x), y - 1);
- }
- }
- }
- //see which thread has the least amount of processes to calculate
- //push this submatrix into it's que
- ThreadedMatrix smallest = thread;
- int min = 100;
- for (ThreadedMatrix _t : threadedMatrices) {
- if (_t.que.size() < min) {
- smallest = _t;
- min = _t.que.size();
- }
- }
- smallest.Push(sub);
- }
- //return 0, the submatrices will be calculated separately
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement