Created
April 23, 2019 04:07
-
-
Save wahyd4/7d1c06506e5a7e064f82f5c0a89fa3c8 to your computer and use it in GitHub Desktop.
oz-lott demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment