Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/multiset/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "7000000ugnot"
multiset.gno
// Package multiset is a bag / frequency counter — a set that allows duplicates
// and remembers how many — as a pure, reusable package.
//
// It is the STL multiset and Python's collections.Counter in one type: Add an
// element several times and the count rises; the distinct elements stay sorted
// so iteration and rendering are deterministic.
//
// The interesting operation is MostCommon(n), and the interesting problem with
// it is ties. Sorting by count alone leaves elements with equal counts in
// whatever order the underlying storage happened to yield — which, if that is a
// built-in map, is unspecified in gno and can differ between nodes. Here the
// order is total: count descending, then element ascending. Two multisets built
// from the same elements always produce the same ranking.
//
// A live demo of this package is at
// [r/moul/x/daily/multisetdemo](/r/nym-moultest123/x/daily/multisetdemo/v0).
package multiset
import "sort"
// MaxDistinct bounds the number of DISTINCT elements so gas stays predictable.
// Counts themselves are unbounded.
const MaxDistinct = 4096
// MultiSet counts occurrences of string elements.
type MultiSet struct {
counts map[string]int
total int
}
// New returns an empty MultiSet.
func New() *MultiSet { return &MultiSet{counts: map[string]int{}} }
// FromSlice builds a MultiSet from elements, counting duplicates.
func FromSlice(elems []string) *MultiSet {
m := New()
for _, e := range elems {
m.Add(e)
}
return m
}
// Add records one occurrence of e. Returns false when e is new and the set
// already holds MaxDistinct distinct elements.
func (m *MultiSet) Add(e string) bool { return m.AddN(e, 1) }
// AddN records n occurrences of e. A non-positive n is a no-op returning true.
func (m *MultiSet) AddN(e string, n int) bool {
if n <= 0 {
return true
}
if _, seen := m.counts[e]; !seen && len(m.counts) >= MaxDistinct {
return false
}
m.counts[e] += n
m.total += n
return true
}
// Count returns how many times e occurs; zero when absent.
func (m *MultiSet) Count(e string) int { return m.counts[e] }
// Has reports whether e occurs at least once.
func (m *MultiSet) Has(e string) bool { return m.counts[e] > 0 }
// Remove drops one occurrence of e, deleting it entirely when the count hits
// zero. Returns false when e was not present.
func (m *MultiSet) Remove(e string) bool { return m.RemoveN(e, 1) }
// RemoveN drops up to n occurrences of e. Returns false when e was absent.
// Removing more than are present clears the element rather than going negative.
func (m *MultiSet) RemoveN(e string, n int) bool {
have, ok := m.counts[e]
if !ok || n <= 0 {
return false
}
if n >= have {
delete(m.counts, e)
m.total -= have
return true
}
m.counts[e] = have - n
m.total -= n
return true
}
// RemoveAll drops every occurrence of e. Returns false when e was absent.
func (m *MultiSet) RemoveAll(e string) bool {
have, ok := m.counts[e]
if !ok {
return false
}
delete(m.counts, e)
m.total -= have
return true
}
// Distinct returns the number of distinct elements.
func (m *MultiSet) Distinct() int { return len(m.counts) }
// Total returns the sum of every count.
func (m *MultiSet) Total() int { return m.total }
// IsEmpty reports whether the set holds nothing.
func (m *MultiSet) IsEmpty() bool { return len(m.counts) == 0 }
// Elements returns the distinct elements, sorted.
func (m *MultiSet) Elements() []string {
out := make([]string, 0, len(m.counts))
for e := range m.counts {
out = append(out, e)
}
sort.Strings(out)
return out
}
// Expand returns every occurrence, sorted — a multiset flattened back to a
// slice. Length equals Total.
func (m *MultiSet) Expand() []string {
out := make([]string, 0, m.total)
for _, e := range m.Elements() {
for i := 0; i < m.counts[e]; i++ {
out = append(out, e)
}
}
return out
}
// Entry pairs an element with its count.
type Entry struct {
Elem string
Count int
}
// byRank orders entries by count descending, then element ascending — a TOTAL
// order, so ranking never depends on map iteration.
type byRank []Entry
func (r byRank) Len() int { return len(r) }
func (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r byRank) Less(i, j int) bool {
if r[i].Count != r[j].Count {
return r[i].Count > r[j].Count
}
return r[i].Elem < r[j].Elem
}
// MostCommon returns the n most frequent entries, ranked by count descending
// then element ascending. n <= 0, or larger than the number of distinct
// elements, returns them all.
func (m *MultiSet) MostCommon(n int) []Entry {
all := make([]Entry, 0, len(m.counts))
for e, c := range m.counts {
all = append(all, Entry{Elem: e, Count: c})
}
sort.Sort(byRank(all))
if n <= 0 || n > len(all) {
return all
}
return all[:n]
}
// Union returns a set where each element's count is the MAXIMUM of the two —
// the standard multiset union.
func (m *MultiSet) Union(other *MultiSet) *MultiSet {
out := m.Clone()
for e, c := range other.counts {
if c > out.counts[e] {
out.setCount(e, c)
}
}
return out
}
// Intersect returns a set where each element's count is the MINIMUM of the two,
// keeping only elements present in both.
func (m *MultiSet) Intersect(other *MultiSet) *MultiSet {
out := New()
for e, c := range m.counts {
if oc, ok := other.counts[e]; ok {
if oc < c {
c = oc
}
out.AddN(e, c)
}
}
return out
}
// Sum returns a set where each element's count is the SUM of the two.
func (m *MultiSet) Sum(other *MultiSet) *MultiSet {
out := m.Clone()
for e, c := range other.counts {
out.AddN(e, c)
}
return out
}
// Clone returns an independent copy.
func (m *MultiSet) Clone() *MultiSet {
out := New()
for e, c := range m.counts {
out.counts[e] = c
}
out.total = m.total
return out
}
// setCount overwrites an element's count, keeping total in step.
func (m *MultiSet) setCount(e string, c int) {
m.total += c - m.counts[e]
m.counts[e] = c
}
multiset_test.gno
package multiset
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestEmpty(t *testing.T) {
m := New()
uassert.True(t, m.IsEmpty())
uassert.Equal(t, 0, m.Distinct())
uassert.Equal(t, 0, m.Total())
uassert.Equal(t, 0, m.Count("nope"))
uassert.False(t, m.Has("nope"))
}
func TestAddAndCount(t *testing.T) {
m := New()
m.Add("apple")
m.Add("apple")
m.Add("pear")
uassert.Equal(t, 2, m.Count("apple"))
uassert.Equal(t, 1, m.Count("pear"))
uassert.Equal(t, 2, m.Distinct(), "distinct counts elements, not occurrences")
uassert.Equal(t, 3, m.Total(), "total counts occurrences")
uassert.True(t, m.Has("apple"))
}
func TestAddN(t *testing.T) {
m := New()
uassert.True(t, m.AddN("x", 5))
uassert.Equal(t, 5, m.Count("x"))
uassert.True(t, m.AddN("x", 0), "adding zero is a no-op that succeeds")
uassert.True(t, m.AddN("x", -3), "adding a negative is a no-op that succeeds")
uassert.Equal(t, 5, m.Count("x"), "count unchanged by non-positive AddN")
uassert.Equal(t, 5, m.Total())
}
func TestFromSlice(t *testing.T) {
m := FromSlice([]string{"a", "b", "a", "c", "a"})
uassert.Equal(t, 3, m.Count("a"))
uassert.Equal(t, 1, m.Count("b"))
uassert.Equal(t, 3, m.Distinct())
uassert.Equal(t, 5, m.Total())
}
func TestRemove(t *testing.T) {
m := FromSlice([]string{"a", "a", "a"})
uassert.True(t, m.Remove("a"))
uassert.Equal(t, 2, m.Count("a"))
uassert.Equal(t, 2, m.Total())
uassert.False(t, m.Remove("absent"), "removing an absent element reports false")
}
// TestRemoveDeletesAtZero pins that a count reaching zero drops the element
// rather than leaving a zero-count ghost that Distinct would still count.
func TestRemoveDeletesAtZero(t *testing.T) {
m := New()
m.Add("a")
uassert.True(t, m.Remove("a"))
uassert.Equal(t, 0, m.Distinct(), "a zero count removes the element entirely")
uassert.False(t, m.Has("a"))
uassert.Equal(t, 0, m.Total())
}
// TestRemoveNClamps pins that over-removing clears rather than going negative.
func TestRemoveNClamps(t *testing.T) {
m := New()
m.AddN("a", 3)
uassert.True(t, m.RemoveN("a", 100))
uassert.Equal(t, 0, m.Count("a"))
uassert.Equal(t, 0, m.Total(), "total must not go negative")
uassert.Equal(t, 0, m.Distinct())
}
func TestRemoveNPartial(t *testing.T) {
m := New()
m.AddN("a", 10)
uassert.True(t, m.RemoveN("a", 4))
uassert.Equal(t, 6, m.Count("a"))
uassert.Equal(t, 6, m.Total())
uassert.False(t, m.RemoveN("a", 0), "a non-positive n reports false")
}
func TestRemoveAll(t *testing.T) {
m := New()
m.AddN("a", 7)
m.Add("b")
uassert.True(t, m.RemoveAll("a"))
uassert.Equal(t, 0, m.Count("a"))
uassert.Equal(t, 1, m.Total(), "only b remains")
uassert.False(t, m.RemoveAll("a"), "already gone")
}
func TestElementsSorted(t *testing.T) {
m := FromSlice([]string{"delta", "alpha", "charlie", "alpha"})
uassert.Equal(t, "alpha,charlie,delta", strings.Join(m.Elements(), ","))
}
func TestExpand(t *testing.T) {
m := FromSlice([]string{"b", "a", "b"})
uassert.Equal(t, "a,b,b", strings.Join(m.Expand(), ","))
uassert.Equal(t, m.Total(), len(m.Expand()), "Expand length equals Total")
}
func TestMostCommon(t *testing.T) {
m := FromSlice([]string{"a", "a", "a", "b", "b", "c"})
top := m.MostCommon(2)
uassert.Equal(t, 2, len(top))
uassert.Equal(t, "a", top[0].Elem)
uassert.Equal(t, 3, top[0].Count)
uassert.Equal(t, "b", top[1].Elem)
uassert.Equal(t, 2, top[1].Count)
}
// TestMostCommonTiesAreAlphabetical is the determinism guarantee: equal counts
// must not fall back on map order, which gno leaves unspecified.
func TestMostCommonTiesAreAlphabetical(t *testing.T) {
m := FromSlice([]string{"zebra", "apple", "mango"}) // all count 1
got := m.MostCommon(0)
uassert.Equal(t, 3, len(got))
uassert.Equal(t, "apple", got[0].Elem)
uassert.Equal(t, "mango", got[1].Elem)
uassert.Equal(t, "zebra", got[2].Elem)
}
// TestMostCommonIsStableAcrossBuilds is the same property from the outside:
// build the set twice, get the same ranking.
func TestMostCommonIsStableAcrossBuilds(t *testing.T) {
build := func() *MultiSet {
m := New()
for i := 0; i < 60; i++ {
m.Add("e" + strconv.Itoa(i%9))
}
return m
}
uassert.Equal(t, rank(build().MostCommon(0)), rank(build().MostCommon(0)))
}
func TestMostCommonBounds(t *testing.T) {
m := FromSlice([]string{"a", "b"})
uassert.Equal(t, 2, len(m.MostCommon(0)), "n<=0 returns everything")
uassert.Equal(t, 2, len(m.MostCommon(-1)), "negative n returns everything")
uassert.Equal(t, 2, len(m.MostCommon(99)), "n beyond distinct returns everything")
uassert.Equal(t, 1, len(m.MostCommon(1)))
uassert.Equal(t, 0, len(New().MostCommon(5)), "empty set ranks nothing")
}
func TestUnionTakesMaximum(t *testing.T) {
a := FromSlice([]string{"x", "x", "y"})
b := FromSlice([]string{"x", "z", "z", "z"})
u := a.Union(b)
uassert.Equal(t, 2, u.Count("x"), "max(2,1)")
uassert.Equal(t, 1, u.Count("y"), "max(1,0)")
uassert.Equal(t, 3, u.Count("z"), "max(0,3)")
uassert.Equal(t, 6, u.Total())
uassert.Equal(t, 3, a.Total(), "operands are untouched")
}
func TestIntersectTakesMinimum(t *testing.T) {
a := FromSlice([]string{"x", "x", "x", "y"})
b := FromSlice([]string{"x", "x", "z"})
i := a.Intersect(b)
uassert.Equal(t, 2, i.Count("x"), "min(3,2)")
uassert.Equal(t, 0, i.Count("y"), "absent from b")
uassert.Equal(t, 0, i.Count("z"), "absent from a")
uassert.Equal(t, 1, i.Distinct())
uassert.Equal(t, 2, i.Total())
}
func TestSumAddsCounts(t *testing.T) {
a := FromSlice([]string{"x", "x", "y"})
b := FromSlice([]string{"x", "z"})
s := a.Sum(b)
uassert.Equal(t, 3, s.Count("x"), "2+1")
uassert.Equal(t, 1, s.Count("y"))
uassert.Equal(t, 1, s.Count("z"))
uassert.Equal(t, 5, s.Total())
}
func TestClone(t *testing.T) {
m := FromSlice([]string{"a", "a"})
cp := m.Clone()
cp.Add("b")
uassert.Equal(t, 1, m.Distinct(), "clone must not share storage")
uassert.Equal(t, 2, cp.Distinct())
uassert.Equal(t, 2, m.Total())
uassert.Equal(t, 3, cp.Total())
}
func TestMaxDistinct(t *testing.T) {
m := New()
for i := 0; i < MaxDistinct; i++ {
uassert.True(t, m.Add("e"+strconv.Itoa(i)), "should accept up to MaxDistinct")
}
uassert.Equal(t, MaxDistinct, m.Distinct())
uassert.False(t, m.Add("overflow"), "a full set refuses a new distinct element")
uassert.Equal(t, MaxDistinct, m.Distinct())
// Counts are NOT bounded: an existing element can still grow.
uassert.True(t, m.AddN("e0", 1000), "existing elements still accept occurrences")
uassert.Equal(t, 1001, m.Count("e0"))
}
func rank(es []Entry) string {
parts := make([]string, len(es))
for i, e := range es {
parts[i] = e.Elem + ":" + strconv.Itoa(e.Count)
}
return strings.Join(parts, ",")
}