autopilot: add Median method
This commit is contained in:
parent
4d8100cc9a
commit
6860ad9ac6
@ -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
Normal file
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)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user