Realm

v0

gno.land/r/moul/x/daily/fenwickdemo/v0

Render

Fenwick tree

A Binary Indexed Tree: prefix sums and point updates both in O(log n), demoing the p/moul/x/daily/fenwick library.

The values

3, 1, 4, 1, 5, 9, 2, 6 — 8 slots totalling 31.

Prefix sums

ivaluePrefix(i+1)
033
114
248
319
4514
5923
6225
7631

Range queries

callmeaningresult
Range(2, 5)slots 2, 3, 410
Range(0, 8)everything31
Range(5, 5)empty0
Range(-9, 99)clamped to the ends31

Reads clamp instead of panicking. A realm cannot be redeployed on the same path, so a Render that panics on an out-of-range index is a page that is broken for good. Writes do panic: a bad Add is a transaction, and aborting it is the useful answer.

What the tree actually stores

The array is not a copy of the values. Each internal slot holds the sum of a run of them, and the run lengths are the powers of two in the index. That is the whole trick, and Covers makes it visible.

nodecovers slotssum
1[0, 1)3
2[0, 2)4
3[2, 3)4
4[0, 4)9
5[4, 5)5
6[4, 6)14
7[6, 7)2
8[0, 8)31

A prefix walk visits one node per set bit of the index, and those nodes tile the prefix exactly: no gap, no overlap. Eight slots means at most three nodes per query.

The weighted draw

SearchPrefix(target) names the slot that owns a target drawn below Total, in O(log n). Each holder is picked in proportion to their stake, and a zero stake can never be picked at all.

holderstakeowns targetsshare
alice30[0, 30)30%
bob0none0%
carol45[30, 75)45%
dave5[75, 80)5%
erin20[80, 100)20%
targetSearchPrefixholder
00alice
290alice
302carol
742carol
994erin

Note target 30: it is the first one past alice's share, and it skips bob entirely rather than landing on a holder with nothing staked. The search steps over zero-weight slots because their prefix does not advance, not because anything checks for them.

Why not a plain slice

Two obvious implementations each win one column and lose another. A realm whose scoreboard is written by every player and read by every page view pays both costs, which is where the middle row earns its keep.

structurepoint updateprefix sumweighted draw
plain sliceO(1)O(n)O(n)
Fenwick treeO(log n)O(log n)O(log n)
running totalsO(n)O(1)O(log n)

The tree also carries no storage overhead: it is exactly n values, rearranged.

Transactions

No indexed transactions for this realm yet.

Calls, deploys, and child packages in indexed history.

Call function

Calls stay disabled until vm/qfuncs lists this package. Delve only submits functions the chain publishes for gno.land/r/moul/x/daily/fenwickdemo/v0.

Source (qfile)