Guest User

Untitled

a guest
Jan 23rd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "reflect"
  5. "sort"
  6. "testing"
  7. )
  8.  
  9. func filterByAppend(input []int) []int {
  10. output := input[:0]
  11. for _, num := range input {
  12. if num != 0 {
  13. output = append(output, num)
  14. }
  15. }
  16. return output
  17. }
  18.  
  19. func filterBySwap(input []int) []int {
  20. var zero int
  21. for i, num := range input {
  22. if num != 0 {
  23. input[i], input[zero] = input[zero], input[i]
  24. zero++
  25. }
  26. }
  27. return input[:zero]
  28. }
  29.  
  30. func filterBySort(input []int) []int {
  31. var border int
  32. sort.Ints(input)
  33. for i, num := range input {
  34. if num != 0 {
  35. border = i
  36. break
  37. }
  38. }
  39. return input[border:]
  40. }
  41.  
  42. func TestFilter(t *testing.T) {
  43. tests := []struct {
  44. name string
  45. algorithm func([]int) []int
  46. input, expected []int
  47. }{
  48. {"filter by append", filterByAppend, []int{0, 1, 0, 0, 2, 3, 4, 0, 5, 0}, []int{1, 2, 3, 4, 5}},
  49. {"filter by swap", filterBySwap, []int{0, 1, 0, 0, 2, 3, 4, 0, 5, 0}, []int{1, 2, 3, 4, 5}},
  50. {"filter by sort", filterBySort, []int{0, 1, 0, 0, 2, 3, 4, 0, 5, 0}, []int{1, 2, 3, 4, 5}},
  51. }
  52. for _, test := range tests {
  53. tc := test
  54. t.Run(test.name, func(t *testing.T) {
  55. tc.input = tc.algorithm(tc.input)
  56. if !reflect.DeepEqual(tc.input, tc.expected) {
  57. t.Errorf("expected %+v, obtained %+v", tc.expected, tc.input)
  58. }
  59. })
  60. }
  61. }
  62.  
  63. // goos: darwin
  64. // goarch: amd64
  65. // BenchmarkFilter/filter_by_append-4 50000000 20.9 ns/op 0 B/op 0 allocs/op
  66. // BenchmarkFilter/filter_by_swap-4 100000000 20.5 ns/op 0 B/op 0 allocs/op
  67. // BenchmarkFilter/filter_by_sort-4 10000000 185 ns/op 32 B/op 1 allocs/op
  68. func BenchmarkFilter(b *testing.B) {
  69. benchmarks := []struct {
  70. name string
  71. algorithm func([]int) []int
  72. input []int
  73. }{
  74. {"filter by append", filterByAppend, []int{0, 1, 0, 0, 2, 3, 4, 0, 5, 0}},
  75. {"filter by swap", filterBySwap, []int{0, 1, 0, 0, 2, 3, 4, 0, 5, 0}},
  76. {"filter by sort", filterBySort, []int{0, 1, 0, 0, 2, 3, 4, 0, 5, 0}},
  77. }
  78. for _, bm := range benchmarks {
  79. tc := bm
  80. b.Run(bm.name, func(b *testing.B) {
  81. copied := make([]int, len(tc.input))
  82. b.ReportAllocs()
  83. b.ResetTimer()
  84. for i := 0; i < b.N; i++ {
  85. copy(copied, tc.input)
  86. _ = tc.algorithm(tc.input)
  87. }
  88. })
  89. }
  90. }
Add Comment
Please, Sign In to add comment