Skip to content

Instantly share code, notes, and snippets.

@timyates
Created December 23, 2014 22:19
Show Gist options
  • Save timyates/32207c13b1cda05d5393 to your computer and use it in GitHub Desktop.
Save timyates/32207c13b1cda05d5393 to your computer and use it in GitHub Desktop.
FizzBuzz with groovy-stream and no conditionals
@Grab('com.bloidonia:groovy-stream:0.9.0')
import groovy.stream.*
def (n, f, b, fb) = [Closure.IDENTITY, { 'fizz' }, { 'buzz' }, {'fizzbuzz'}]
def fns = Stream.from([n, n, f, n, b, f, n, n, f, b, n, f, n, n, fb]).repeat()
def num = Stream.from(1..100).zip(fns) { counter, fn -> fn(counter) }
num.each { println it }
@dvberkel
Copy link

I really like your code!

I am toying with idea of generating the array from similar principles but I haven't got a solution yet. I will keep you posted.

@dvberkel
Copy link

It got this, but it lacks your elegance

@Grab('com.bloidonia:groovy-stream:0.9.0')
import groovy.stream.*

def (n, f, b) = [
    { [ it[0], it[1] + '' ] },
    { [ it[0], it[1] + 'fizz' ] },
    { [ it[0], it[1] + 'buzz' ] }
]

def fizzs = Stream.from([f, n, n]).repeat()
def buzzs = Stream.from([b, n, n, n, n]).repeat()

def fizzbuzzs = fizzs.zip(buzzs) { u, v -> [u, v] }

def s = Stream.from(0..100).zip(fizzbuzzs) {
    index, fs -> fs.inject([index, '']) { r, g -> g(r) }
}

def t = s.map { tuple -> tuple[1].size() > 0 ? tuple[1] : tuple[0] }

t.each { println it }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment