
Опытный
 
Профиль
Группа: Участник
Сообщений: 649
Регистрация: 22.4.2008
Где: Витебск
Репутация: 14 Всего: 28
|
Держи класс Matrix и класс Main, в котором он тестируется. Писал, что называется, "на коленке", так что код не совсем оптимален, но работает - под open JDK 1.8 with lambda. | Код | import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
public class Matrix<T extends Number> { private String type; private T[][] matrix; private int cols, rows;
public Matrix(T[][] matrix) { this.matrix = matrix; rows = matrix.length; cols = matrix[0].length; }
public int colsCount() { return cols; }
public int rowsCount() { return rows; }
public T getValue(int row, int col) { return matrix[row][col]; }
public void setValue(int row, int col, T value) { matrix[row][col] = value; }
@SuppressWarnings("unchecked") public Matrix<T> multiply(Matrix<? extends Number> m2) { if (rows != m2.colsCount()) { throw new IndexOutOfBoundsException("can not multiply this matrix"); } type = matrix[0][0].getClass().getName(); T[][] m3 = (T[][]) (new Number[rows][m2.colsCount()]); Matrix<T> result = new Matrix<>(m3); fillWithZero(result); ExecutorService executor = Executors.newFixedThreadPool(result.rowsCount()); for (int i = 0; i < result.rowsCount(); i++) { executor.execute(mult(i, m2, result)); } executor.shutdown(); try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (InterruptedException e) { } return result; }
@SuppressWarnings("unchecked") public Matrix<T> sum(Matrix<? extends Number> m2) { if (rows != m2.colsCount() && cols != m2.colsCount()) { throw new IndexOutOfBoundsException("can not sum this matrix"); } type = matrix[0][0].getClass().getName(); T[][] m3 = (T[][]) (new Number[rows][cols]); Matrix<T> result = new Matrix<>(m3); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result.setValue(i, j, sumNumbers(matrix[i][j], m2.getValue(i, j))); } } return result; }
public T determinant() { type = matrix[0][0].getClass().getName(); return determinant(matrix, rows); }
@SuppressWarnings("unchecked") protected T determinant(T[][] matr, int r) { if (matr.length != matr[0].length) { throw new IndexOutOfBoundsException("can't calculate determinant"); } T res; if (r == 1) { res = matr[0][0]; } else if (r == 2) { res = sumNumbers(multNumbers(matr[0][0], matr[1][1]), multNumbers((T) new Double(-1), multNumbers(matr[1][0], matr[0][1]))); } else { res = (T) new Double(0); for (int j1 = 0; j1 < r; j1++) { T [][] m = (T [][]) new Number[r - 1][]; for (int k = 0; k < (r - 1); k++) m[k] = (T[]) new Double[r - 1]; for (int i = 1; i < r; i++) { int j2 = 0; for (int j = 0; j < r; j++) { if (j == j1) continue; m[i - 1][j2] = (T) new Double(matr[i][j].doubleValue()); j2++; } } res = sumNumbers(res, multNumbers((T) new Double(Math.pow(-1.0, 1.0 + j1 + 1.0)), multNumbers(matr[0][j1], determinant(m, r - 1)))); } } return res; }
@Override public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { sb.append(matrix[i][j].toString() + "\t"); } sb.append("\n"); } return sb.toString(); }
protected Runnable mult(int row, Matrix<? extends Number> m2, Matrix<T> res) { return () -> { for (int i = 0; i < rows; i++) { for (int j = 0; j < m2.rowsCount(); j++) { res.setValue(row, i, sumNumbers(res.getValue(row, i), multNumbers(matrix[row][j], m2.getValue(j, i)))); // System.out.println(Thread.currentThread().getName()); } } }; }
@SuppressWarnings("unchecked") protected void fillWithZero(Matrix<T> m) { for (int i = 0; i < m.rowsCount(); i++) { for (int j = 0; j < m.colsCount(); j++) { switch (type) { case "java.lang.Integer": m.setValue(i, j, (T) new Integer(0)); break; case "java.lang.Double": m.setValue(i, j, (T) new Double(0)); break; case "java.lang.Long": m.setValue(i, j, (T) new Long(0)); break; case "java.lang.Byte": m.setValue(i, j, (T) new Byte("0")); break; case "java.lang.Float": m.setValue(i, j, (T) new Float(0)); break; case "java.lang.Short": m.setValue(i, j, (T) new Short("0")); break; default: throw new NumberFormatException("Not a Number"); } } } }
@SuppressWarnings("unchecked") protected <E extends Number> T sumNumbers(T v1, E v2) { switch (type) { case "java.lang.Integer": return (T) (new Integer(v1.intValue() + v2.intValue())); case "java.lang.Double": return (T) (new Double(v1.doubleValue() + v2.doubleValue())); case "java.lang.Long": return (T) (new Long(v1.longValue() + v2.longValue())); case "java.lang.Byte": return (T) (new Integer(v1.byteValue() + v2.byteValue())); case "java.lang.Float": return (T) (new Float(v1.floatValue() + v2.floatValue())); case "java.lang.Short": return (T) (new Integer(v1.shortValue() + v2.shortValue())); default: throw new NumberFormatException("Not supporting this Number or not a Number"); } }
@SuppressWarnings("unchecked") protected <E extends Number> T multNumbers(T v1, E v2) { switch (type) { case "java.lang.Integer": return (T) (new Integer(v1.intValue() * v2.intValue())); case "java.lang.Double": return (T) (new Double(v1.doubleValue() * v2.doubleValue())); case "java.lang.Long": return (T) (new Long(v1.longValue() * v2.longValue())); case "java.lang.Byte": return (T) (new Integer(v1.byteValue() * v2.byteValue())); case "java.lang.Float": return (T) (new Float(v1.floatValue() * v2.floatValue())); case "java.lang.Short": return (T) (new Integer(v1.shortValue() * v2.shortValue())); default: throw new NumberFormatException("Not a Number"); } } }
|
| Код | public class Main { public static void main(String ...args) { try { Byte arr1[][] = {{1, 2, 3, 8}, {4, 5, 6, 14}, {4, 5, 6, 14}}; Double arr2[][] = {{1., 2., 3.}, {4., 5., 5.}, {7., 8., 7.}, {3., 9., 8.}}; Double arr3[][] = {{1., 2., 3., 8.}, {4., 5., 6., 14.}, {4., 5., 6., 14.}}; Byte arr4[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {6, 4, 4, 4}, {5, 6, 4, 4}}; Matrix<Byte> m1 = new Matrix<>(arr1); Matrix<Double> m2 = new Matrix<>(arr2); Matrix<Byte> multMatr = m1.multiply(m2); Matrix<Double> m3 = new Matrix<>(arr3); Matrix<Byte> sumMatr = m1.sum(m3); System.out.println("OUTPUT :"); System.out.println(); System.out.println(m1); System.out.println(m2); System.out.println(m3); System.out.println(sumMatr); System.out.println(multMatr); Matrix<Byte> m4 = new Matrix<>(arr4); System.out.println(m4); System.out.println(m4.determinant()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
|
Позже, если успею, сделаю вектор. собственно, сделал (точнее, нашел подходящий код): | Код | package com.company;
public class Vector<T extends Number> { private T a, b, c;
public Vector(T a, T b, T c) { this.a = a; this.b = b; this.c = c; }
protected double dot(Vector<?> vec) { return (a.doubleValue() * vec.a.doubleValue() + b.doubleValue() * vec.b.doubleValue() + c.doubleValue() * vec.c.doubleValue()); }
protected Vector<Double> cross(Vector<?> vec) { Double newA = b.doubleValue() * vec.c.doubleValue() - c.doubleValue() * vec.b.doubleValue(); Double newB = c.doubleValue() * vec.a.doubleValue() - a.doubleValue() * vec.c.doubleValue(); Double newC = a.doubleValue() * vec.b.doubleValue() - b.doubleValue() * vec.a.doubleValue(); return new Vector<Double>(newA, newB, newC); }
public double scalTrip(Vector<?> vecB, Vector<?> vecC) { return this.dot(vecB.cross(vecC)); }
public Vector<Double> vecTrip(Vector<?> vecB, Vector<?> vecC) { return this.cross(vecB.cross(vecC)); }
public Vector<Double> sumVec(Vector<?> vec) { Double newA = a.doubleValue() + vec.a.doubleValue(); Double newB = b.doubleValue() + vec.b.doubleValue(); Double newC = c.doubleValue() + vec.c.doubleValue(); return new Vector<Double>(newA, newB, newC); }
@Override public String toString() { return "<" + a.toString() + ", " + b.toString() + ", " + c.toString() + ">"; } }
|
| Код | package com.company;
public class Main { public static void main(String[] args) { Vector<Integer> a = new Vector<Integer>(3, 4, 5); Vector<Integer> b = new Vector<Integer>(4, 3, 5); Vector<Integer> c = new Vector<Integer>(-5, -12, -13); System.out.println(a.scalTrip(b, c)); System.out.println(a.vecTrip(b, c)); System.out.println(a.sumVec(b)); } }
|
Комменты я не делал - это больше, чем полчаса времени  Но, думаю, там все более-менее наглядно Это сообщение отредактировал(а) Pawl - 29.5.2013, 16:43
--------------------
В действительности всё совсем не так, как на самом деле
|