Sobes.tech
Middle+

Write a function that removes all elements equal to val from a slice in-place. Returns a slice without the removed values. func RemoveValue(slice []int, val int) []int { // your code } // Example RemoveValue([]int{1,2,3,2,4}, 2) // -> []int{1,3,4} RemoveValue([]int{1,2,3}, 5) // -> []int{1,2,3} RemoveValue([]int{}, 1) // -> []int{}

sobes.tech AI

Answer from AI

The function removes all elements equal to val from the slice, modifying it in place, and returns a new slice without these elements. To do this, two indices can be used: one for reading and one for writing.

func RemoveValue(slice []int, val int) []int {
    j := 0
    for _, v := range slice {
        if v != val {
            slice[j] = v
            j++
        }
    }
    return slice[:j]
}

Example:

fmt.Println(RemoveValue([]int{1,2,3,2,4}, 2)) // [1 3 4]
fmt.Println(RemoveValue([]int{1,2,3}, 5))     // [1 2 3]
fmt.Println(RemoveValue([]int{}, 1))          // []
Write a function that removes all elements equal to… - sobes.tech