Ver Fonte

math.Matrix

Ranides Atterwim há 12 anos atrás
pai
commit
ad135190f5

+ 72 - 0
src/main/java/net/ranides/assira/math/Matrix.java

@@ -0,0 +1,72 @@
+/*
+ * @author Ranides Atterwim <ranides@gmail.com>
+ * @copyright Ranides Atterwim
+ * @license WTFPL
+ * @url http://ranides.net/projects/assira
+ */
+
+package net.ranides.assira.math;
+
+import java.io.PrintStream;
+
+/**
+ *
+ * @author Mariusz Sieron <m.sieron@samsung.com>
+ */
+public class Matrix {
+
+    private int hsize;
+    private int vsize;
+    private int[][] data;
+
+    public Matrix(int hsize, int vsize) {
+        this.hsize = hsize;
+        this.vsize = vsize;
+        this.data = new int[hsize][vsize];
+    }
+
+    public static Matrix random(int hsize, int vsize, int max) {
+        Matrix ret = new Matrix(hsize, vsize);
+        for(int h=0, H=ret.hsize; h<H; h++) {
+            for(int v=0, V=ret.vsize; v<V; v++) {
+                ret.data[h][v] = Randomizer.number(max);
+            }
+        }
+        return ret;
+    }
+
+    public static Matrix mul(Matrix left, Matrix right) {
+        if( left.hsize != right.vsize ) {
+            throw new IllegalArgumentException();
+        }
+        int rv = left.vsize;
+        int rh = right.hsize;
+        int rz = left.hsize;
+
+        Matrix ret = new Matrix(rh, rv);
+
+        for(int h=0; h<rh; h++) {
+            for(int v=0; v<rv; v++) {
+                int s = 0;
+                for(int z=0; z<rz; z++) {
+                    s += left.data[z][v] * right.data[h][z];
+                }
+                ret.data[h][v] = s;
+            }
+        }
+
+        return ret;
+    }
+
+    public void print(PrintStream stream) {
+        for(int h=0, H=hsize; h<H; h++) {
+            for(int v=0, V=vsize; v<V; v++) {
+                stream.print(data[h][v]);
+                stream.print(" ");
+            }
+            stream.println();
+        }
+        stream.println();
+    }
+
+}

+ 33 - 0
src/test/java/net/ranides/assira/math/MatrixTest.java

@@ -0,0 +1,33 @@
+/*
+ * @author Ranides Atterwim <ranides@gmail.com>
+ * @copyright Ranides Atterwim
+ * @license WTFPL
+ * @url http://ranides.net/projects/assira
+ */
+
+package net.ranides.assira.math;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ *
+ * @author Mariusz Sieron <m.sieron@samsung.com>
+ */
+public class MatrixTest {
+
+    public MatrixTest() {
+    }
+
+    @Test
+    public void testMul() {
+        Matrix a = Matrix.random(4, 3, 10);
+        Matrix b = Matrix.random(2, 4, 10);
+        Matrix c = Matrix.mul(a, b);
+        a.print(System.out);
+        b.print(System.out);
+        c.print(System.out);
+        assertTrue(true);
+    }
+
+}