github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/data_comparator.go (about) 1 package sort 2 3 import ( 4 "fmt" 5 "math/rand" 6 "sort" 7 "time" 8 ) 9 10 type sortFunc func([]int) 11 12 func GenerateRandomArr(maxSize int, maxNum int) []int { 13 if maxSize <= 0 { 14 panic("incorrect max size for array") 15 } 16 17 var arr []int 18 rand.Seed(time.Now().UnixNano()) 19 for i := 0; i < maxSize; i++ { 20 arr = append(arr, rand.Intn(maxNum)) 21 } 22 23 return arr 24 } 25 26 func IsEquals(standardArr []int, customizedArr []int) bool { 27 if (standardArr != nil && customizedArr == nil) || 28 (standardArr == nil && customizedArr != nil) { 29 return false 30 } 31 32 if len(standardArr) != len(customizedArr) { 33 return false 34 } 35 36 for i := 0; i < len(standardArr); i++ { 37 if standardArr[i] != customizedArr[i] { 38 return false 39 } 40 } 41 return true 42 } 43 44 func CopyArr(originArr []int, maxSize int) []int { 45 if originArr == nil { 46 return nil 47 } 48 dstArr := make([]int, maxSize) 49 copy(dstArr, originArr) 50 return dstArr 51 } 52 53 func PrintArr(arr []int) { 54 if arr == nil { 55 return 56 } 57 58 fmt.Println(arr) 59 } 60 61 func DataComparator(sf sortFunc, benchmarkNum int, maxArrSize int, maxNum int, isAsc bool) { 62 equals := true 63 for i := 0; i < benchmarkNum; i++ { 64 originArr := GenerateRandomArr(maxArrSize, maxNum) 65 arr1 := CopyArr(originArr, maxArrSize) 66 arr2 := CopyArr(originArr, maxArrSize) 67 68 if isAsc { 69 sort.Slice(arr1, func(i, j int) bool { 70 return arr1[i] < arr1[j] 71 }) 72 } else { 73 sort.Slice(arr1, func(i, j int) bool { 74 return arr1[i] > arr1[j] 75 }) 76 } 77 sf(arr2) 78 79 if !IsEquals(arr1, arr2) { 80 PrintArr(originArr) 81 PrintArr(arr1) 82 PrintArr(arr2) 83 equals = false 84 break 85 } 86 } 87 88 if equals { 89 fmt.Println("Success correct") 90 } else { 91 fmt.Println("Error") 92 } 93 }