package main
import (
stdheap "container/heap"
"fmt"
"math"
"sort"
"testing"
"algo/metrics"
)
// scatteredRatings is a deterministic xorshift rating set. Lesson 9's ratedLib
// walks the ratings in a cycle, which is fine for a counting sort and useless
// here — a heap fed an orderly sequence never has to move anything.
func scatteredRatings(n int) []Item {
s := make([]Item, n)
x := uint64(88172645463325252)
for i := range s {
x ^= x << 13
x ^= x >> 7
x ^= x << 17
s[i] = Item{ID: i + 1, Rating: int(x % (MaxRating + 1))}
}
return s
}
// ratingsOf reads the heap's array straight off the struct — it does not use
// IsHeap() or Height(), which you have not written yet.
func ratingsOf(h *MinHeap) []int {
out := make([]int, len(h.a))
for i, it := range h.a {
out[i] = it.Rating
}
return out
}
// parentsAreNoLarger is the heap property, checked on the raw array.
func parentsAreNoLarger(a []Item) bool {
for i := 1; i < len(a); i++ {
if a[(i-1)/2].Rating > a[i].Rating {
return false
}
}
return true
}
// THE TABLE IS THE SPECIFICATION. The seven pushes and seven pops from step 2:
// the comparisons and swaps each one cost, and the array it left behind.
func TestTraceReproducesTheLessonTable(t *testing.T) {
h := NewMinHeap(0)
pushes := []struct {
rating int
cmps, swaps int64
array string
}{
{19, 0, 0, "[19]"},
{17, 1, 1, "[17 19]"},
{15, 1, 1, "[15 19 17]"},
{41, 1, 0, "[15 19 17 41]"},
{22, 1, 0, "[15 19 17 41 22]"},
{12, 2, 2, "[12 19 15 41 22 17]"},
{33, 1, 0, "[12 19 15 41 22 17 33]"},
}
for _, p := range pushes {
var c metrics.Counter
before := h.Swaps
h.Push(Item{Rating: p.rating}, &c)
got := fmt.Sprint(ratingsOf(h))
if c.N() != p.cmps || int64(h.Swaps-before) != p.swaps || got != p.array {
t.Fatalf("push %d: cmps / swaps / array = %d / %d / %s, want %d / %d / %s",
p.rating, c.N(), h.Swaps-before, got, p.cmps, p.swaps, p.array)
}
}
pops := []struct {
rating int
cmps, swaps int64
array string
}{
{12, 3, 2, "[15 19 17 41 22 33]"},
{15, 2, 1, "[17 19 33 41 22]"},
{17, 3, 1, "[19 22 33 41]"},
{19, 2, 1, "[22 41 33]"},
{22, 1, 0, "[33 41]"},
{33, 0, 0, "[41]"},
{41, 0, 0, "[]"},
}
for _, p := range pops {
var c metrics.Counter
before := h.Swaps
it, ok := h.Pop(&c)
got := fmt.Sprint(ratingsOf(h))
if !ok || it.Rating != p.rating || c.N() != p.cmps || int64(h.Swaps-before) != p.swaps || got != p.array {
t.Fatalf("pop: rating / cmps / swaps / array = %d / %d / %d / %s, want %d / %d / %d / %s",
it.Rating, c.N(), h.Swaps-before, got, p.rating, p.cmps, p.swaps, p.array)
}
}
if _, ok := h.Pop(new(metrics.Counter)); ok {
t.Error("Pop on an empty heap reported ok")
}
}
// The heap property is checked after EVERY pop, not at the end: a wrong sift
// often damages the array in a way the next pop happens to hide. And what comes
// out must be exactly the ratings that went in, smallest first.
func TestPopKeepsTheHeapAndComesOutAscending(t *testing.T) {
items := scatteredRatings(500)
want := make([]int, len(items))
for i, it := range items {
want[i] = it.Rating
}
sort.Ints(want)
h := NewMinHeap(len(items))
var c metrics.Counter
for _, it := range items {
h.Push(it, &c)
}
for i, n := 0, len(items); n > 0; i, n = i+1, n-1 {
it, ok := h.Pop(&c)
if !ok {
t.Fatalf("Pop reported empty with %d items left", n)
}
if it.Rating != want[i] {
t.Fatalf("pop %d returned %d, want %d — not the next smallest", i+1, it.Rating, want[i])
}
if h.Len() != n-1 {
t.Fatalf("Len %d after a pop, want %d", h.Len(), n-1)
}
if !parentsAreNoLarger(h.a) {
t.Fatalf("the heap property broke after a pop, with %d items left", h.Len())
}
}
}
// A heap is not sorted, but draining it IS.
func TestPopComesOutAscending(t *testing.T) {
items := scatteredRatings(5000)
h := NewMinHeap(0)
var c metrics.Counter
for _, it := range items {
h.Push(it, &c)
if !h.IsHeap() {
t.Fatalf("the heap invariant broke during Push at len %d", h.Len())
}
}
if h.Len() != len(items) {
t.Fatalf("len %d, want %d", h.Len(), len(items))
}
prev := -1
for h.Len() > 0 {
it, _ := h.Pop(&c)
if it.Rating < prev {
t.Fatalf("Pop returned %d after %d — not ascending", it.Rating, prev)
}
prev = it.Rating
}
}
// THE ARRAY IS THE TREE. The shape is implied by the length alone: no traversal
// is needed to know the height, because there is nothing to traverse.
func TestHeightIsImpliedByLength(t *testing.T) {
h := NewMinHeap(0)
var c metrics.Counter
for n := 1; n <= 5000; n++ {
h.Push(Item{Rating: n % (MaxRating + 1)}, &c)
want := int(math.Floor(math.Log2(float64(n)))) + 1
if h.Height() != want {
t.Fatalf("n=%d: Height %d, want %d", n, h.Height(), want)
}
}
}
// A HEAP IS NOT SORTED, AND THAT IS THE POINT. It knows its minimum and nothing
// else — asserted here so nobody "improves" Push into an insertion sort.
func TestTheHeapIsNotSorted(t *testing.T) {
items := scatteredRatings(1000)
h := NewMinHeap(0)
var c metrics.Counter
for _, it := range items {
h.Push(it, &c)
}
got := make([]int, 0, h.Len())
for _, it := range h.a {
got = append(got, it.Rating)
}
if sort.IntsAreSorted(got) {
t.Fatal("the array came out fully sorted — that is a stronger property " +
"than a heap has, and it costs more than a heap costs")
}
// It is a heap, though: every parent is <= its children.
if !h.IsHeap() {
t.Fatal("the heap invariant does not hold")
}
min, _ := h.Peek()
for _, it := range items {
if it.Rating < min.Rating {
t.Fatalf("Peek returned %d but %d is present", min.Rating, it.Rating)
}
}
}
// TopKHeap must agree with sorting, and cost far less.
func TestTopKAgreesWithSortingAndCostsLess(t *testing.T) {
items := scatteredRatings(100000)
const k = 10
var hc metrics.Counter
byHeap := TopKHeap(items, k, &hc)
var sc metrics.Counter
bySort := topKSort(items, k, &sc)
if len(byHeap) != k {
t.Fatalf("heap returned %d items, want %d", len(byHeap), k)
}
for i := range byHeap {
if byHeap[i].Rating != bySort[i].Rating {
t.Fatalf("rank %d: heap %d, sort %d", i, byHeap[i].Rating, bySort[i].Rating)
}
}
// O(n log k) against O(n log n): with k=10 and n=100000 the heap should be
// within a small multiple of n, while the sort is not.
if float64(hc.N()) > 2*float64(len(items)) {
t.Errorf("%d comparisons for k=%d, want about n=%d", hc.N(), k, len(items))
}
if hc.N() >= sc.N() {
t.Errorf("heap %d comparisons, sort %d — the heap should win by a lot", hc.N(), sc.N())
}
t.Logf("n=%d k=%d: heap %d comparisons, sort %d (%.1fx)",
len(items), k, hc.N(), sc.N(), float64(sc.N())/float64(hc.N()))
}
// AND THE HONEST BOUNDARY: at large k the heap LOSES. O(n log k) is only a win
// while log k is well under log n.
func TestTopKLosesWhenKApproachesN(t *testing.T) {
items := scatteredRatings(100000)
var hc metrics.Counter
TopKHeap(items, len(items), &hc)
var sc metrics.Counter
topKSort(items, len(items), &sc)
if hc.N() <= sc.N() {
t.Errorf("at k=n the heap used %d comparisons and the sort %d — the heap "+
"is expected to lose here", hc.N(), sc.N())
}
t.Logf("k=n: heap %d comparisons, sort %d (%.1fx worse)",
hc.N(), sc.N(), float64(hc.N())/float64(sc.N()))
}
// LESSON 6'S UNANSWERED QUESTION. There the standard library won; here it does
// not, and the benchmarks are where that shows.
//
// go test -run XXX -bench 'Heap' -benchtime=20x -count=5
func benchHeapItems() []Item { return scatteredRatings(10000) }
func BenchmarkHeapMine(b *testing.B) {
items := benchHeapItems()
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
h := NewMinHeap(len(items))
for _, it := range items {
h.Push(it, &c)
}
for h.Len() > 0 {
h.Pop(&c)
}
}
}
func BenchmarkHeapStdlib(b *testing.B) {
items := benchHeapItems()
b.ResetTimer()
for i := 0; i < b.N; i++ {
s := &stdItems{}
stdheap.Init(s)
for _, it := range items {
stdheap.Push(s, it)
}
for s.Len() > 0 {
stdheap.Pop(s)
}
}
}
func BenchmarkTopKHeap(b *testing.B) {
items := scatteredRatings(100000)
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
TopKHeap(items, 10, &c)
}
}
func BenchmarkTopKSort(b *testing.B) {
items := scatteredRatings(100000)
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
topKSort(items, 10, &c)
}
}