From 6860ad9ac6348a49527c0b150fcb069d976ca707 Mon Sep 17 00:00:00 2001 From: "Johan T. Halseth" Date: Wed, 27 Mar 2019 15:04:14 +0100 Subject: [PATCH] autopilot: add Median method --- autopilot/graph.go | 20 +++++++++++++++++ autopilot/graph_test.go | 50 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 autopilot/graph_test.go diff --git a/autopilot/graph.go b/autopilot/graph.go index 95bf89ad..413aaf13 100644 --- a/autopilot/graph.go +++ b/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] + } +} diff --git a/autopilot/graph_test.go b/autopilot/graph_test.go new file mode 100644 index 00000000..a83d7f3a --- /dev/null +++ b/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) + } + } +}