Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package project;
- import java.util.Random;
- import java.util.Vector;
- public class Matrix {
- // leftover matrices that haven't been processed yet
- public static Vector<Matrix> matricesToBeProcessed = new Vector<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;
- // 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];
- matricesToBeProcessed.add(this);
- }
- // 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>();
- // how many processes are left
- public static int numberOfProcesses;
- //generate submatrices
- //if the size of this one is 2, add a result to the array of results instead
- public void run() {
- // remove this matrix from the thread que
- thread.Pop(this);
- if (size == 2) {
- // no longer needs to be processed
- matricesToBeProcessed.remove(this);
- // calculate result if this is the lowest level submatrix
- ThreadedMatrix.results[numberOfProcesses - 1] = (elements[0] * elements[3] - elements[1] * elements[2])
- * valueInParent;
- // decrement remaining processes
- Matrix.numberOfProcesses--;
- } else {
- //see which thread has the smallest amount of matrices
- ThreadedMatrix smallest=thread;
- for(ThreadedMatrix thread: threadedMatrices)
- {
- if(thread.que.size()<smallest.que.size())
- {
- smallest=thread;
- }
- }
- // 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;
- // 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);
- }
- }
- }
- // push this submatrix into it's que
- smallest.Push(sub);
- }
- matricesToBeProcessed.remove(this);
- }
- }
- }
Add Comment
Please, Sign In to add comment