Groovy web console

subscribe to the feed Subscribe
to this
site
Cookie Jar Challenge (via #groovywebconsole)
tweet this snippet Tweet
this
script

Cookie Jar Challenge

Published 3 weeks ago by Ralf D. M?ler
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def jar = []

100.times {
    def random = (int)(Math.random()*10)
    switch (random) {
        case 0: // Grandma
            10.times {jar<<"cookie"}
            println "grandma just put 10 cookies in the jar. Now we have ${jar.size()} cookies"
            break
        case 1..4: // Cat
            if (jar.size()) {
                jar.pop() 
                println "cat ate a cookie. ${jar.size()} cookies left"
            } else {
                println "cat tried to steal a cookie, but jar was empty"
            }
            break
        case 5..6: // Monster
            if (jar.size()) {
                def numCookies = Math.min((int)(Math.random()*40),jar.size())
                numCookies.times() { jar.pop() }
                println "monster just ate ${numCookies} cookies. Now are ${jar.size()} left"
            } else {
                println "monster only finds an empty jar :-("
            }
            break
    }
}