Skip to content

Commit

Permalink
refactor exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
sgmdlt committed Sep 3, 2024
1 parent 1633ff2 commit af7d3c9
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 22 deletions.
7 changes: 6 additions & 1 deletion modules/20-array-slice-map/15-slice/ru/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
Реализуйте функцию Reverse(slice []int) []int, которая принимает слайс целых чисел и возвращает новый слайс с элементами в обратном порядке.

В Go нет встроенной функции удаления элемента из слайса. Реализуйте функцию `Remove(nums []int, i int) []int`, которая удаляет элемент по индексу `i` из слайса `nums`. Если приходит несуществующий индекс, то из функции возвращается исходный слайс. Порядок элементов может быть нарушен после удаления элемента.
```go
original := []int{1, 2, 3, 4, 5}
Reverse(original) // [5 4 3 2 1]
Reverse([]int{}) // []
```
13 changes: 6 additions & 7 deletions modules/20-array-slice-map/15-slice/solution.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ package solution

// BEGIN

// Remove removes an item from the nums slice by index i.
func Remove(nums []int, i int) []int {
if i < 0 || i > len(nums)-1 {
return nums
}
func Reverse(slice []int) []int {
reversed := make([]int, len(slice))

nums[i] = nums[len(nums)-1]
for i := len(slice) - 1; i >= 0; i-- {
reversed[len(slice)-1-i] = slice[i]
}

return nums[:len(nums)-1]
return reversed
}

// END
19 changes: 5 additions & 14 deletions modules/20-array-slice-map/15-slice/solution_test.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
package solution

import (
"sort"
"testing"

"github.com/stretchr/testify/assert"
)

func TestRemove(t *testing.T) {
func TestReverse(t *testing.T) {
a := assert.New(t)
equalSlices(a, []int{1, 2}, Remove([]int{1, 2}, -1))
equalSlices(a, []int{1, 2}, Remove([]int{1, 2}, -5))
equalSlices(a, []int{2, 3}, Remove([]int{1, 2, 3}, 0))
equalSlices(a, []int{1, 2}, Remove([]int{1, 2, 3}, 2))
equalSlices(a, []int{1, 2, 3}, Remove([]int{1, 2, 3}, 3))
equalSlices(a, []int{1, 2, 3}, Remove([]int{1, 2, 3}, 5))
}

func equalSlices(a *assert.Assertions, expected, actual []int) {
sort.Ints(expected)
sort.Ints(actual)
a.Equal(expected, actual)
a.Equal([]int{4, 3, 2, 1}, Reverse([]int{1, 2, 3, 4}))
a.Equal([]int{}, Reverse([]int{}))
a.Equal([]int{-1, -2, -3, -4}, Reverse([]int{-4, -3, -2, -1}))
a.Equal([]int{3}, Reverse([]int{3}))
}

0 comments on commit af7d3c9

Please sign in to comment.