advent-of-code/ranger/range.go

85 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-04-05 16:27:02 -06:00
package main
// export GOEXPERIMENT=rangefunc
import "iter"
func Step(start, stop, step int) iter.Seq[int] {
if step < 0 {
return func(yield func(int) bool) {
for i := start; i <= start && i > stop; i += step {
next := yield(i)
if !next {
return
}
}
}
}
if step > 0 {
return func(yield func(int) bool) {
for i := start; i >= start && i < stop; i += step {
next := yield(i)
if !next {
println("stopped!")
return
}
}
}
}
return func(yield func(int) bool) { yield(start) }
}
func Fib() iter.Seq[uint] {
return func(yield func(uint) bool) {
previous, value := uint(1), uint(1)
next := yield(value)
for next {
next = yield(value)
value, previous = value+previous, value
if value < previous {
return
}
}
}
}
func Fizzbuzzed[T int | uint](from iter.Seq[T]) iter.Seq2[T, string] {
pull, stop := iter.Pull(from)
return func(yield func(T, string) bool) {
defer stop()
for {
var fizzbuzz string
p, ok := pull()
if !ok {
return
}
if p%3 == 0 {
fizzbuzz = "fizz"
}
if p%5 == 0 {
fizzbuzz += "buzz"
}
if !yield(p, fizzbuzz) {
return
}
}
}
}
// func main() {
// for i, v := range Fizzbuzzed(Fib()) {
// println(i, v)
// }
// }
func countScan(n int) (func() bool, func() int) {
pos := -1
return func() bool {
pos++
return pos < n
}, func() int {
return pos
}
}