DEV Community

Cover image for [Golang] How to get the diagonal difference: Problem Solving
Kuldeep Singh
Kuldeep Singh

Posted on

[Golang] How to get the diagonal difference: Problem Solving

Hi,
So today we're about to cover up another problem solving question which is how we can find the diagonal difference and we are going to cover up this problem via two ways.

  1. Using Loop
  2. Using Recursive function.

Let's see the question first

Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.

Now Let's start Writing Code

  1. Using Loop
func DiagonalDifference(arr [][]int) int {
    d1 := []int{}
    d2 := []int{}
    d1Sum := 0
    d2Sum := 0
    for x := range arr {
        for y := range arr {
            if x == y {
                d1 = append(d1, arr[x][y])
                d1Sum += arr[x][y]
            }

            if x == len(arr)-y-1 {
                d2 = append(d2, arr[x][y])
                d2Sum += arr[x][y]
            }
        }
    }
    fmt.Println("Left Diagonal Values", d1)
    fmt.Println("Right Diagonal Values", d2)

    return int(math.Abs(float64(d1Sum) - float64(d2Sum)))
}
Enter fullscreen mode Exit fullscreen mode

Find the code from here for recursive method:
https://kdsingh4.blogspot.com/2021/10/how-to-find-diagonal-difference.html

Also Subscribe My Channel as well :)
https://www.youtube.com/channel/UCXhmNqWQ50zitqIdTgS7s8Q

Thanks for Reading

Top comments (0)