Skip to content

Instantly share code, notes, and snippets.

@thoroc
Last active August 29, 2015 14:15
Show Gist options
  • Save thoroc/ad03ccd5b6cf11f6e46e to your computer and use it in GitHub Desktop.
Save thoroc/ad03ccd5b6cf11f6e46e to your computer and use it in GitHub Desktop.
codingame - Temperature
package main
import (
"fmt"
"os"
"bufio"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
// N: the number of temperatures to analyse
var N int
scanner.Scan()
fmt.Sscan(scanner.Text(),&N)
fmt.Fprintln(os.Stderr, "number of values: " + strconv.Itoa(N))
scanner.Split(bufio.ScanWords)
var values []int
var result int
for scanner.Scan() {
// the N temperatures expressed as integers ranging from -273 to 5526
x, err := strconv.Atoi(scanner.Text())
if err != nil {
panic(err)
}
values = append(values, x)
}
result = closest(values, 0)
// fmt.Fprintln(os.Stderr, "sum: " + strconv.Itoa(sum))
fmt.Println(result)// Write answer to stdout
}
func closest(values []int, median int) int {
var result int
var curr int
for i := 0; i < len(values); i++ {
fmt.Fprintln(os.Stderr, "=============================")
fmt.Fprintln(os.Stderr, "pos: " + strconv.Itoa(i))
curr = values[i]
fmt.Fprintln(os.Stderr, "curr: " + strconv.Itoa(curr))
fmt.Fprintln(os.Stderr, "rest: " + strconv.Itoa(result))
if i == 0 {
result = curr
} else {
if abs(curr) < abs(result){
result = curr
} else if abs(curr) == abs(result) {
if curr != result {
result = abs(result)
} else {
result = result
}
} else {
result = result
}
}
}
return result
}
// from src/image/png/paeth.go
// intSize is either 32 or 64.
const intSize = 32 << (^uint(0) >> 63)
func abs(x int) int {
// m := -1 if x < 0. m := 0 otherwise.
m := x >> (intSize - 1)
// In two's complement representation, the negative number
// of any number (except the smallest one) can be computed
// by flipping all the bits and add 1. This is faster than
// code with a branch.
// See Hacker's Delight, section 2-4.
return (x ^ m) - m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment