Go語言演算法:切片處理
阿新 • • 發佈:2019-01-04
判斷切片相等
func AreEquivalentSlice(temp, answers []interface{}) bool { if len(temp) != len(answers) { return false } else { for i, v := range temp { //先判斷型別是否相同 if reflect.TypeOf(v) != reflect.TypeOf(answers[i]) { return false } if v != answers[i] { return false } } } return true }
切片洗牌
/*打亂任意型別切片*/ func ShuffleSlice(slice []interface{}) []interface{} { var newSlice = []interface{}{} r := rand.New(rand.NewSource(time.Now().UnixNano())) for { if len(newSlice) == len(slice) { break } index := r.Intn(len(slice)) value := slice[index] if value != nil { newSlice = append(newSlice, value) slice[index] = nil } } return newSlice }
獲得亂序切片
/*獲得指定範圍的亂序切片*/
func GetShuffledIntSlice(start, end int) []int {
var slice = []int{}
for i := start; i < end; i++ {
slice = append(slice, i)
}
//得到slice亂序切片
slice = ShuffleIntSlice(slice)
return slice
}