-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix-bit-and-or.rb
58 lines (51 loc) · 1003 Bytes
/
matrix-bit-and-or.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class BitAndOrMatrix
attr_reader :n, :bits
def initialize(n, bits)
@n, @bits = n, bits
@u = (1 << n) - 1
@v = ((@u + 1)**n - 1) / @u
end
def self.rows(rows)
n, bits = rows.size, 0
rows.each_with_index do |row, i|
x = 0
row.each_with_index do |a, j|
x |= a << j
end
bits |= x << n * i
end
new(n, bits)
end
def self.id(n)
new(n, ((1 << (n + 1) * n) - 1) / ((1 << n + 1) - 1))
end
def [](i, j)
@bits >> i * @n + j & 1
end
def +(other)
self.class.new(@n, @bits | other.bits)
end
def *(other)
a, b = @bits, other.bits
bits = 0
while a > 0 and b > 0
bits |= ((a & @v) * @u) & ((b & @u) * @v)
a >>= 1
b >>= n
end
self.class.new(@n, bits)
end
def **(e)
r = self.class.id(@n)
x = self
while e > 0
r *= x if (e & 1) == 1
x *= x
e >>= 1
end
r
end
def to_a
(0 ... @n).map { |i| (0 ... @n).map { |j| self[i, j] } }
end
end