golang 一维数组变二维数组,根据字段排序随机

golang 一维数组变二维数组,根据字段排序随机

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main

import (
"encoding/json"
"fmt"
"math/rand"
"sort"
"time"
)

type DemoItemModel struct {
ID int `json:"id"`
Name string `json:"name"`
SortValue int `json:"sort_value"`
}

type DemoModel []DemoItemModel

type SortKeys []int

type Groups struct {
sortNum SortKeys
data map[int]DemoModel
}

func (s SortKeys) Len() int { return len(s) }
func (s SortKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SortKeys) Less(i, j int) bool { return s[i] < s[j] }

func NewGroups() *Groups {
return &Groups{
sortNum: make([]int, 0),
data: make(map[int]DemoModel, 0),
}
}

func (a *Groups) sortKey() []int {
sort.Sort(a.sortNum)
return a.sortNum
}

func (a *Groups) append(key int, item DemoItemModel) {
a.data[key] = append(a.data[key], item)
}

func NewGroup() DemoModel {
return make([]DemoItemModel, 0)
}

func (a *Groups) Add(num int) {
a.sortNum = append(a.sortNum, num)
a.data[num] = NewGroup()
}

func (a *Groups) Exits(num int) bool {
if a.data[num] == nil {
return false
}
return true
}

func GetRandomItems(a DemoModel) []DemoItemModel {
groups := NewGroups()
for _, item := range a {
sort := item.SortValue
if !groups.Exits(sort) {
groups.Add(sort)
}
groups.append(sort, item)
}
return groups.Sort()
}

func (a *DemoModel) Random() DemoModel {
length := len(*a)
temp := make([]DemoItemModel, 0)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
random := r.Intn(length)
temp = append(temp, (*a)[random])
*a = append((*a)[:random], (*a)[random+1:]...)
length = len(*a)
if length < 1 {
break
}
}
*a = temp

return temp
}

func (a *Groups) Sort() []DemoItemModel {
temp := make([]DemoItemModel, 0)
for _, item := range a.sortKey() {
data := a.data[item]
temp = append(temp, data.Random()...)
}
return temp
}

func main() {

objString := `[{"id":1,"name":"1-1","sort_value":1},{"id":2,"name":"1-2","sort_value":1},{"id":3,"name":"2-1","sort_value":2},{"id":4,"name":"2-2","sort_value":2},{"id":5,"name":"2-3","sort_value":2},{"id":6,"name":"5-1","sort_value":5}]`
var someOne []DemoItemModel
if err := json.Unmarshal([]byte(objString), &someOne); err == nil {
fmt.Println("================json str 转struct==")
fmt.Println(someOne)
} else {
fmt.Println(err)
}
fmt.Println(22, GetRandomItems(someOne))

}
感谢你的打赏哦!