From bfa6a3e3ea89f306520067144a836b35b5e7d37a Mon Sep 17 00:00:00 2001 From: Junwei Zhao Date: Tue, 23 Apr 2019 14:15:55 +1000 Subject: [PATCH] init commit --- main.go | 115 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 main.go diff --git a/main.go b/main.go new file mode 100644 index 0000000..3eb442d --- /dev/null +++ b/main.go @@ -0,0 +1,115 @@ +package main + +import ( + "flag" + "fmt" + "math/rand" + "sort" + "time" +) + +// const +const ( + NumberCount = 7 + MaximumResults = 50 +) + +var ( + winners = make(map[[NumberCount]int]int) +) + +func main() { + timesInput := flag.Int("t", 100000, "an int") + flag.Parse() + times := *timesInput + + now := time.Now() + + startTime := now.Unix() + + fmt.Printf("Started at %v to run lottery for %v times \n", now, times) + for i := 0; i < times; i++ { + winner := run() + if currentTimes, ok := winners[winner]; ok { + winners[winner] = currentTimes + 1 + } else { + winners[winner] = 1 + } + } + + fmt.Printf("Calculation finished at : %v \n", time.Now()) + // only print out top numbers + type kv struct { + Key [NumberCount]int + Value int + } + + var ss []kv + for k, v := range winners { + // to reduce the time consuming, if the number only exists once then skip it + if v > 1 { + ss = append(ss, kv{k, v}) + } + + } + + sort.Slice(ss, func(i, j int) bool { + return ss[i].Value > ss[j].Value + }) + + fmt.Printf("Sorting finished at : %v \n", time.Now()) + + index := 0 + for _, kv := range ss { + // only pick the top numbers + if index > MaximumResults { + break + } + fmt.Printf("%v, %d \n", kv.Key, kv.Value) + index++ + } + fmt.Printf("The process takes about: %v seconds", time.Now().Unix()-startTime) +} + +func run() [7]int { + var winNumbers []int + // generate the randomised numbers + list := rand.Perm(45) + // because perm generate [0,45) but we need [1,45] + for index, item := range list { + list[index] = item + 1 + } + + rand.Seed(time.Now().UnixNano()) + + indexes := make([]int, 0) + + for i := 0; i < NumberCount; i++ { + pickedIndex := pickIndex(indexes, len(list)) + indexes = append(indexes, pickedIndex) + + //pick random number + chosen := list[pickedIndex] + + winNumbers = append(winNumbers, chosen) + } + + sort.Ints(winNumbers) + var arr [NumberCount]int + copy(arr[:], winNumbers) + + return arr + +} + +func pickIndex(indexes []int, length int) int { + chosen := rand.Intn(length - 1) + // make sure the index only exist once + for _, value := range indexes { + if value == chosen { + return pickIndex(indexes, length) + } + } + + return chosen +}