Sean_J
Sean_J

Reputation: 55

Can't swap elements of 2D array slice using Golang

I am trying to write a simple function that transposes a square matrix (i.e. swaps the columns and rows). Here is the function in question:

func Transpose(a [][]bool) {
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(a[i]); j++ {
            a[i][j], a[j][i] = a[j][i], a[i][j]
        }
    }
}

It doesn't seem to work. If I run this function

func TestTranspose(t *testing.T) {
    a := make([][]bool, 3)
    a[0] = []bool{true, true, true}
    a[1] = []bool{false, true, false}
    a[2] = []bool{true, true, true}

    fmt.Println(BoolArrayViz(a))

    Transpose(a)

    fmt.Println(BoolArrayViz(a))
}

It gives the following output (BoolArrayViz simply prints the bool as '*' if true ' ' if false):

***
 * 
***

***
 * 
***

I believe it has something to do with pointers and the fact that I'm passing around slices. Any help is appreciated!

Upvotes: 1

Views: 1828

Answers (2)

user6169399
user6169399

Reputation:

Your Transpose logic is not correct (you transposed it twice),
See this working test sample (not using swap to demonstrate the idea):

package main

import "fmt"

func Transpose(a [][]bool) {
    n := len(a)
    b := make([][]bool, n)
    for i := 0; i < n; i++ {
        b[i] = make([]bool, n)
        for j := 0; j < n; j++ {
            b[i][j] = a[j][i]
        }
    }
    copy(a, b)
}
func main() {
    a := [][]bool{
        []bool{true, true, true},
        []bool{false, true, false},
        []bool{true, true, true},
    }
    BoolArrayViz(a)
    Transpose(a)
    BoolArrayViz(a)
}

func BoolArrayViz(a [][]bool) {
    n := len(a)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            if a[i][j] {
                fmt.Printf("*")
            } else {
                fmt.Printf(" ")
            }
        }
        fmt.Println()
    }
    fmt.Println()
}

output:

***
 * 
***

* *
***
* *

using swap (the inner loop, j should start at i+1 instead of 0):

package main

import "fmt"

func Transpose(a [][]bool) {
    n := len(a)
    for i := 0; i < n; i++ {
        for j := i + 1; j < n; j++ {
            a[i][j], a[j][i] = a[j][i], a[i][j]
        }
    }
}
func main() {
    a := [][]bool{
        []bool{true, true, true},
        []bool{false, true, false},
        []bool{true, true, true},
    }
    BoolArrayViz(a)
    Transpose(a)
    BoolArrayViz(a)
}

func BoolArrayViz(a [][]bool) {
    n := len(a)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            if a[i][j] {
                fmt.Printf("*")
            } else {
                fmt.Printf(" ")
            }
        }
        fmt.Println()
    }
    fmt.Println()
}

Upvotes: 2

Andy Schweig
Andy Schweig

Reputation: 6739

You transpose function is wrong. The way it is, you're transposing the matrix and then transposing it back. In the inner loop, j should start at i + 1 instead of 0.

Upvotes: 1

Related Questions