luoshao23
luoshao23

Reputation: 431

how to swap values by index in Golang

In python's numpy, one can swap values by index within a list easily like this:

a[[2, 3, 5]] = a[[5, 2, 3]]

Is there a good way to implement this function in Golang.

Upvotes: 0

Views: 2156

Answers (3)

Shubham Srivastava
Shubham Srivastava

Reputation: 1877

If you want something similar to that you can over engineer some solution, but will create a lot of problem and handling

To give you an idea about what I mean see this Go PlayGround Go passes Slices as reference so making a function to swap in place and you get something like this

package main

import (
    "errors"
    "fmt"
    "strings"
    "strconv"
)

func main() {
    a := []int{1, 2, 3, 4, 5, 6}
    err := swap(a, "1,3,5=>0,2,4")
    fmt.Println(a, err)
}

func swap(arr []int, str string) error {
    parts := strings.Split(str, "=>")
    if len(parts) != 2 {
        return errors.New("Invalid Input")
    }

    leftIndices := strings.Split(parts[0], ",")
    rightIndices := strings.Split(parts[1], ",")

    if len(leftIndices) != len(rightIndices) {
        return errors.New("Swap Indices not Balanced")
    }
    
    fmt.Println(leftIndices, rightIndices)

    for i := 0; i < len(leftIndices); i++ {
        i1, _:= strconv.Atoi(leftIndices[i])
        i2, _:= strconv.Atoi(rightIndices[i])

        arr[i1], arr[i2] = arr[i2], arr[i1]
        fmt.Println(arr)
    }
    return nil
}

Even for this i need to handle so many cases (While still some remain not handled), making some thing generic will require even more checks and complexity

It will be way easier to use the builtin syntax like

a[0], a[1], a[2] = a[3], a[4], a[5]

Upvotes: 0

Volker
Volker

Reputation: 42422

Is there a good way to implement this function in Go[...][? emph mine]

No. Go doesn't provide syntax for this. Note that inplace permutation is a hard problem (and probably numpy doesn't do this under the hood either).

Copy and permute.

Upvotes: 1

hobbs
hobbs

Reputation: 240049

Go doesn't have fancy indexing like that; the closest you can do is

a[2],a[3],a[5] = a[5],a[2],a[3]

using regular indexing and regular tuple assignment.

Upvotes: 6

Related Questions