Created
May 28, 2017 14:27
-
-
Save superfashi/8f84e288772ca07ade33c284b169933f to your computer and use it in GitHub Desktop.
poor pigs validation
This file contains 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 ( | |
"fmt" | |
"math" | |
"math/rand" | |
"reflect" | |
"time" | |
) | |
const ( | |
buckets = 1000 | |
minutesToDie = 15 | |
minutesToTest = 60 | |
) | |
var ( | |
poison, states int | |
pigsRequire int | |
pigs []PoorPigs | |
convSave []int | |
assign [][][]int | |
) | |
// PoorPigs represents little poor pigs | |
type PoorPigs struct { | |
dead bool | |
} | |
// Drink means that a poor pig's licking its ass | |
func (p *PoorPigs) Drink(bucket int) bool { | |
if bucket == poison { | |
p.dead = true // Oops... | |
return true | |
} | |
return false | |
} | |
// converts a number to a certain numeric system | |
func converter(num int) []int { | |
ret := make([]int, pigsRequire) | |
for i := 0; i < pigsRequire; i++ { | |
ret[i] = num / convSave[i] | |
num %= convSave[i] | |
} | |
return ret | |
} | |
// It's the doomsday of the poor pigs! | |
func init() { | |
// Variable setting | |
rand.Seed(time.Now().UnixNano()) | |
poison = rand.Intn(buckets) | |
states = minutesToTest/minutesToDie + 1 | |
pigsRequire = int(math.Ceil(math.Log(float64(buckets)) / math.Log(float64(states)))) | |
pigs = make([]PoorPigs, pigsRequire) | |
// Pre-calc setting | |
convSave = make([]int, pigsRequire) | |
convSave[pigsRequire-1] = 1 | |
for i := pigsRequire - 2; i >= 0; i-- { | |
convSave[i] = convSave[i+1] * states | |
} | |
assign = make([][][]int, pigsRequire) | |
for i := 0; i < pigsRequire; i++ { | |
assign[i] = make([][]int, states) | |
} | |
for i := 0; i < buckets; i++ { | |
arr := converter(i) | |
for j, k := range arr { | |
assign[j][k] = append(assign[j][k], i) | |
} | |
} | |
} | |
// It's poison-licking good! | |
func main() { | |
final := make([]int, pigsRequire) | |
for i := 0; i < pigsRequire; i++ { | |
final[i] = states - 1 | |
} | |
for i := 0; i < states-1; i++ { | |
for j := 0; j < pigsRequire; j++ { | |
if !pigs[j].dead { | |
for _, k := range assign[j][i] { | |
if pigs[j].Drink(k) { | |
final[j] = i | |
break | |
} | |
} | |
} | |
} | |
} | |
fmt.Println(poison, final, reflect.DeepEqual(converter(poison), final)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment