Skip to content

Instantly share code, notes, and snippets.

@tonistiigi
Created November 7, 2017 01:06
Show Gist options
  • Save tonistiigi/5ef15ed8eb8874ef48870ad835a6d6f8 to your computer and use it in GitHub Desktop.
Save tonistiigi/5ef15ed8eb8874ef48870ad835a6d6f8 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
"sort"
"strconv"
)
func main() {
if err := gosort(os.Stdin, os.Stdout); err != nil {
panic(err)
}
}
func gosort(r io.Reader, w io.Writer) error {
re := regexp.MustCompile("(\\d+) minutes?\\]")
s := bufio.NewScanner(r)
type block struct {
active int
bytes []byte
}
blocks := make([]block, 0)
b := block{}
add := func(bb block) {
blocks = append(blocks, b)
b = block{}
}
for {
if !s.Scan() {
add(b)
break
}
row := s.Bytes()
if len(row) == 0 {
add(b)
continue
}
if b.bytes == nil {
if matches := re.FindSubmatch(row); len(matches) == 2 {
min, err := strconv.Atoi(string(matches[1]))
if err != nil {
return err
}
b.active = min
}
}
b.bytes = append(b.bytes, row...)
b.bytes = append(b.bytes, '\n')
}
sort.Slice(blocks, func(i, j int) bool {
return blocks[i].active < blocks[j].active
})
for _, r := range blocks {
fmt.Printf("%s\n", r.bytes)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment