diff options
author | Michaël Ball <michael.ball@gmail.com> | 2017-01-07 18:07:51 +0000 |
---|---|---|
committer | Michaël Ball <michael.ball@gmail.com> | 2017-01-07 18:07:51 +0000 |
commit | b57ee0ffc26098560202c751de9142c88d80bcc6 (patch) | |
tree | 5ed722cfc8d9a262821e5c14cc687b7fd6f6b5ab /generator/generator.go | |
parent | 6068ab484fa377917514753becf61d2211460218 (diff) | |
parent | 7e0c7250e1a9afd9930fbb200c5cbd9a8095404e (diff) |
Merge branch 'release/0.2.0'0.2.0
Diffstat (limited to 'generator/generator.go')
-rw-r--r-- | generator/generator.go | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/generator/generator.go b/generator/generator.go new file mode 100644 index 0000000..3ec5154 --- /dev/null +++ b/generator/generator.go @@ -0,0 +1,45 @@ +package generator + +import ( + "bufio" + "math/rand" + "os" + "time" +) + +func readLines(path string) ([]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + var lines []string + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + return lines, scanner.Err() +} + +// RandomWords picks numberOfWords random words from the file located at +// wordsFile +func RandomWords(wordsFile string, numberOfWords int) ([]string, error) { + rand.Seed(time.Now().UTC().UnixNano()) + + words, err := readLines(wordsFile) + + if err != nil { + return nil, err + } + + phraseWords := make([]string, numberOfWords) + + for index := 0; index < numberOfWords; index++ { + randInt := rand.Intn((len(words) - 1)) + + phraseWords[index] = words[randInt] + } + + return phraseWords, nil +} |