Skip to content

Instantly share code, notes, and snippets.

@wperron
Created March 22, 2022 15:30
Show Gist options
  • Save wperron/88283de6f5e28bfe8ef15ac89e959f5a to your computer and use it in GitHub Desktop.
Save wperron/88283de6f5e28bfe8ef15ac89e959f5a to your computer and use it in GitHub Desktop.
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