Skip to content

Instantly share code, notes, and snippets.

@proglottis
Last active December 24, 2015 11:09
Show Gist options
  • Save proglottis/6788547 to your computer and use it in GitHub Desktop.
Save proglottis/6788547 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/md5"
"fmt"
"io"
"math/rand"
"runtime"
"time"
)
const pattern = "Hello, James here. %s. I like cupcakes."
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
func RandomString(length int, generator *rand.Rand) string {
ret := ""
for i := 0; i < length; i++ {
ret += string(chars[generator.Intn(len(chars))])
}
return ret
}
type Stamp struct {
Attempt string
Sum []byte
}
func (s *Stamp) MakeAttempt(generator *rand.Rand) {
s.Attempt = fmt.Sprintf(pattern, RandomString(15, generator))
hash := md5.New()
io.WriteString(hash, s.Attempt)
s.Sum = hash.Sum(nil)
}
func (s *Stamp) IsValid() bool {
count := 0
for _, b := range s.Sum[:3] {
if b == 0 {
count++
}
}
return count >= 3
}
func FindStamp(c chan<- *Stamp) {
source := rand.NewSource(time.Now().UnixNano())
generator := rand.New(source)
stamp := new(Stamp)
for {
stamp.MakeAttempt(generator)
if stamp.IsValid() {
c <- stamp
return
}
}
}
func main() {
c := make(chan *Stamp)
num_cpus := runtime.NumCPU()
runtime.GOMAXPROCS(num_cpus)
for i := 0; i < num_cpus; i++ {
go FindStamp(c)
}
stamp := <-c
fmt.Printf("%s\n%x\n", stamp.Attempt, stamp.Sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment