autopilot: add Median method

This commit is contained in:
Johan T. Halseth 2019-03-27 15:04:14 +01:00
parent 4d8100cc9a
commit 6860ad9ac6
No known key found for this signature in database
GPG Key ID: 15BAADA29DA20D26
2 changed files with 70 additions and 0 deletions

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"math/big" "math/big"
"net" "net"
"sort"
"sync/atomic" "sync/atomic"
"time" "time"
@ -501,3 +502,22 @@ func (m memNode) ForEachChannel(cb func(ChannelEdge) error) error {
return nil 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]
}
}

50
autopilot/graph_test.go Normal file

@ -0,0 +1,50 @@
package autopilot_test
import (
"testing"
"github.com/btcsuite/btcutil"
"github.com/lightningnetwork/lnd/autopilot"
)
// TestMedian tests the Median method.
func TestMedian(t *testing.T) {
t.Parallel()
testCases := []struct {
values []btcutil.Amount
median btcutil.Amount
}{
{
values: []btcutil.Amount{},
median: 0,
},
{
values: []btcutil.Amount{10},
median: 10,
},
{
values: []btcutil.Amount{10, 20},
median: 15,
},
{
values: []btcutil.Amount{10, 20, 30},
median: 20,
},
{
values: []btcutil.Amount{30, 10, 20},
median: 20,
},
{
values: []btcutil.Amount{10, 10, 10, 10, 5000000},
median: 10,
},
}
for _, test := range testCases {
res := autopilot.Median(test.values)
if res != test.median {
t.Fatalf("expected median %v, got %v", test.median, res)
}
}
}