Created
January 27, 2016 05:20
-
-
Save sargunv/9dcfd77861b194a6f071 to your computer and use it in GitHub Desktop.
Kotlin sequence drop problem tester
This file contains 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 com.github.andrewoma.kommon.util.StopWatch | |
import java.util.concurrent.TimeUnit | |
class Squares(val length: Long): Iterable<Long>, Sequence<Long> { | |
override fun iterator() = object : Iterator<Long> { | |
var current: Long = 0 | |
override fun hasNext() = current < length | |
override fun next() = Math.pow(current++.toDouble(), 2.toDouble()).toLong() | |
} | |
} | |
val sizes = listOf<Long>(100, 500, 1000, 1500) | |
fun test(name: String, block: ()->Unit) { | |
val sw = StopWatch(); | |
sw.start() | |
block() | |
sw.stop() | |
println("${sw.toString(TimeUnit.MILLISECONDS)}\t$name") | |
} | |
fun main(vararg args: String) { | |
sizes.forEach { size -> | |
test("Iterable drop $size") { | |
var x: Iterable<Long> = Squares(size) | |
while (x.firstOrNull() != null) | |
x = x.drop(1) | |
} | |
test("Sequence drop $size") { | |
var x: Sequence<Long> = Squares(size) | |
while (x.firstOrNull() != null) | |
x = x.drop(1) | |
} | |
test("Sequence myDrop $size") { | |
var x: Sequence<Long> = Squares(size) | |
while (x.firstOrNull() != null) | |
x = x.myDrop(1) | |
} | |
println() | |
} | |
} | |
fun <T> Sequence<T>.myDrop(n: Int): Sequence<T> { | |
require(n >= 0) { "Requested element count $n is less than zero." } | |
return when { | |
n == 0 -> this | |
this is MyDropSequence -> MyDropSequence(this.sequence, this.count + n) | |
else -> MyDropSequence(this, n) | |
} | |
} | |
class MyDropSequence<T>( | |
val sequence: Sequence<T>, | |
val count: Int | |
): Sequence<T> { | |
init { | |
require(count >= 0) { throw IllegalArgumentException("count should be non-negative, but it is $count") } | |
} | |
override fun iterator(): Iterator<T> = object : Iterator<T> { | |
val iterator = sequence.iterator() | |
var left = count | |
private fun drop() { | |
while (left > 0 && iterator.hasNext()) { | |
iterator.next() | |
left-- | |
} | |
} | |
override fun next(): T { | |
drop() | |
return iterator.next() | |
} | |
override fun hasNext(): Boolean { | |
drop() | |
return iterator.hasNext() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output: