github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/physicscompress2/physics/sorting.go (about) 1 package physics 2 3 import ( 4 "sort" 5 6 "github.com/egonelbre/exp/bit" 7 ) 8 9 type sorterZ struct { 10 order []int 11 get func(i int) int 12 } 13 14 func (s *sorterZ) Len() int { return len(s.order) } 15 func (s *sorterZ) Swap(i, j int) { s.order[i], s.order[j] = s.order[j], s.order[i] } 16 func (s *sorterZ) Less(i, j int) bool { 17 vi := int64(s.get(s.order[i])) 18 vj := int64(s.get(s.order[j])) 19 return bit.ZEncode(vi) < bit.ZEncode(vj) 20 } 21 22 func SortByZ(items []int, get func(i int) int) { 23 sort.Sort(&sorterZ{ 24 order: items, 25 get: get, 26 }) 27 } 28 29 type sorterZCount struct { 30 order []int 31 get func(i int) int 32 } 33 34 func (s *sorterZCount) Len() int { return len(s.order) } 35 func (s *sorterZCount) Swap(i, j int) { s.order[i], s.order[j] = s.order[j], s.order[i] } 36 func (s *sorterZCount) Less(i, j int) bool { 37 vi := int64(s.get(s.order[i])) 38 vj := int64(s.get(s.order[j])) 39 return bit.Count(bit.ZEncode(vi)) < bit.Count(bit.ZEncode(vj)) 40 } 41 42 func SortByZCount(items []int, get func(i int) int) { 43 sort.Sort(&sorterZCount{ 44 order: items, 45 get: get, 46 }) 47 }