Skip to content

Instantly share code, notes, and snippets.

@lukekrikorian
Created May 14, 2019 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukekrikorian/3f0d4d80beccd718e8c42160255b7cc0 to your computer and use it in GitHub Desktop.
Save lukekrikorian/3f0d4d80beccd718e8c42160255b7cc0 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"math/big"
"sort"
crypto "crypto/rand"
)
/* First try: 32,893,123 Guesses */
var (
winningCombo = []byte{7, 13, 18, 34, 36, 42}
guesses = 0
loop = true
guess = make([]byte, 6)
)
func main() {
/* While the loop value is true... */
for loop == true {
guesses++ // Increment the amount of guesses
/* Loop over the six numbers in our guess array... */
for i := range guess {
var (
next bool
gen byte
) /* There are two values being created in each loop, the
the `gen` value, which is the generated random number,
and the `next` boolean which lets the next loop down
below know if we can move onto the next number in the
guess array */
/* Keep looping until `next` is true.. */
for next == false {
/* Generate a new random number */
big, _ := crypto.Int(crypto.Reader, big.NewInt(49))
gen = byte(big.Int64()) // Convert it to a byte
/* If we're on the first number in the guess array,
we have nothing to compare that number to so we just
skip it, but otherwise, we check if `guess` already
contains the number we just generated. If it doesn't
have that number we set `next` to true, so that the
outer loop can move forward */
if i == 0 || !contains(guess, gen) {
next = true
}
}
guess[i] = gen // Assign the generated number to index `i`
}
/* Sort the guess array, e.g [3, 13, 7] -> [3, 7, 13] */
sort.Slice(guess, func(i, j int) bool {
return guess[i] < guess[j]
})
/* If the bytes of `guess` and `winningCombo` are equal,
we have a match! Print out some next, the number of
guesses, and end our first loop by setting `loop` to
false */
if bytes.Equal(guess, winningCombo) {
loop = false
fmt.Printf("WINNING GUESS!\n")
fmt.Printf("%d Guesses\n", guesses)
}
}
}
func contains(s []byte, e byte) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment