forked from titzer/virgil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitMatrixDemo.v3
57 lines (48 loc) · 2.19 KB
/
BitMatrixDemo.v3
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
// Copyright 2022 Ben L. Titzer. All rights reserved.
// See LICENSE for details of Apache 2.0 license.
def demo() {
// A BitMatrix is a two-dimensional matrix where each element represents
// a bit (i.e. 0 or 1). It is packed into words for dense storage.
// It offers both per-element and per-row operations.
def ROWS = 4, COLS = 11;
var m = BitMatrix.new(ROWS, COLS);
// A BitMatrix supports the indexing operators {e[i]} and {e[i] = e} for
// reading and writing individual elements as if they were booleans.
m[0, 3] = true;
m[2, 4] = false;
m[1, COLS - 1] = true;
if (m[1, COLS - 1]) System.puts("m[x,y] was true\n");
// A BitMatrix also supports the {.set()} and {.clear()} methods that set
// or clear an individual element, which is slightly more efficient than
// passing a constant boolean argument to the above indexing operators.
m.set(0, 4);
m.clear(2, 4);
if (!m[2, 4]) System.puts("m[x,y] was false\n");
// A BitMatrix supports efficient row-level operations {.or()}, {.and()},
// and {.copy()}.
m.or(0, 1); // inclusive-or rows 0 and 1, store in row 0
m.and(2, 3); // bitwise-and rows 2 and 3, store in row 2
m.copy(1, 0); // copy row 0 into row 1
m.set(2, 10);
// A range of rows can be extracted as a new BitMatrix.
var m2 = m.range(0, 2); // copy rows 0 and 1 into a new BitMatrix
// A BitMatrix can be grown, either by adding rows ({.grow()} or adding
// columns ({.widen()}). The new elements are all {0}, and the existing
// elements are unchanged (though internally, the storage may be copied).
m.grow(4); // grow the matrix to 4 rows
m.widen(20); // grow the matrix to 40 columns
// The {.count()} utility method counts the number of {1}s in a row.
var k = m.count(2); // count 1s in row 2
// A BitMatrix (or a single row of one) can be rendered into a {StringBuilder}
// using the "render method" pattern.
var s = StringBuilder.new();
s.put1("matrix: \n%q", m.render); // using %q in a format string
System.puts(s.toString());
s.put1("matrix[2]: \n%q", m.renderRow(2, _)); // using %q in a format string
System.puts(s.toString());
m.renderRow(1, s); // or just directly calling {renderRow}
System.puts(s.toString());
}
component BitMatrixDemo {
def run = demo;
}