Last active
May 10, 2016 17:50
-
-
Save julienhay/5b7384fca28f00ba155ee6504964c2b8 to your computer and use it in GitHub Desktop.
Code generator
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 ( | |
"github.com/lazybeaver/xorshift" | |
"log" | |
"os" | |
"strconv" | |
"time" | |
) | |
const ( | |
possibleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
) | |
var totalCode, possibleCharsLength, lengthCode int | |
var outputFile string | |
var randomValue uint64 | |
func init() { | |
// Default values | |
totalCode = 10 | |
lengthCode = 5 | |
outputFile = "output.txt" | |
if len(os.Args) >= 2 { | |
totalCode, _ = strconv.Atoi(os.Args[1]) | |
} | |
if len(os.Args) >= 3 { | |
lengthCode, _ = strconv.Atoi(os.Args[2]) | |
} | |
if len(os.Args) >= 4 { | |
outputFile = os.Args[3] | |
} | |
possibleCharsLength = len(possibleChars) | |
} | |
func main() { | |
start := time.Now() | |
writeContent(generateCodes(totalCode), outputFile) | |
elapsed := time.Since(start) | |
log.Printf("Total time %s", elapsed) | |
} | |
func generateCodes(totalCodes int) (codes map[string]int) { | |
count := 0 | |
codes = make(map[string]int) | |
seed := uint64(time.Now().Nanosecond()) | |
xor64s := xorshift.NewXorShift64Star(seed) | |
for count < totalCode { | |
randomValueString := "" | |
for len(randomValueString) < (lengthCode * 2) { | |
randomValue = xor64s.Next() | |
randomValueString += strconv.FormatUint(randomValue, 10) | |
} | |
s := []int{} | |
for i := 0; i < len(randomValueString)-1; i += 2 { | |
tow_num, _ := strconv.Atoi(string(randomValueString[i]) + string(randomValueString[i+1])) | |
s = append(s, tow_num%possibleCharsLength) | |
} | |
var code string | |
for i := 0; i < lengthCode; i++ { | |
code += string(possibleChars[s[i]]) | |
} | |
code += "\n" | |
codes[code]++ | |
if len(codes) == count+1 { | |
count++ | |
} | |
} | |
return | |
} | |
func writeContent(content map[string]int, output string) { | |
os.Remove(output) | |
os.Create(output) | |
f, err := os.OpenFile(output, os.O_APPEND|os.O_WRONLY, 0600) | |
if err != nil { | |
panic(err) | |
} | |
defer f.Close() | |
for code, _ := range content { | |
if _, err = f.WriteString(code); err != nil { | |
panic(err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment