Skip to content

Instantly share code, notes, and snippets.

@wperron
Created Mar 22, 2022
Embed
What would you like to do?
Find the shortest interval in a list by *sleeping*
package main
import (
"fmt"
"time"
)
var (
input = []string{"01h00m", "08h15m", "11h30m", "13h45m", "14h10m", "20h05m"}
)
func main() {
c := make(chan struct{})
wg := sync.WaitGroup{}
wg.Add(len(input))
for _, s := range input {
d, err := time.ParseDuration(s)
if err != nil {
panic(err)
}
go func() {
time.Sleep(d)
c <- struct{}{}
wg.Done()
}()
}
go func() {
wg.Wait()
close(c)
}()
var last time.Time
var smol time.Duration
for range c {
if last.IsZero() {
last = time.Now()
continue
}
now := time.Now()
elapsed := now.Sub(last)
if int64(smol) == 0 || elapsed < smol {
smol = elapsed
}
last = now
}
fmt.Println("smallest interval:", smol)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment