patterngoMinor
Sleepsort in Go
Viewed 0 times
sleepsortstackoverflowprogramming
Problem
I implemented sleepsort in Go. I am new to channels, and I'd like to get some advice on them, especially on how to close channels after N messages have been sent on them. Currently I use a counter and an if statement (see the second for loop in
Other advice is also very appreciated.
Sleepsort), but maybe this can be done in a nicer way?package main
import (
"fmt"
"time"
)
func sleep(n int, channel chan<- int) {
time.Sleep(time.Duration(n) * time.Second)
channel <- n
}
func Sleepsort(xs []int) []int {
channel := make(chan int, len(xs))
for _, x := range xs {
go sleep(x, channel)
}
result := make([]int, len(xs))
i := 0
for x := range channel {
result[i] = x
i++
if i == len(xs) {
close(channel)
}
}
return result
}
func main() {
xs := []int{2, 5, 2, 1, 4, 3, 5}
fmt.Printf("%v\n", Sleepsort(xs))
}Other advice is also very appreciated.
Solution
I'm self-answering since I found a nicer way to do this.
In this case, you can loop from 0 to N and receive from the channel manually, rather than using
In this case, you can loop from 0 to N and receive from the channel manually, rather than using
range.for i := 0; i < len(xs); i++ {
result[i] = <-channel
}
close(channel)close(channel) is not strictly needed here since the channel would already be closed by the garbage collector.Code Snippets
for i := 0; i < len(xs); i++ {
result[i] = <-channel
}
close(channel)Context
StackExchange Code Review Q#26587, answer score: 4
Revisions (0)
No revisions yet.