Golang prepend the array [duplicate] - go

This question already has an answer here:
golang prepend a string to a slice ...interface{}
(1 answer)
Closed 4 years ago.
package main
import (
"fmt"
)
func main() {
var result [][]int
var tempArr []int
tempArr = append(tempArr, 1, 2, 3, 5)
result = append(result, tempArr)
prepend := []int{1, 2, 3}
result = append([]int{prepend}, result...) // Not working
fmt.Println(result)
}
What is the correct way to prepend to an array? I need help to fix this line:
result = append([]int{prepend}, result...)

The type is mismatch. []int{prepend} type is [] int. But prepend type is [] int. So []int{prepend} is not correct. The right way is [][]int{prepend}, below code will pass.
result = append([][]int{prepend}, result...)
The result will be:
[[1 2 3] [1 2 3 5]]

Related

How to move elements from one slice to another

package main
import (
"fmt"
)
func main() {
arr0 := []int{
1,2,3,4,5,
}
arr1 := []int{}
fmt.Println(arr0)
fmt.Println(arr1)
fmt.Println("transferring...")
transfer(&arr0, &arr1)
fmt.Println(arr0)
fmt.Println(arr1)
}
func transfer(arr0 *[]int, arr1 *[]int) {
tmp := make([]int, 0)
for i:=0;i<len(*arr0);i++ {
tmp = append(tmp, (*arr0)[i])
}
arr1 = &tmp
s := make([]int, 0)
arr0 = &s
}
For function of transfer, I intented to transfer elements of slice arr0 to slice arr1 and empty slice arr0
But it is not successful
Here is my output
[1 2 3 4 5]
[]
transferring...
[1 2 3 4 5]
[]
After transferring, I need the result below.
[]
[1 2 3 4 5]
But actually, arr0, and arr1 in the main function remain as it was!
can someone tell me why this is not ok?
I thought in the memory, it should be like this
after running transfer function
#jacobsa has given an excellent answer.
Just keep that in mind. You can achieve the same effect but with better performance. Golang offers an excellent opportunity for this.
package main
import (
"fmt"
)
func main() {
arr0 := []int{
1, 2, 3, 4, 5,
}
arr1 := []int{}
fmt.Println(arr0)
fmt.Println(arr1)
fmt.Println("transferring...")
transfer(&arr0, &arr1)
fmt.Println(arr0)
fmt.Println(arr1)
}
func transfer(arr0 *[]int, arr1 *[]int) {
*arr0, *arr1 = *arr1, *arr0
}
These two lines:
arr1 = &tmp
arr0 = &s
change the local variables arr1 and arr0 within the function. Those variables happen to be pointers, but they are just copies of the input pointers provided by main—they are not references to the input pointers.
If you changed the things the arr1 and arr0 pointers point to, rather than the pointers themselves, then you would see a change to the values provided by main:
*arr1 = tmp
*arr0 = s

how to get lonely value from a slice golang [duplicate]

This question already has answers here:
How to remove duplicates strings or int from Slice in Go
(12 answers)
How to delete duplicates of an item from a slice?
(3 answers)
how to delete Duplicate elements between slices on golang
(1 answer)
Closed 10 months ago.
I want to create a function that can retrieve data that has no duplicates from a slice
an example of a slice that will be processed:
number1 := []int{3,4,5,4,3}
number2 := []int{3,4,5,6,4,3}
expected result :
res1 = []int{5}
res2 = []int{5,6}
i have do something like this
func unique(arg []int) []int {
var inResult = make(map[int]bool)
var result []int
for _, value := range arg {
if _, ok := inResult[value]; !ok {
inResult[value] = true
result = append(result, value)
} else {
inResult[value] = false
}
}
fmt.Println(inResult)
return result
}
func main() { arg := []int{6, 6, 7, 1, 2, 3, 4, 5, 3, 2, 1}
res := unique(arg)
fmt.Println(res)
}
how to get the key from map where the value is true?
map[1:false 2:false 3:false 4:true 5:true 6:false 7:true]
[6 7 1 2 3 4 5]
You can filter out the keys like this.
Remove the following line in if block. It should be done after the complete iteration.
result = append(result, value)
Filter the keys with having true value before returning result.
for key, value := range inResult {
if value {
result = append(result, key)
}
}
Go Playground

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]]

The Equivalent of indexof [duplicate]

This question already has answers here:
How to find out element position in slice?
(10 answers)
Closed 2 years ago.
I am trying to find out the equivalent of indexof to get the position of specific element in array golang the purpose for integers in array.
package main
import (
"fmt"
)
func main() {
fmt.Println("what")
arr := []int{1, 2, 3, 4, 2, 2, 3, 5, 4, 4, 1, 6}
i := IndexOf(2, arr)
}
Write a function. Here's an example assuming that IndexOf returns the first index of the number or -1 if none is found.
// IndexOf returns the first index of needle in haystack
// or -1 if needle is not in haystack.
func IndexOf(haystack []int, needle int) int {
for i, v := range haystack {
if v == needle {
return i
}
}
return -1
}
Run this code on the Go Programming Language Playground.
There is no common library function to do this for you in go.
However if you are using a byte slice, you can use IndexByte(b []byte, c byte) int.
Or you can write a quick function which does this for you:
func indexOf(arr []int, val int) int {
for pos, v := range arr {
if v == val {
return pos
}
}
return -1
}
package main
import "fmt"
func IndexOf(arr []int, candidate int) int {
for index, c := range arr {
if c == candidate {
return index
}
}
return -1
}
func main() {
fmt.Println("what")
arr := []int{1, 2, 3, 4, 2, 2, 3, 5, 4, 4, 1, 6}
i := IndexOf(arr, 2)
fmt.Println(i)
}
Add a method IndexOf to search, this is a linear search method.
Ref: https://play.golang.org/p/Hp6Dg--XoIV
There is no equivalent for IndexOf in Go. You need to implement one your self. But if you have have sorted array of Ints, you can use sort.SearchInts as shown below.
package main
import (
"fmt"
"sort"
)
func main() {
fmt.Println(sort.SearchInts([]int{2,3,4,5,9,10,11}, 5))
}
Also from the godoc:
SearchInts searches for x in a sorted slice of ints and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

Change golang slice in another function

I have a slice, if i remove one element from it directly in a main function the length of slice would be cut by one. But do the remove in another function and called it in main, the length of the slice is still keep origin. Who can explain it for me? Thanks!
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4}
i := 0
//copy(a[i:], a[i+1:])
//a[len(a)-1] = 0
//a = a[:len(a)-1]
//fmt.Println(a) //outputs: [2 3 4], this is correct
f(a, i)
fmt.Println(a) //outputs: [2 3 4 0], this is wrong!
}
func f(a []int, i int) {
copy(a[i:], a[i+1:])
a[len(a)-1] = 0
a = a[:len(a)-1]
fmt.Println(a) //outputs: [2 3 4], here still correct
}
Go Playground Link
The slice is passed by value, so changing it in your function f won't change it in function main. You can pass by pointer, like this:
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4}
i := 0
f(&a, i)
fmt.Println(a) //outputs: [2 3 4], correct
}
func f(a *[]int, i int) {
b := *a
copy(b[i:], b[i+1:])
// The following line seems pointless, but ok...
b[len(b)-1] = 0
b = b[:len(b)-1]
fmt.Println(b) //outputs: [2 3 4], here still correct
*a = b
}
Go Playground
As suggested by #zerkms in the comments, you could also return the new slice, avoiding the use of pointers:
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4}
i := 0
a = f(a, i)
fmt.Println(a)
}
func f(a []int, i int) []int {
copy(a[i:], a[i+1:])
// The following line seems pointless, but ok...
a[len(a)-1] = 0
a = a[:len(a)-1]
fmt.Println(a) //outputs: [2 3 4], here still correct
return a
}
Not providing new solution, just trying to explain why your program is behaving the way you asked:
Let us try to understand first how the built in function ‘copy’ works

Ref: [https://golang.org/pkg/builtin/#copy]
func copy(dst, src []Type) int
The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
Two things:
1. 
First comment the line : //a[len(a)-1] = 0
Second: As you are using the same array i.e as source and destination you are getting [2,3,4,4] as output as the destination array is {1,2,3,4} which got overwritten to {2,3,4,4(which is already present)}

you can try with different array’s to make it more clear to you

Resources