Skip to content

Instantly share code, notes, and snippets.

@yewton
Last active December 14, 2015 16:49
Show Gist options
  • Save yewton/5118008 to your computer and use it in GitHub Desktop.
Save yewton/5118008 to your computer and use it in GitHub Desktop.
// from http://stackoverflow.com/questions/15182496/why-does-this-code-print-hello-world
import java.util.Random
import scala.annotation.tailrec
object HelloWorld extends App {
println(randomString(-229985452) +" "+ randomString(-147909649))
println(randomString2(-229985452) +" "+ randomString2(-147909649))
println(randomString3(-229985452) +" "+ randomString3(-147909649))
println(randomString4(-229985452) +" "+ randomString4(-147909649))
def randomString(i :Int) :String = {
val rand = new Random(i)
val sb = new StringBuilder()
rs(rand.nextInt(27))
@tailrec
def rs(k :Int) {
if (k == 0) return
else {
sb.append(('`' + k).toChar)
rs(rand.nextInt(27))
}
}
sb.toString
}
def randomString2(i :Int) :String = {
val rand = new Random(i)
def mkList(rand :Random) :List[Int] = {
val k = rand.nextInt(27)
if (k == 0) Nil
else k :: mkList(rand)
}
("" /: mkList(rand)){ (x, y) => x + (('`' + y).toChar.toString) }
}
def randomString3(i :Int) :String = {
val rand = new Random(i)
@tailrec
def mkList(l :List[Int]) :List[Int] = {
val k = rand.nextInt(27)
if (k == 0) l
else mkList(k :: l)
}
("" /: mkList(Nil)){ (x, y) => (('`' + y).toChar.toString) + x }
}
def randomString4(i :Int) :String = {
val rand = new Random(i)
val sb = new StringBuilder()
Iterator.continually(rand.nextInt(27)).takeWhile(_ != 0).foreach(k => sb.append(('`' + k).toChar.toString))
sb.toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment