0
func assertEq(test [][]string, ans [][]string) {
    for i := 0; i < len(test); i++ {
        for j := 0; j < len(ans); j++ {
            if test[i][j] != ans[i][j] {
                fmt.Print(test)
                fmt.Print(" ! ")
                fmt.Print(ans)
            }
        }
    }
    fmt.Println()
}

In my code it's not checking. I have used two different string arrays to compare each and every character.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
nagulan
  • 41
  • 2
  • 3
  • 1
    have you tried `reflect.DeepEqual` https://golang.org/pkg/reflect/#DeepEqual ? – Alex Efimov Apr 16 '18 at 11:06
  • 1
    Note that `[][]string` is not an array. It's a slice of slices. – Jonathan Hall Apr 16 '18 at 11:07
  • 2
    You have already written the code for comparing the slices. What's the problem, exactly (other than missing boundary checks). – Peter Apr 16 '18 at 11:08
  • For better performance, check that the slice lengths are equal before checking all the elements are equal. If performance is not a concern you could use DeepEqual as suggested by @AlexEfimov – StevieB Apr 16 '18 at 11:25
  • Possible duplicate of [Checking the equality of two slices](https://stackoverflow.com/questions/15311969/checking-the-equality-of-two-slices) – Abdullah Al Maruf - Tuhin Apr 16 '18 at 11:40

2 Answers2

4

i and j are lengths of test and ans. So, they are not valid index for test[i][j] or ans[i][j].

You can simply use reflect.DeepEqual().

You can extend this solution for multiple dimension slices.

One simple example:

package main

import (
    "fmt"
    "reflect"
)

func assertEq(test [][]string, ans [][]string) bool {
    return reflect.DeepEqual(test, ans)
}

func main() {
    str1 := [][]string{{"1", "2", "3"}, {"1", "2", "3"}, {"1", "2", "3"}}
    str2 := [][]string{{"1", "2", "3"}, {"1", "2", "3"}, {"1", "2", "3"}}
    str3 := [][]string{{"1", "2", "3"}, {"1", "2", "3"}, {"1", "2"}}

    fmt.Println(assertEq(str1, str2)) // answer is true
    fmt.Println(assertEq(str1, str3)) // answer is false
}
0

package cmp

import "github.com/google/go-cmp/cmp"

Package cmp determines equality of values.

This package is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.


Use package cmp.

peterSO
  • 158,998
  • 31
  • 281
  • 276