Last active
February 3, 2016 00:36
-
-
Save h0tk3y/6dda2b292d8804d72967 to your computer and use it in GitHub Desktop.
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 kotlin.system.measureTimeMillis | |
| /** | |
| * Created by igushs on 2/2/16. | |
| */ | |
| public operator fun <T> Sequence<T>.plus(otherGenerator: () -> Sequence<T>) = | |
| object : Sequence<T> { | |
| private val thisIterator: Iterator<T> by lazy { [email protected]() } | |
| private val otherIterator: Iterator<T> by lazy { otherGenerator().iterator() } | |
| override fun iterator() = object : Iterator<T> { | |
| override fun next(): T = | |
| if (thisIterator.hasNext()) | |
| thisIterator.next() | |
| else | |
| otherIterator.next() | |
| override fun hasNext(): Boolean = | |
| thisIterator.hasNext() || otherIterator.hasNext() | |
| } | |
| } | |
| fun primes(): Sequence<Int> { | |
| fun primesFilter(from: Sequence<Int>): Sequence<Int> = from.iterator().let { | |
| val current = it.next() | |
| sequenceOf(current) + { primesFilter(it.asSequence().filter { it % current != 0 }) } | |
| } | |
| return primesFilter((2..Int.MAX_VALUE).asSequence()) | |
| } | |
| fun main(args: Array<String>) { | |
| println(measureTimeMillis { primes().take(1000).toList() }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment