Browse Source

autopilot: add Median method

master
Johan T. Halseth 5 years ago
parent
commit
6860ad9ac6
No known key found for this signature in database
GPG Key ID: 15BAADA29DA20D26
  1. 20
      autopilot/graph.go
  2. 50
      autopilot/graph_test.go

20
autopilot/graph.go

@ -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]
}
}

50
autopilot/graph_test.go

@ -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)
}
}
}
Loading…
Cancel
Save