Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

tally.gno

2.32 Kb · 89 lines
 1package rulecalc
 2
 3import (
 4	"errors"
 5	"strconv"
 6)
 7
 8// Sheet is one evaluator's scores: Scores[app][criterion], apps ordered by ID 0..n-1,
 9// criteria in the order of Rule.Criteria.
10type Sheet struct {
11	Evaluator address
12	Scores    [][]int
13}
14
15// ValidateSheet checks that s scores every app on every criterion within 0-10.
16func ValidateSheet(r Rule, nApps int, s Sheet) error {
17	if len(s.Scores) != nApps {
18		return errors.New("rulecalc: sheet must score " + strconv.Itoa(nApps) + " apps")
19	}
20	for i, row := range s.Scores {
21		if len(row) != len(r.Criteria) {
22			return errors.New("rulecalc: app " + strconv.Itoa(i) + " needs " + strconv.Itoa(len(r.Criteria)) + " scores")
23		}
24		for _, v := range row {
25			if v < MinScore || v > MaxScore {
26				return errors.New("rulecalc: score out of range 0-10 for app " + strconv.Itoa(i))
27			}
28		}
29	}
30	return nil
31}
32
33func weighted(r Rule, row []int) int {
34	sum := 0
35	for c, v := range row {
36		sum += r.Criteria[c].Weight * v
37	}
38	return sum
39}
40
41// argmax returns the lowest index holding the maximum and whether that maximum is shared.
42func argmax(xs []int) (best int, tied bool) {
43	for i := 1; i < len(xs); i++ {
44		if xs[i] > xs[best] {
45			best = i
46			tied = false
47		} else if xs[i] == xs[best] {
48			tied = true
49		}
50	}
51	return best, tied
52}
53
54// Totals returns the per-app figure the rule's method ranks by:
55// weighted score sums for WeightedSum, first-place counts for MajorityFirst.
56// Sheets must already pass ValidateSheet.
57func Totals(r Rule, nApps int, sheets []Sheet) []int {
58	tot := make([]int, nApps)
59	for _, s := range sheets {
60		switch r.Method {
61		case WeightedSum:
62			for app, row := range s.Scores {
63				tot[app] += weighted(r, row)
64			}
65		case MajorityFirst:
66			per := make([]int, nApps)
67			for app, row := range s.Scores {
68				per[app] = weighted(r, row)
69			}
70			first, _ := argmax(per) // in-sheet tie -> lowest ID
71			tot[first]++
72		}
73	}
74	return tot
75}
76
77// Compute returns the winning app ID. paid == false means the grant is refunded:
78// no apps, fewer sheets than the quorum, or a top-level tie under the Refund tie-break.
79// Sheets must already pass ValidateSheet.
80func Compute(r Rule, nApps int, sheets []Sheet) (winner int, paid bool) {
81	if nApps < 1 || len(sheets) < r.Quorum {
82		return 0, false
83	}
84	best, tied := argmax(Totals(r, nApps, sheets))
85	if tied && r.Tie == Refund {
86		return 0, false
87	}
88	return best, true
89}