Created
February 6, 2015 00:31
-
-
Save hraban/52bb4271603388b1b4a5 to your computer and use it in GitHub Desktop.
Get a random paragraph from a file
This file contains hidden or 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
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