Can't modify a matrix in a function - go

I have an array of matrices and I try to mutate each matrix in case an if statement is true.
for example, if I have this matrix:
1 2 3
4 5 6
7 8 9
I want to change each odd number to 0.
This is what I have:
func main() {
matrices := createMatrix() <-- returns an array of matrices.
for _, matrix := range matrices {
removeOdds(matrix)
}
}
func removeOdds(mat [][]int) {
for i := 0; i < len(mat); i++ {
for j := 0; j < len(mat[i]); j++ {
if mat[i][j] % 2 != 0 {
mat[i][j] = 0
}
}
}
}
This is not working because the matrix is not being changed.
I read that Go pass array by value and not reference, so I tried using pointers. But still, when I print the matrix after the changes of removeOdds, I get the original one.
This is what I wrote:
func main() {
matrices := createMatrix() <-- returns an array of matrices.
for _, matrix := range matrices {
removeOdds(&matrix)
}
}
func removeOdds(mat *[][]int) {
for i := 0; i < len(*mat); i++ {
for j := 0; j < len((*mat)[i]); j++ {
if (*mat)[i][j] % 2 != 0 {
(*mat)[i][j] = 0
}
}
}
}

As far as I concerned, the code snippet looks completely ok.
To be clear, type []int is not an array, it's a slice. Array is a fix length block of data, and type signature of array should be like [3]int. Slice is a reference type, a variable length view onto the real data, means it does not own the data, it only record where to find the data in memory in its value.
When you pass a slice into function, that reference value is copied, even inside the function, you are still referencing the same data block, or you can say the underlaying array, as you are when out side function scope.
How ever, I've tried your code my self, and I wrote this:
type Mat = [][]int
func makeMat() Mat {
return [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
}
func main() {
mats := []Mat{}
for i := 0; i < 10; i++ {
mats = append(mats, makeMat())
}
for _, mat := range mats {
// no change was made to this function
removeOdds(mat)
}
for _, mat := range mats {
fmt.Println(mat)
}
}
output:
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
[[0 2 0] [4 0 6] [0 8 0]]
So I think there may be some mistake in your observation. Maybe provide more information about your createMatrix().

Your first approach is true except iterating over matrices.
You should use
for i := range matrices {
removeOdds(matrix[i])
}
instead of
for _, matrix := range matrices {
removeOdds(matrix)
}
https://go.dev/play/p/iE0uCE_6Z2v

Related

Error when using pointers to append into slice [][]int

While I was trying to solve a problem "Subset II" from LC, I came across a strange problem. The code generates a power set from a given set.
However, when I run the code it failed because one of the set wasn't correct.
The set [0,3,5,7] replaced by [0,3,5,9] (hence gets appended twice).
I have a print statement (highlighted in code) right before a set gets appended to res, and it prints the correct power set.
The only issue I could think is the use of pointers to append values into a slice, however since it's does not run concurrently I don't see why there would be a race condition.
Appreciate if someone can point out my mistake.
package main
import (
"fmt"
"sort"
)
func ValueCount( nums []int) map[int]int{
hm := make(map[int]int)
for _,v := range(nums){
if c, ok := hm[v]; ok {
hm[v] = c + 1
}else{
hm[v] = 1
}
}
return hm
}
func subsetsWithDup(nums []int) [][]int {
var res [][]int
res = append(res,[]int{})
sort.Ints(nums)
hashMap := ValueCount(nums)
var t []int
printTest(nums, t, &res, hashMap)
return res
}
func printTest(nums []int, t []int, res *[][]int, hm map[int]int) {
if len(nums) == 0 {
return
}
for i:= 0; i < len(nums); {
v := nums[i]
x := nums[i:]
for k:= 0; k< hm[v]; k++ {
var a,b []int
for z:= 0; z<k+1; z++ {
a = append(t,x[z])
}
fmt.Println(a) // <--------- Prints the values that gets appended to res
*res = append(*res, a)
b = a
printTest(nums[i+hm[v]:], b, res, hm)
}
i += hm[v]
}
}
func main(){
n := []int{9,0,3,5,7}
fmt.Println("Find the power set of:", n)
fmt.Println(subsetsWithDup(n))
}
// [0,3,5,7] changes to
// [0,3,5,9] in the output
The bug occurs on line 40:
a = append(t, x[z])
A quick fix would be to change this for loop:
for k := 0; k < hm[v]; k++ {
var a, b []int
for z := 0; z < k+1; z++ {
a = append(t, x[z])
}
fmt.Println(a) // <--------- Prints the values that gets appended to res
*res = append(*res, a)
b = a
printTest(nums[i+hm[v]:], b, res, hm)
}
To this:
for k := 0; k < hm[v]; k++ {
var a, b []int
a = make([]int, len(t))
copy(a, t)
for z := 0; z < k+1; z++ {
a = append(a, x[z])
}
fmt.Println(a) // <--------- Prints the values that gets appended to res
*res = append(*res, a)
b = a
printTest(nums[i+hm[v]:], b, res, hm)
}
It has to do with how Go uses slices as a data structure. When the first argument to the built-in append function was a slice argument, it copied some of the slice's internal data that wasn't intuitive to the programmer. It then modified the argument slice, t, and the newly created slice, a.
I'd recommend reading up on slice internals if you're interested in learning more.
Full program edited:
package main
import (
"fmt"
"sort"
)
func ValueCount(nums []int) map[int]int {
hm := make(map[int]int)
for _, v := range nums {
if c, ok := hm[v]; ok {
hm[v] = c + 1
} else {
hm[v] = 1
}
}
return hm
}
func subsetsWithDup(nums []int) [][]int {
var res [][]int
res = append(res, []int{})
sort.Ints(nums)
hashMap := ValueCount(nums)
var t []int
printTest(nums, t, &res, hashMap)
return res
}
func printTest(nums []int, t []int, res *[][]int, hm map[int]int) {
if len(nums) == 0 {
return
}
for i := 0; i < len(nums); {
v := nums[i]
x := nums[i:]
for k := 0; k < hm[v]; k++ {
var a, b []int
a = make([]int, len(t))
copy(a, t)
for z := 0; z < k+1; z++ {
a = append(a, x[z])
}
fmt.Println(a) // <--------- Prints the values that gets appended to res
*res = append(*res, a)
b = a
printTest(nums[i+hm[v]:], b, res, hm)
}
i += hm[v]
}
}
func main() {
n := []int{9, 0, 3, 5, 7}
fmt.Println("Find the power set of:", n)
fmt.Println(subsetsWithDup(n))
}
New output:
Find the power set of: [9 0 3 5 7]
[0]
[0 3]
[0 3 5]
[0 3 5 7]
[0 3 5 7 9]
[0 3 5 9]
[0 3 7]
[0 3 7 9]
[0 3 9]
[0 5]
[0 5 7]
[0 5 7 9]
[0 5 9]
[0 7]
[0 7 9]
[0 9]
[3]
[3 5]
[3 5 7]
[3 5 7 9]
[3 5 9]
[3 7]
[3 7 9]
[3 9]
[5]
[5 7]
[5 7 9]
[5 9]
[7]
[7 9]
[9]
[[] [0] [0 3] [0 3 5] [0 3 5 7] [0 3 5 7 9] [0 3 5 9] [0 3 7] [0 3 7 9] [0 3 9] [0 5] [0 5 7] [0 5 7 9] [0 5 9] [0 7] [0 7 9] [0 9] [3] [3 5] [3 5 7] [3 5 7 9] [3 5 9] [3 7] [3 7 9] [3 9] [5] [5 7] [5 7 9] [5 9] [7] [7 9] [9]]
Be very careful using (and reusing) slice results - especially when altering those slice values later. Since slices have backing arrays, the referenced data can change in very unexpected ways!
A quick fix to your problem is to copy slice results to a new slice. This ensures changes to the original slice do not introduce bugs (especially in a recursive algorithm).
To copy a slice:
func copyIntSlice(a []int) []int {
c := make([]int, len(a))
copy(c, a) // `a` can now grow/shrink/change without affecting `c`
return c
}
and just call this from your main code:
aCopy := copyIntSlice(a)
*res = append(*res, aCopy)
printTest(nums[i+hm[v]:], aCopy, res, hm)
https://play.golang.org/p/1p8Z4sV9foQ

Golang: Appending keys from a map to a slice of slices

I ran into this simple Golang code and was surprised by Go's behavior here. Can someone explain what is going on here, and how to write the below code correctly?
As you can see, I have a map, where the key is an array of int. I add a couple of values and then I loop through the map, convert each key to a slice and append each key to an object of type [][]int.
func test() {
myMap := make(map[[3]int]bool)
myMap[[3]int{1, 2, 3}] = true
myMap[[3]int{0, 5, 4}] = true
myMap[[3]int{9, 7, 1}] = true
myMap[[3]int{0, 2, 8}] = true
array := [][]int{}
for val := range myMap {
array = append(array, val[:])
}
fmt.Println(array)
}
I was expecting the last line to print [[1,2,3], [0,5,4], [9,7,1], [0,2,8]], however, to my surprise it prints [[0 2 8] [0 2 8] [0 2 8] [0 2 8]], or [[9 7 1] [9 7 1] [9 7 1] [9 7 1]], or some other variation containing only one of the keys multiple times.
My go version is 1.16.5
In a for-loop, the loop variables are overwriten at every iteration. That is, the val is an array, and for each iteration, the contents of val are overwritten with the next item in the map. Since you added slices (which are simply views over an array), all the slices have val as the backing array, and they all have the same contents, namely, whatever the last element iterated.
To fix, copy the array:
for val := range myMap {
val:=val
array = append(array, val[:])
}
You're appending the loop iterator variable each time, which is updated each iteration. You need to append a locally-scoped copy instead:
for val := range myMap {
v := val
array = append(array, v[:])
}
Based on suggestion of Adrian, recreating your code with a simple program as follows:
package main
import (
"fmt"
)
func main() {
test()
}
func test() {
myMap := make(map[[3]int]bool)
myMap[[3]int{1, 2, 3}] = true
myMap[[3]int{0, 5, 4}] = true
myMap[[3]int{9, 7, 1}] = true
myMap[[3]int{0, 2, 8}] = true
array := [][]int{}
for val := range myMap {
key := val
array = append(array, key[:])
}
fmt.Println(array)
}
Output:
[[1 2 3] [0 5 4] [9 7 1] [0 2 8]]

Unexpected behavior when passing a pointer to a slice in go

The following go program is supposed to generate all permutations of a slice of integers:
package main
import "fmt"
func permute(nums []int) [][]int {
var res [][]int
var s []int
permuteHlp(&res, nums, 0, s)
return res
}
func permuteHlp(res *[][]int, nums []int, i int, s []int) {
if i == len(nums) {
*res = append(*res, s)
return
}
for j := i; j < len(nums); j++ {
s = append(s, nums[j])
nums[i], nums[j] = nums[j], nums[i]
permuteHlp(res, nums, i+1, s)
s = s[:len(s)-1]
nums[i], nums[j] = nums[j], nums[i]
}
}
func main() {
x := []int{1,2,3,4}
y := permute(x)
fmt.Println(y)
}
The output is unexpected
[[1 2 4 3] [1 2 4 3] [1 3 4 2] [1 3 4 2] [1 4 2 3] [1 4 2 3] [2 1 4 3] [2 1 4 3] [2 3 4 1] [2 3 4 1] [2 4 1 3] [2 4 1 3] [3 2 4 1] [3 2 4 1] [3 1 4 2] [3 1 4 2] [3 4 2 1] [3 4 2 1] [4 2 1 3] [4 2 1 3] [4 3 1 2] [4 3 1 2] [4 1 2 3] [4 1 2 3]]
I don't understand what is wrong here. I would appreciate any help.
Thank you!
You're passing around a pointer to the the same slice. In the end you wind up with a bunch of pointers to the same slice in your results, so of course all the values will be identical - it's the same slice printed over and over.
It's also worth noting that a pointer to a slice is rarely what you want, as slices already contain a pointer to the underlying array.
There's no need for a pointer to the slice since slices are pointers themselves. "a slice is a reference to a contiguous segment of an array.", reference.
The strange behavior you're seeing is because you're using append, when a slice grows beyond its capacity it's required to create a new slice with increased capacity and copy all the contents of the original one (this is what append does behind the scenes), hence new slice is no longer pointing to the original underlying array.
Instead of modifying the incoming parameter, I suggest returning the slice as a return value for the function.
func permute(nums []int) [][]int {
res := permuteHlp(nums, 0, new([]int))
return res
}
I recommend you read the blog post in golang.org about slices internals, here
Edit:
I add a refactor, taking the algorithm from this answer.
package main
import (
"fmt"
)
func permutations(arr []int)[][]int{
var helper func([]int, int)
res := [][]int{}
helper = func(arr []int, n int){
if n == 1{
tmp := make([]int, len(arr))
copy(tmp, arr)
res = append(res, tmp)
} else {
for i := 0; i < n; i++{
helper(arr, n - 1)
if n % 2 == 1{
tmp := arr[i]
arr[i] = arr[n - 1]
arr[n - 1] = tmp
} else {
tmp := arr[0]
arr[0] = arr[n - 1]
arr[n - 1] = tmp
}
}
}
}
helper(arr, len(arr))
return res
}
func main() {
x := []int{1,2,3,4}
d := permutations(x)
fmt.Print(d)
}
Generally you won't want to have a pointer to a slice, instead, return a new one from the function, another thing to comment on, try not to use recursion if possible as golang doesn't have tail call optimization, and its loops perform amazingly. Hope it helps!

Working with maps in Golang

I am new to Go and doing a few exercises. One of them is to sort the numbers in an array by frequency, from most to least frequent.
Example:
Input: [2, 2, 5, 7, 4, 4, 4, 7, 2]
Output: [2, 4, 7, 5]
Note that [4, 2, 7, 5] would also be correct, since 4 and 2 have the same frequency.
For this purpose I am converting the array into a value value map, which here would look like this: [2:3][4:3][7:2][5:1] (2 and 3 have freq. of 3, 7 has the freq of 2,... )
Afterwards I would like to simply loop through the map and output the keys ordered by value. For that I use the following code, which apparently does not work. Why?
count := 0
max := -1
// break loop, if map is empty
for i := 0; i < 1; i-- {
if len(m) == 0 {
break
}
max = -1
// get key of biggest value
for k, v := range m {
if v > max {
max = k
}
}
// res (for result) is a slice of integers
res[count] = max
// remove key-value-pair from map
delete(m, max)
count++
}
return res
Please keep in mind that this is an exercise. I am very sure there are much better, build in ways to do this.
Your 'max' variable is meant to keep track of the maximum frequency seen so far. However when you do 'max = k' you're assigning a key.
You need to keep track of the maximum frequency and the key associated with that frequency in separate variables.
...
for k, v := range m {
if v > maxFreq {
maxFreq = v
mostFrequentKey = k
}
}
// res (for result) is a slice of integers
res[count] = mostFrequentKey
// remove key-value-pair from map
delete(m, mostFrequentKey)
count++
...
For sorted frequencies, use a map then a slice. For example,
package main
import (
"fmt"
"sort"
)
func main() {
Input := []int{2, 2, 5, 7, 4, 4, 4, 7, 2}
fmt.Println("Input: ", Input)
mFreq := make(map[int]int, len(Input))
for _, n := range Input {
mFreq[n]++
}
sFreq := make([][2]int, 0, len(mFreq))
for n, f := range mFreq {
sFreq = append(sFreq, [2]int{n, f})
}
sort.Slice(sFreq, func(i, j int) bool {
if sFreq[i][1] <= sFreq[j][1] {
if sFreq[i][1] < sFreq[j][1] {
return false
}
if sFreq[i][0] >= sFreq[j][0] {
return false
}
}
return true
},
)
Output := []int{2, 4, 7, 5}
fmt.Println("Output: ", Output)
fmt.Println("Frequencies:", sFreq)
}
Playground: https://play.golang.org/p/8tiSksz3S76
Output:
Input: [2 2 5 7 4 4 4 7 2]
Output: [2 4 7 5]
Frequencies: [[2 3] [4 3] [7 2] [5 1]]

Get all permutations of a slice

I was wondering if there was a way to find all the permutations of an slice filled with characters in Go?
In Python you can use itertools.product with a list or characters or integers, and you can get all the possible permutations.
I have looked to see if there is a package out there, and I cannot seem to find one. Any help would be welcomed.
Permutations of anything implementing sort.Interface: Permutation{First,Next}
Here is a implementation of a permutation function i've written...
https://github.com/itcraftsman/GoPermutation
func permutate(slice [][]int) (permutations [][][]int){
f := fac(len(slice))
for i := 0; i < len(slice); i++ {
elem, s := splice(slice, i)
pos := 0
for count := 0; count < (f / len(slice)); count++{
if pos == (len(s) -1) {
pos = 0
}
s = swap(s, pos, pos +1)
permutation := make([][]int, len(slice))
permutation = s
permutation = append(permutation, elem)
permutations = append(permutations, permutation)
pos++
}
}
return
}
it takes a 2D slice as input and returns a 3D slice, but you can easily change the code so that the function will take a simple slice as input and return a 2D slice with all permutations
Not really sure if this answers your question but this is a simple recursive implementation to find the output below.
package main
import "fmt"
func main() {
values := [][]int{}
// These are the first two rows.
row1 := []int{1, 2, 3}
row2 := []int{4, 5, 6}
row3 := []int{7, 8, 9}
// Append each row to the two-dimensional slice.
values = append(values, row1)
values = append(values, row2)
values = append(values, row3)
fmt.Println(getPermutation(values))
}
func getPermutation(vids [][]int) [][]int {
toRet := [][]int{}
if len(vids) == 0 {
return toRet
}
if len(vids) == 1 {
for _, vid := range vids[0] {
toRet = append(toRet, []int{vid})
}
return toRet
}
t := getPermutation(vids[1:])
for _, vid := range vids[0] {
for _, perm := range t {
toRetAdd := append([]int{vid}, perm...)
toRet = append(toRet, toRetAdd)
}
}
return toRet
}
https://play.golang.org/p/f8wktrxkU0
Output of above snippet:
[[1 4 7] [1 4 8] [1 4 9] [1 5 7] [1 5 8] [1 5 9] [1 6 7] [1 6 8] [1 6 9] [2 4 7] [2 4 8] [2 4 9] [2 5 7] [2 5 8] [2 5 9] [2 6 7] [2 6 8] [2 6 9] [3 4 7] [3 4 8] [3 4 9] [3 5 7] [3 5 8] [3 5 9] [3 6 7] [3 6 8] [3 6 9]]

Resources