Skip to content

Instantly share code, notes, and snippets.

@hraban
Created February 6, 2015 00:31
Show Gist options
  • Save hraban/52bb4271603388b1b4a5 to your computer and use it in GitHub Desktop.
Save hraban/52bb4271603388b1b4a5 to your computer and use it in GitHub Desktop.
Get a random paragraph from a file
import scala.io
import scala.util.Random
object RandomQuote {
private def splitParagraphs(r: io.BufferedSource) =
r.mkString.split("\n\n")
private def getRandomElement[T](ar: Array[T]): Option[T] = ar.length match {
case 0 => None
case _ => Some(ar(Random.nextInt(ar.length)))
}
def main(args: Array[String]) {
val file = if (args.length > 0) io.Source.fromFile(args(0)) else io.Source.stdin
val quotes = splitParagraphs(file)
getRandomElement(quotes) map println
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment