File: StringCount.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,764 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 stringutil

import "sort"

// StringCount is a struct store count of Key
type StringCount struct {
	Key   string
	Count int
}

// StringCountList is slice of Keycount
type StringCountList []StringCount

func (b StringCountList) Len() int { return len(b) }
func (b StringCountList) 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 StringCountList) Swap(i, j int) { b[i], b[j] = b[j], b[i] }

// ReversedStringCountList is Reversed StringCountList
type ReversedStringCountList struct {
	StringCountList
}

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

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

// SortCountOfString sorts count of Key
func SortCountOfString(count map[string]int, reverse bool) StringCountList {
	countList := make(StringCountList, len(count))
	i := 0
	for b, c := range count {
		countList[i] = StringCount{b, c}
		i++
	}
	if reverse {
		sort.Sort(ReversedStringCountList{countList})
	} else {
		sort.Sort(countList)
	}
	return countList
}