BitMatrix.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (C) 2013 by Yan Huang <yhuang@cs.umd.edu>
  2. // Improved by Xiao Shaun Wang <wangxiao@cs.umd.edu>
  3. package com.oblivm.backend.ot;
  4. import java.math.BigInteger;
  5. import java.security.SecureRandom;
  6. class BitMatrix {
  7. private int nRows;
  8. private int nCols;
  9. BigInteger[] data; // column vectors of the matrix
  10. public BitMatrix(int rows, int cols) {
  11. nRows = rows;
  12. nCols = cols;
  13. data = new BigInteger[nCols];
  14. }
  15. public void initialize(SecureRandom rnd) {
  16. for (int i = 0; i < nCols; i++)
  17. data[i] = new BigInteger(nRows, rnd);
  18. }
  19. public BitMatrix transpose() {
  20. return NaiveTranspose(this);
  21. }
  22. static public BitMatrix NaiveTranspose(BitMatrix a) {
  23. BitMatrix b = new BitMatrix(a.nCols, a.nRows);
  24. for (int i = 0; i < a.nRows; i++)
  25. b.data[i] = BigInteger.ZERO;
  26. for (int j = 0; j < a.nCols; j++)
  27. for (int i = 0; i < a.nRows; i++)
  28. if (a.data[j].testBit(i))
  29. b.data[i] = b.data[i].setBit(j);
  30. return b;
  31. }
  32. static public BitMatrix COtranspose(BitMatrix a) {
  33. BitMatrix b = new BitMatrix(a.nCols, a.nRows);
  34. for (int i = 0; i < a.nRows; i++)
  35. b.data[i] = BigInteger.ZERO;
  36. COtranspose(a, b, 0, 0, a.nRows, a.nCols);
  37. return b;
  38. }
  39. static public void COtranspose(BitMatrix a, BitMatrix b, int startx, int starty, int endx, int endy) {
  40. if (endy - starty == 1 && endx - startx == 1) {
  41. if (a.data[starty].testBit(startx))
  42. b.data[startx] = b.data[startx].setBit(starty);
  43. return;
  44. } else if (endy - starty < endx - startx) {
  45. int midx = (startx + endx) / 2;
  46. COtranspose(a, b, startx, starty, midx, endy);
  47. COtranspose(a, b, midx, starty, endx, endy);
  48. } else {
  49. int midy = (starty + endy) / 2;
  50. COtranspose(a, b, startx, starty, endx, midy);
  51. COtranspose(a, b, startx, midy, endx, endy);
  52. }
  53. }
  54. }