Resort top numbers

This commit is contained in:
2022-03-14 21:35:34 +11:00
parent c090c4ec97
commit c9a82b134a
5 changed files with 63 additions and 7 deletions
+1 -1
View File
@@ -47,5 +47,5 @@ func CalculateLargestNumbers(filePath string, topX int) ([]int, error) {
}
}
return topXHeap, nil
return sortDesc(topXHeap), nil
}
+5 -6
View File
@@ -1,9 +1,8 @@
package calculator
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCalculateLargestNumbers(t *testing.T) {
@@ -23,7 +22,7 @@ func TestCalculateLargestNumbers(t *testing.T) {
filePath: "../test1.txt",
topX: 3,
},
want: []int{0, 2, 5},
want: []int{5, 2, 0},
wantErr: false,
},
{
@@ -41,7 +40,7 @@ func TestCalculateLargestNumbers(t *testing.T) {
filePath: "../test3.txt",
topX: 4,
},
want: []int{23435, 38949, 11111, 11111},
want: []int{38949, 23435, 11111, 11111},
wantErr: false,
},
{
@@ -50,7 +49,7 @@ func TestCalculateLargestNumbers(t *testing.T) {
filePath: "../test2.txt",
topX: 5,
},
want: []int{1, 9, 3, 2},
want: []int{9, 3, 2, 1},
wantErr: false,
},
{
@@ -88,7 +87,7 @@ func TestCalculateLargestNumbers(t *testing.T) {
t.Errorf("CalculateLargestNumbers() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !assert.ElementsMatch(t, got, tt.want) {
if err == nil && !reflect.DeepEqual(got, tt.want) {
t.Errorf("test CalculateLargestNumbers() = %v, want %v", got, tt.want)
}
})
+10
View File
@@ -0,0 +1,10 @@
package calculator
import "sort"
func sortDesc(numbers []int) []int {
sort.SliceStable(numbers, func(i, j int) bool {
return numbers[i] > numbers[j]
})
return numbers
}
+46
View File
@@ -0,0 +1,46 @@
package calculator
import (
"reflect"
"testing"
)
func TestSort(t *testing.T) {
type args struct {
numbers []int
}
tests := []struct {
name string
args args
want []int
}{
{
name: "Should sort numbers",
args: args{
numbers: []int{1, 2, 3, 4, 5},
},
want: []int{5, 4, 3, 2, 1},
},
{
name: "Should sort mixed order numbers",
args: args{
numbers: []int{1, 11, 2, 9, 8},
},
want: []int{11, 9, 8, 2, 1},
},
{
name: "Should handler duplicate numbers",
args: args{
numbers: []int{11, 11, 20, 9, 20, 8},
},
want: []int{20, 20, 11, 11, 9, 8},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := sortDesc(tt.args.numbers); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Sort() = %v, want %v", got, tt.want)
}
})
}
}
+1
View File
@@ -23,6 +23,7 @@ func main() {
fmt.Println("Oops: " + err.Error())
os.Exit(1)
}
fmt.Printf("Top %d numbers for file %s are: %v", topNumber, filePath, topNumbers)
}