Check if all items in a slice are equal - go

I need to create a function that:
returns true if all elements in a slice are equal (they will all be the same type)
returns false if any elements in a slice are different
The only way I can think of doing it is to reverse the slice, and compare the slice and the reversed slice.
Is there a better way to do this thats good syntax and more efficient?

I am not sure what your though process was for reversing the slice was, but that would be unnecessary. The simplest algorithm would be to check to see if all elements after the the first are equal to the first:
func allSameStrings(a []string) bool {
for i := 1; i < len(a); i++ {
if a[i] != a[0] {
return false
}
}
return true
}

Although there is an accepted answer, I'm just posting it with range keyword.
func allSameStrings(a []string) bool {
for i, v := range(a) {
if v != a[0] {
return false
}
}
return true
}

Related

Reading from a slice of unknown length in Golang

I'm trying to replicate this algorithm for finding duplicates in an array in Golang. Here's the javascript version:
function hasDuplicateValue(array) {
let existingNumbers = [];
for(let i = 0; i < array.length; i++) {
if(existingNumbers[array[i]] === 1) {
return true;
} else {
existingNumbers[array[i]] = 1;
}
}
return false;
}
On line 2, the algorithm creates an empty array of unknown length, and then adds 1 to an index in the array corresponding with each number that it finds (e.g. if it finds the number 3 in the array, it will add a 1 to index 3 in existing numbers.
I'm wondering — how do I replicate this in Golang (since we need to have slots allocated in the slice before reading it). Would I first need to find the max value in the array and then declare the existingNumbers slice to be of that same size?
Or is there a more efficient way of doing this (instead of searching through the array and finding the max value before constructing the slice).
Thanks!
Edit:
I realized that I can't do this with a slice because I can't read from an empty value. However, as #icza suggested, it will work with a map:
func findDuplicates(list []int)(bool) {
temp := make(map[int]int)
for _, elem := range list {
if temp[elem] == 1 {
return true
} else {
temp[elem] = 1
}
}
return false
}
As comments, I would also suggest using a map to keep the state of the duplications, but we can use map[int]struct{} because empty structs are not consumed any memory in Go.
And also I have simplified the code a bit and it is as follows.
func findDuplicates(list []int) bool {
temp := make(map[int]struct{})
for _, elem := range list {
if _, ok := temp[elem]; ok {
return true
}
temp[elem] = struct{}{}
}
return false
}
Full code can be executed here

Find the minimum value in golang?

In the language there is a minimum function https://golang.org/pkg/math/#Min But what if I have more than 2 numbers? I must to write a manual comparison in a for loop, or is there another way? The numbers are in the slice.
No, there isn't any better way than looping. Not only is it cleaner than any other approach, it's also the fastest.
values := []int{4, 20, 0, -11, -10}
min := values[0]
for _, v := range values {
if (v < min) {
min = v
}
}
fmt.Println(min)
EDIT
Since there has been some discussion in the comments about error handling and how to handle empty slices, here is a basic function that determines the minimum value. Remember to import errors.
func Min(values []int) (min int, e error) {
if len(values) == 0 {
return 0, errors.New("Cannot detect a minimum value in an empty slice")
}
min = values[0]
for _, v := range values {
if (v < min) {
min = v
}
}
return min, nil
}
General answer is: "Yes, you must use a loop, if you do not know exact number of items to compare".
In this package Min functions are implemented like:
// For 2 values
func Min(value_0, value_1 int) int {
if value_0 < value_1 {
return value_0
}
return value_1
}
// For 1+ values
func Mins(value int, values ...int) int {
for _, v := range values {
if v < value {
value = v
}
}
return value
}
You should write a loop. It does not make sense to create dozens of function in standard library to find min/max/count/count_if/all_of/any_of/none_of etc. like in C++ (most of them in 4 flavours according arguments).

Arrays compare in golang

I need to compare 2 arrays of uint32, something like this
func in(a uint32, list []uint32) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
for n := 0 ;n < len(a); n++ {
fmt.Println(in(a[n], b))
}
// a and b []uint32
but I think it is not the most optimal way
Why not just use == if you are actually using arrays?
https://golang.org/ref/spec#Comparison_operators
Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.
If you are using slices, you can use reflect.DeepEqual.
But, from your code, it seems like you should look into https://godoc.org/golang.org/x/tools/container/intsets
Then, you create your two intsets.Sparse and could then do:
func main() {
s1 := intsets.Sparse{}
s2 := intsets.Sparse{}
s1.Insert(1)
s1.Insert(2)
s1.Insert(3)
s2.Insert(1)
s2.Insert(2)
//s1:{1,2,3}
//s2:{1,2}
fmt.Println(s1.SubsetOf(&s2), s2.SubsetOf(&s1))
//false, true
}
which will ignore duplicates, but let you know if s1 is a subset of s2, meaning every element in s1 exists in s2.

How do I check for an empty slice?

I am calling a function that returns an empty array if there are no values.
When I do this it doesn't work:
if r == [] {
fmt.Println("No return value")
}
The work around I'm using is:
var a [0]int
if r == a {
fmt.Println("No return value")
}
But declaring a variable just to check the return value doesn't seem right. What's the better way to do this?
len() returns the number of elements in a slice or array.
Assuming whatever() is the function you invoke, you can do something like:
r := whatever()
if len(r) > 0 {
// do what you want
}
or if you don't need the items
if len(whatever()) > 0 {
// do what you want
}
You can just use the len function.
if len(r) == 0 {
fmt.Println("No return value")
}
Although since you are using arrays, an array of type [0]int (an array of int with size 0) is different than [n]int (n array of int with size n) and are not compatible with each other.
If you have a function that returns arrays with different lengths, consider using slices, because function can only be declared with an array return type having a specific length (e.g. func f() [n]int, n is a constant) and that array will have n values in it (they'll be zeroed) even if the function never writes anything to that array.
You can use the inbuilt function provided by Golang
len()
It will helps you to easily find a slice is empty or not.
if len( yourFunction() ) == 0 {
// It implies that your array is empty.
}

How to check the uniqueness inside a for-loop?

Is there a way to check slices/maps for the presence of a value?
I would like to add a value to a slice only if it does not exist in the slice.
This works, but it seems verbose. Is there a better way to do this?
orgSlice := []int{1, 2, 3}
newSlice := []int{}
newInt := 2
newSlice = append(newSlice, newInt)
for _, v := range orgSlice {
if v != newInt {
newSlice = append(newSlice, v)
}
}
newSlice == [2 1 3]
Your approach would take linear time for each insertion. A better way would be to use a map[int]struct{}. Alternatively, you could also use a map[int]bool or something similar, but the empty struct{} has the advantage that it doesn't occupy any additional space. Therefore map[int]struct{} is a popular choice for a set of integers.
Example:
set := make(map[int]struct{})
set[1] = struct{}{}
set[2] = struct{}{}
set[1] = struct{}{}
// ...
for key := range(set) {
fmt.Println(key)
}
// each value will be printed only once, in no particular order
// you can use the ,ok idiom to check for existing keys
if _, ok := set[1]; ok {
fmt.Println("element found")
} else {
fmt.Println("element not found")
}
Most efficient is likely to be iterating over the slice and appending if you don't find it.
func AppendIfMissing(slice []int, i int) []int {
for _, ele := range slice {
if ele == i {
return slice
}
}
return append(slice, i)
}
It's simple and obvious and will be fast for small lists.
Further, it will always be faster than your current map-based solution. The map-based solution iterates over the whole slice no matter what; this solution returns immediately when it finds that the new value is already present. Both solutions compare elements as they iterate. (Each map assignment statement certainly does at least one map key comparison internally.) A map would only be useful if you could maintain it across many insertions. If you rebuild it on every insertion, then all advantage is lost.
If you truly need to efficiently handle large lists, consider maintaining the lists in sorted order. (I suspect the order doesn't matter to you because your first solution appended at the beginning of the list and your latest solution appends at the end.) If you always keep the lists sorted then you you can use the sort.Search function to do efficient binary insertions.
Another option:
package main
import "golang.org/x/tools/container/intsets"
func main() {
var (
a intsets.Sparse
b bool
)
b = a.Insert(9)
println(b) // true
b = a.Insert(9)
println(b) // false
}
https://pkg.go.dev/golang.org/x/tools/container/intsets
This option if the number of missing numbers is unknown
AppendIfMissing := func(sl []int, n ...int) []int {
cache := make(map[int]int)
for _, elem := range sl {
cache[elem] = elem
}
for _, elem := range n {
if _, ok := cache[elem]; !ok {
sl = append(sl, elem)
}
}
return sl
}
distincting a array of a struct :
func distinctObjects(objs []ObjectType) (distinctedObjs [] ObjectType){
var output []ObjectType
for i:= range objs{
if output==nil || len(output)==0{
output=append(output,objs[i])
} else {
founded:=false
for j:= range output{
if output[j].fieldname1==objs[i].fieldname1 && output[j].fieldname2==objs[i].fieldname2 &&......... {
founded=true
}
}
if !founded{
output=append(output,objs[i])
}
}
}
return output
}
where the struct here is something like :
type ObjectType struct {
fieldname1 string
fieldname2 string
.........
}
the object will distinct by checked fields here :
if output[j].fieldname1==objs[i].fieldname1 && output[j].fieldname2==objs[i].fieldname2 &&......... {

Resources