Skip to content

Instantly share code, notes, and snippets.

@sgade
Created November 29, 2016 09:52
Show Gist options
  • Save sgade/f12fb450878038d7147d47df88394d99 to your computer and use it in GitHub Desktop.
Save sgade/f12fb450878038d7147d47df88394d99 to your computer and use it in GitHub Desktop.
Randomly output one of the input lines
// 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