TutorialEdge

Challenge 13 - Smallest Difference

Welcome, everyone to the discussion thread for the 13th Go challenge posted to the site :tada:

Feel free to show us how you solved the challenge by posting your solutions below!

package main

import "fmt"

import "sort"

func CalcSmallestDifference(arr1, arr2 []int) int {  
  sort.Ints(arr1)
  sort.Ints(arr2)
  
  greater1 := arr1[len(arr1)-1]
  smaller2 := arr2[0]
  
  if (greater1 >= smaller2) {
return 0
  } 
  return smaller2 - greater1
}

func main() {
  fmt.Println("Smallest Difference Challenge")

  arr1 := []int{9, 8, 7, 6}
  arr2 := []int{7, 3, 2, 5}

  smallestDiff := CalcSmallestDifference(arr1, arr2)
  fmt.Println(smallestDiff)
}
import (
	"fmt"
	"math"
)

func CalcSmallestDifference(arr1, arr2 []int) int {
	answer := -1
	for i := range arr1 {
		for j := range arr2 {
			ret := arr1[i] - arr2[j]
			if answer == -1 {
				answer = int(math.Abs(float64(ret)))
			} else if int(math.Abs(float64(ret))) < answer {
				answer = int(math.Abs(float64(ret)))
			}
		}
	}
	return answer
}