Unexpected behaviour when populating a map using recursion [duplicate] - go

This question already has answers here:
Slice getting updated magically
(1 answer)
Problem accumulating/appending values in an array using recursion with Go
(2 answers)
Pass slice as function argument, and modify the original slice
(4 answers)
Recursively append to slice not working
(2 answers)
appending to slice of slices recursively
(2 answers)
Closed 1 year ago.
The goal is to compute all possible slices of length k that can be formed from a set of n strings.
I tried to do it using a simple recursion. Just printing the result works fine. Putting the results in a map yields some unexpected results for odd k's greater than 2.
What causes differences between the map's keys and their corresponding values?
https://play.golang.org/p/_SGrPRFjJ5g
package main
import (
"fmt"
"strings"
)
func main() {
QQM := make(map[string][]string)
states := []string{
"a",
"b",
}
var perm func(Q []string, k int)
perm = func(Q []string, k int) {
if k == 0 {
QQM[strings.Join(Q, "")] = Q
fmt.Println(QQM)
return
}
for i := 0; i < len(states); i++ {
perm(append(Q, states[i]), k-1)
}
}
perm([]string{}, 4)
}
map[aaaa:[a a a a]]
map[aaaa:[a a a b] aaab:[a a a b]]
map[aaaa:[a a a b] aaab:[a a a b] aaba:[a a b a]]
...

A slice is a view of an underlying array. When you pass slices around, you are not passing the values they contain, but references to those values. So when you put a slice to a map then add elements to that slice, if the slice has the capacity, you would be adding elements to the slice in the map as well.
Copy the slice before putting into the map:
newQ:=make([]string,len(Q))
copy(newQ,Q)
QQM[strings.Join(Q, "")] = newQ

Related

Problem creating superset from list of integers [duplicate]

This question already has answers here:
Slice within a loop seems to retain the previous/last reference (depending on the length of slice)
(2 answers)
unexpected slice append behaviour
(3 answers)
Bug in HouseRobber Programming Task in GoLang
(1 answer)
How to append to a 2d slice
(3 answers)
Closed 11 days ago.
I was defining a function that returns all the subsets (power set) of a list of integers.
Example: [1,2,3] -> [[], [1], [2], [3], [1,2], [2,3], [1,3], [1,2,3]]
The code I wrote is as follows :-
func subsets(nums []int) [][]int {
out := make([][]int, 0)
out = append(out, []int{})
for _, num := range nums {
n := len(out)
for i:=0; i<n; i++ {
out = append(out, append(out[i], num))
}
}
return out
}
Which adds the next number in the list to all the previous subsets.
Output when input = [9,0,3,5,7]
Upto input length <= 4, the function runs fine. But when it is more than that, some weird behaviour occurs, like the out should be appended [9,0,3,5] but it appends [9,0,3,7] (input list [9,0,3,5,7])
What could be the reason behind this peculiar behaviour?

Get all combinations of a slice until a certain length

I am using the go combinations package to find all the combinations of a list of ints. The package out of the box is for strings but I've edited to do []int instead.
func All(set []int) (subsets [][]int) {
length := uint(len(set))
// Go through all possible combinations of objects
// from 1 (only first object in subset) to 2^length (all objects in subset)
for subsetBits := 1; subsetBits < (1 << length); subsetBits++ {
var subset []int
for object := uint(0); object < length; object++ {
// checks if object is contained in subset
// by checking if bit 'object' is set in subsetBits
if (subsetBits>>object)&1 == 1 {
// add object to subset
subset = append(subset, set[object])
}
}
// add subset to subsets
subsets = append(subsets, subset)
}
return subsets
}
This works for me, however, only when given a small slice. once the slice gets large the combinations become exponential and tolling to calculate.
Luckily I know when I need to stop. Before running the combinations I have determined the max length of the combinations.
s := []int{2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4}
limit := 2
The above would generate an exorbent amount of combinations, majority I will not need, as I can define the limit to the length of combinations I'd need as a maximum.
// Ideal output
[[2] [2] [2] [2] ...... [2 3] [2 4]] // Stop once we hit length of 3 as limit was set to 2
I can't really figure out how to implement a limit break or return once the combinations reach a certain length.
Example:
func All(set []int, limit int) (subsets [][]int) {
// ... previous code here
if len(combinations) > limit {
return output
}
}

Trying to initialize 2D slice, but the element reference changes all the rows in the slice [duplicate]

This question already has answers here:
What is a concise way to create a 2D slice in Go?
(4 answers)
Closed 2 years ago.
I created a 2D slice using the below code. Say I created [3]3] slice -- [[1 2 3],[4 5 6][7 8 9]]
But if I update the slice say s[1][1]=99 all changes --> [1 99 3], [4 99 6], [7 99 9]]
However, the second slice I have initialized below with variable cost does behave correctly. Not sure what is wrong:
func CreateSparseM() *SparseM{
var m,n,nz int
fmt.Println("Enter the row count of matrix ")
fmt.Scan(&m)
fmt.Println("Enter the column count of matrix ")
fmt.Scan(&n)
fmt.Println("Enter the count of Non Zero elements in the matrix ")
fmt.Scan(&nz)
r:=make([][]int,m)
c:=make([]int,n)
for i:=0;i<m;i++{
r[i] = c
}
fmt.Println(" r ", r)
r[1][1] = 99
fmt.Println(r[1][1])
fmt.Println(r[0][1])
//enter the non-zero elements
var row,col,elem int
for i:=0;i<nz;i++{
fmt.Println("Enter row ")
fmt.Scan(&row)
fmt.Println("Enter col ")
fmt.Scan(&col)
fmt.Println("Enter element ")
fmt.Scan(&elem)
r[row][col] = elem
}
fmt.Println(r)
cost:= [][]int{ {1,1,2,2,3,4,4,5,5},
{2,6,3,7,4,5,7,6,7},
{25,5,12,10,8,16,14,20,18}}
fmt.Println(cost)
cost[1][2]= 777
fmt.Println(cost)
sparseM := &SparseM{m,n,nz,r}
return sparseM
}
A slice contains a reference to an array, the capacity, and the length of the slice. So the following code:
r:=make([][]int,m)
c:=make([]int,n)
for i:=0;i<m;i++{
r[i] = c
}
sets all of r[i] to the same slice c. That is, all r[i] share the same backing array. So if you set r[i][j]=x, you set j'th element of all slices r[i] to x.
The slice you initialized using a literal has three distinct slices, so it does not behave like this.
If you do:
for i:=0;i<m;i++{
r[i] = make([]int,n)
}
then you'll have distinct slices for the first case as well.

cap vs len of slice in golang

What is the difference between cap and len of a slice in golang?
According to definition:
A slice has both a length and a capacity.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
x := make([]int, 0, 5) // len(b)=0, cap(b)=5
Does the len mean non null values only?
A slice is an abstraction that uses an array under the covers.
cap tells you the capacity of the underlying array. len tells you how many items are in the array.
The slice abstraction in Go is very nice since it will resize the underlying array for you, plus in Go arrays cannot be resized so slices are almost always used instead.
Example:
s := make([]int, 0, 3)
for i := 0; i < 5; i++ {
s = append(s, i)
fmt.Printf("cap %v, len %v, %p\n", cap(s), len(s), s)
}
Will output something like this:
cap 3, len 1, 0x1040e130
cap 3, len 2, 0x1040e130
cap 3, len 3, 0x1040e130
cap 6, len 4, 0x10432220
cap 6, len 5, 0x10432220
As you can see once the capacity is met, append will return a new slice with a larger capacity. On the 4th iteration you will notice a larger capacity and a new pointer address.
Play example
I realize you did not ask about arrays and append but they are pretty foundational in understanding the slice and the reason for the builtins.
From the source code:
// The len built-in function returns the length of v, according to its type:
// Array: the number of elements in v.
// Pointer to array: the number of elements in *v (even if v is nil).
// Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
// String: the number of bytes in v.
// Channel: the number of elements queued (unread) in the channel buffer;
// if v is nil, len(v) is zero.
func len(v Type) int
// The cap built-in function returns the capacity of v, according to its type:
// Array: the number of elements in v (same as len(v)).
// Pointer to array: the number of elements in *v (same as len(v)).
// Slice: the maximum length the slice can reach when resliced;
// if v is nil, cap(v) is zero.
// Channel: the channel buffer capacity, in units of elements;
// if v is nil, cap(v) is zero.
func cap(v Type) int
Simple explanation
Slice are self growing form of array so there are two main properties.
Length is total no of elements() the slice is having and can be used for looping through the elements we stored in slice. Also when we print the slice all elements till length gets printed.
Capacity is total no elements in underlying array, when you append more elements the length increases till capacity. After that any further append to slice causes the capacity to increase automatically(apprx double) and length by no of elements appended.
The real magic happens when you slice out sub slices from a slice where all the actual read/write happens on the underlaying array. So any change in sub slice will also change data both in original slice and underlying array. Where as any sub slices can have their own length and capacity.
Go through the below program carefully. Its modified version of golang tour example
package main
import "fmt"
func main() {
sorig := []int{2, 3, 5, 7, 11, 13}
printSlice(sorig)
// Slice the slice to give it zero length.
s := sorig[:0]
printSlice(s)
// Extend its length.
s = s[:4]
s[2] = 555
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
printSlice(sorig)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
//Output
//len=6 cap=6 [2 3 5 7 11 13]
//len=0 cap=6 []
//len=4 cap=6 [2 3 555 7]
//len=2 cap=4 [555 7]
//len=6 cap=6 [2 3 555 7 11 13]

Checking the equality of two slices

How can I check if two slices are equal, given that the operators == and != are not an option?
package main
import "fmt"
func main() {
s1 := []int{1, 2}
s2 := []int{1, 2}
fmt.Println(s1 == s2)
}
This does not compile with:
invalid operation: s1 == s2 (slice can only be compared to nil)
You should use reflect.DeepEqual()
DeepEqual is a recursive relaxation of Go's == operator.
DeepEqual reports whether x and y are “deeply equal,” defined as
follows. Two values of identical type are deeply equal if one of the
following cases applies. Values of distinct types are never deeply
equal.
Array values are deeply equal when their corresponding elements are
deeply equal.
Struct values are deeply equal if their corresponding fields, both
exported and unexported, are deeply equal.
Func values are deeply equal if both are nil; otherwise they are not
deeply equal.
Interface values are deeply equal if they hold deeply equal concrete
values.
Map values are deeply equal if they are the same map object or if they
have the same length and their corresponding keys (matched using Go
equality) map to deeply equal values.
Pointer values are deeply equal if they are equal using Go's ==
operator or if they point to deeply equal values.
Slice values are deeply equal when all of the following are true: they
are both nil or both non-nil, they have the same length, and either
they point to the same initial entry of the same underlying array
(that is, &x[0] == &y[0]) or their corresponding elements (up to
length) are deeply equal. Note that a non-nil empty slice and a nil
slice (for example, []byte{} and []byte(nil)) are not deeply equal.
Other values - numbers, bools, strings, and channels - are deeply
equal if they are equal using Go's == operator.
You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a bytes.Equal function if you are comparing values of type []byte.
func testEq(a, b []Type) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
This is just example using reflect.DeepEqual() that is given in #VictorDeryagin's answer.
package main
import (
"fmt"
"reflect"
)
func main() {
a := []int {4,5,6}
b := []int {4,5,6}
c := []int {4,5,6,7}
fmt.Println(reflect.DeepEqual(a, b))
fmt.Println(reflect.DeepEqual(a, c))
}
Result:
true
false
Try it in Go Playground
If you have two []byte, compare them using bytes.Equal. The Golang documentation says:
Equal returns a boolean reporting whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.
Usage:
package main
import (
"fmt"
"bytes"
)
func main() {
a := []byte {1,2,3}
b := []byte {1,2,3}
c := []byte {1,2,2}
fmt.Println(bytes.Equal(a, b))
fmt.Println(bytes.Equal(a, c))
}
This will print
true
false
And for now, here is https://github.com/google/go-cmp which
is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
a := []byte{1, 2, 3}
b := []byte{1, 2, 3}
fmt.Println(cmp.Equal(a, b)) // true
}
You cannot use == or != with slices but if you can use them with the elements then Go 1.18 has a new function to easily compare two slices, slices.Equal:
Equal reports whether two slices are equal: the same length and all elements equal. If the lengths are different, Equal returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first unequal pair. Floating point NaNs are not considered equal.
The slices package import path is golang.org/x/exp/slices. Code inside exp package is experimental, not yet stable. It will be moved into the standard library in Go 1.19 eventually.
Nevertheless you can use it as soon as Go 1.18 (playground)
sliceA := []int{1, 2}
sliceB := []int{1, 2}
equal := slices.Equal(sliceA, sliceB)
fmt.Println(equal) // true
type data struct {
num float64
label string
}
sliceC := []data{{10.99, "toy"}, {500.49, "phone"}}
sliceD := []data{{10.99, "toy"}, {200.0, "phone"}}
equal = slices.Equal(sliceC, sliceD)
fmt.Println(equal) // true
If the elements of the slice don't allow == and !=, you can use slices.EqualFunc and define whatever comparator function makes sense for the element type.
In case that you are interested in writing a test, then github.com/stretchr/testify/assert is your friend.
Import the library at the very beginning of the file:
import (
"github.com/stretchr/testify/assert"
)
Then inside the test you do:
func TestEquality_SomeSlice (t * testing.T) {
a := []int{1, 2}
b := []int{2, 1}
assert.Equal(t, a, b)
}
The error prompted will be:
Diff:
--- Expected
+++ Actual
## -1,4 +1,4 ##
([]int) (len=2) {
+ (int) 1,
(int) 2,
- (int) 2,
(int) 1,
Test: TestEquality_SomeSlice
Thought of a neat trick and figured I'd share.
If what you are interested in knowing is whether two slices are identical (i.e. they alias the same region of data) instead of merely equal (the value at each index of one slice equals the value in the same index of the other) then you can efficiently compare them in the following way:
foo := []int{1,3,5,7,9,11,13,15,17,19}
// these two slices are exactly identical
subslice1 := foo[3:][:4]
subslice2 := foo[:7][3:]
slicesEqual := &subslice1[0] == &subslice2[0] &&
len(subslice1) == len(subslice2)
There are some caveats to this sort of comparison, in particular that you cannot compare empty slices in this way, and that the capacity of the slices isn't compared, so this "identicality" property is only really useful when reading from a slice or reslicing a strictly narrower subslice, as any attempt to grow the slice will be affected by the slices' capacity. Still, it's very useful to be able to efficiently declare, "these two huge blocks of memory are in fact the same block, yes or no."
To have a complete set of answers: here is a solution with generics.
func IsEqual[A comparable](a, b []A) bool {
// Can't be equal if length differs
if len(a) != len(b) {
return false
}
// Empty arrays trivially equal
if len(a) == 0 {
return true
}
// Two pointers going towards each other at every iteration
left := 0
right := len(a) - 1
for left < right {
if a[left] != b[left] || a[right] != b[right] {
return false
}
left++
right--
}
return true
}
Code uses strategy of "two pointers" which brings runtime complexity of n / 2, which is still O(n), however, twice as less steps than a linear check one-by-one.

Resources