File: count.go

package info (click to toggle)
golang-github-shenwei356-util 0.0~git20201231.861956c-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 192 kB
  • sloc: makefile: 2
file content (74 lines) | stat: -rw-r--r-- 1,697 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package byteutil

import "sort"

// ByteCount is a struct store count of byte
type ByteCount struct {
	Key   byte
	Count int
}

// ByteCountList is slice of ByteCount
type ByteCountList []ByteCount

func (b ByteCountList) Len() int { return len(b) }
func (b ByteCountList) Less(i, j int) bool {
	// return b[i].Count < b[j].Count
	// This will return unwanted result: return b[i].Count < b[j].Count || b[i].Key < b[j].Key
	if b[i].Count < b[j].Count {
		return true
	}
	if b[i].Count == b[j].Count {
		if b[i].Key < b[j].Key {
			return true
		}
		return false
	}
	return false
}
func (b ByteCountList) Swap(i, j int) { b[i], b[j] = b[j], b[i] }

// ReversedByteCountList is Reversed ByteCountList
type ReversedByteCountList struct {
	ByteCountList
}

// Less is different from the Less of ByteCountList
func (b ReversedByteCountList) Less(i, j int) bool {
	// return b.ByteCountList[i].Count > b.ByteCountList[j].Count
	if b.ByteCountList[i].Count > b.ByteCountList[j].Count {
		return true
	}
	if b.ByteCountList[i].Count == b.ByteCountList[j].Count {
		if b.ByteCountList[i].Key < b.ByteCountList[j].Key {
			return true
		}
		return false
	}
	return false
}

// CountOfByte returns the count of byte for a byte slice
func CountOfByte(s []byte) map[byte]int {
	count := make(map[byte]int)
	for _, b := range s {
		count[b]++
	}
	return count
}

// SortCountOfByte sorts count of byte
func SortCountOfByte(count map[byte]int, reverse bool) ByteCountList {
	countList := make(ByteCountList, len(count))
	i := 0
	for b, c := range count {
		countList[i] = ByteCount{b, c}
		i++
	}
	if reverse {
		sort.Sort(ReversedByteCountList{countList})
	} else {
		sort.Sort(countList)
	}
	return countList
}