Skip to content

Instantly share code, notes, and snippets.

@jamiecuthill
Created October 11, 2019 11:02
Show Gist options
  • Save jamiecuthill/887daa33ce611cc0d33b20559b34917f to your computer and use it in GitHub Desktop.
Save jamiecuthill/887daa33ce611cc0d33b20559b34917f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
in, _ := strconv.Atoi(os.Args[1])
fmt.Println(Nearest([]int{3, -20, 1, -8, 7, 4, 11, -3}, in))
}
func Nearest(data []int, to int) int {
if len(data) == 1 {
return data[0]
}
current := data[0]
nearest := Nearest(data[1:], to)
if diff(current, to) < diff(nearest, to) {
return current
}
return nearest
}
func diff(a, b int) int {
d := a - b
if d < 0 {
return -d
}
return d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment