Skip to content

Instantly share code, notes, and snippets.

@nickwanninger
Created August 29, 2018 19:26
Show Gist options
  • Select an option

  • Save nickwanninger/9228929f6042940477158f304980fbc1 to your computer and use it in GitHub Desktop.

Select an option

Save nickwanninger/9228929f6042940477158f304980fbc1 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
)
func main() {
values := randomInts(100)
fmt.Println(values)
fmt.Println(ArrowSort(values))
}
const gravity = 9.80665 // m/s
type Arrow struct {
payload int
height float64
velocity float64
landed bool
}
func (a *Arrow) Fire(velocity float64) {
a.velocity = velocity
}
func NewArrow(value int) *Arrow {
return &Arrow{
payload: value,
height: 0.0,
velocity: 0.0,
}
}
func (a *Arrow) Tick() bool {
a.height += a.velocity
a.velocity -= gravity
if a.height <= 0 {
a.landed = true
}
return a.landed
}
func ArrowSort(values []int) []int {
sorted := make([]int, 0, len(values)) // Allocate enough space for the sorted values
hits := make(chan int)
arrows := make([]*Arrow, 0, len(values))
for _, v := range values {
a := NewArrow(v)
a.Fire(float64(v))
arrows = append(arrows, a)
}
go func() {
flying := true
for flying {
for _, a := range arrows {
if !a.landed {
flying = !a.Tick()
if !flying {
hits <- a.payload
}
}
}
}
close(hits)
}()
for hit := range hits {
sorted = append(sorted, hit)
}
return sorted
}
func randomInts(count int) []int {
values := make([]int, 0, count)
for i := 0; i < count; i++ {
values = append(values, rand.Int()%30)
}
return values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment