Created
November 29, 2016 09:52
-
-
Save sgade/f12fb450878038d7147d47df88394d99 to your computer and use it in GitHub Desktop.
Randomly output one of the input lines
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
// Copyright (c) 2016 Sören Gade | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"math/rand" | |
"os" | |
"time" | |
) | |
func main() { | |
// this holds all input lines | |
var input []string | |
// scanner reads each input line into the destination buffer | |
scanner := bufio.NewScanner(os.Stdin) | |
// read each line | |
for scanner.Scan() { | |
line := scanner.Text() | |
input = append(input, line) | |
} | |
// check for errors | |
if err := scanner.Err(); err != nil { | |
fmt.Printf("Error reading input: %v.\n", err) | |
os.Exit(1) | |
} | |
// seed the number generator | |
rand.Seed(time.Now().UnixNano()) | |
// get the index | |
index := rand.Intn(len(input)) | |
// output the random line | |
fmt.Printf("%v\n", input[index]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment