autopilot: add Median method

This commit is contained in:
Johan T. Halseth
2019-03-27 15:04:14 +01:00
parent 4d8100cc9a
commit 6860ad9ac6
2 changed files with 70 additions and 0 deletions

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"math/big"
"net"
"sort"
"sync/atomic"
"time"
@@ -501,3 +502,22 @@ func (m memNode) ForEachChannel(cb func(ChannelEdge) error) error {
return nil
}
// Median returns the median value in the slice of Amounts.
func Median(vals []btcutil.Amount) btcutil.Amount {
sort.Slice(vals, func(i, j int) bool {
return vals[i] < vals[j]
})
num := len(vals)
switch {
case num == 0:
return 0
case num%2 == 0:
return (vals[num/2-1] + vals[num/2]) / 2
default:
return vals[num/2]
}
}