github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/sort/sortmap/string-keyed-int.go (about)

     1  // Adding a special case.
     2  // I often have map[string]int for counters. I.e.:
     3  //   mapX["someKey"]++
     4  // SortMapByCount sorts such a map by the integer.
     5  // It then returns the sorted data as a sorted slice of {int,key}.
     6  
     7  package sortmap
     8  
     9  import (
    10  	"fmt"
    11  	"sort"
    12  )
    13  
    14  type sel1 struct {
    15  	Key string
    16  	Cnt int
    17  }
    18  
    19  type SortByCnt []sel1
    20  
    21  func (s SortByCnt) Len() int {
    22  	return len(s)
    23  }
    24  
    25  func (s SortByCnt) Swap(i, j int) {
    26  	s[i], s[j] = s[j], s[i]
    27  }
    28  
    29  func (s SortByCnt) Less(i, j int) bool {
    30  	if s[i].Cnt > s[j].Cnt {
    31  		return true
    32  	}
    33  	return false
    34  }
    35  
    36  // map[string]int is converted into a slice of
    37  // []{Key,Val} and sorted by
    38  func SortMapByCount(m map[string]int) SortByCnt {
    39  
    40  	sT := make([]sel1, 0, len(m))
    41  
    42  	for key, cnt := range m {
    43  		sT = append(sT, sel1{key, cnt})
    44  	}
    45  
    46  	sbc := SortByCnt(sT)
    47  	sort.Sort(sbc)
    48  	return sbc
    49  }
    50  
    51  func (sbc SortByCnt) Print(cols int) {
    52  	cntr := 0
    53  	for k, val := range sbc {
    54  		_ = k
    55  		// fmt.Printf("%2v: %14v %4v ", k, val.Key, val.Cnt)
    56  		fmt.Printf("%14v %4v ", val.Key, val.Cnt)
    57  		cntr++
    58  		if cntr%cols == 0 {
    59  			fmt.Println()
    60  		}
    61  	}
    62  	fmt.Println()
    63  }
    64  
    65  func (s SortByCnt) String() string {
    66  	b := []byte{}
    67  	for _, v := range s {
    68  		b = append(b, []byte(v.Key)...)
    69  		b = append(b, byte(32))
    70  		b = append(b, []byte(fmt.Sprintf("%v", v.Cnt))...)
    71  		b = append(b, byte(32))
    72  	}
    73  	return string(b)
    74  }