Last active
November 1, 2016 16:20
-
-
Save caelifer/89a08f81562ed0badd7f51aaf339ae4c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a solution implemented in Go (golang.org) for the "lonely integer" problem | |
// as presented here: | |
// | |
// https://www.hackerrank.com/contests/master/challenges/lonely-integer | |
// | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"log" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
for _, tc := range tests { | |
nums := input(strings.NewReader(tc.in)) | |
got := reduce(func(a, b int) int { | |
return a ^ b | |
}, nums...) | |
fmt.Printf("Input:\n%s\n", tc.in) | |
if got != tc.ans { | |
fmt.Printf("[FAIL] Got %d, expected %d\n\n", got, tc.ans) | |
} else { | |
fmt.Printf("[OK] Got correct asnwer: %d\n\n", got) | |
} | |
} | |
} | |
func reduce(tr func(int, int) int, a ...int) int { | |
x := 0 | |
for _, v := range a { | |
x = tr(x, v) | |
} | |
return x | |
} | |
func input(in io.Reader) (out []int) { | |
scn := bufio.NewScanner(in) | |
// Read first line | |
scn.Scan() | |
// Get integer from the line | |
n, err := strconv.Atoi(scn.Text()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Alloc output slice | |
out = make([]int, n) | |
// Read the second line | |
scn.Scan() | |
for i, v := range strings.SplitN(scn.Text(), " ", n) { | |
if out[i], err = strconv.Atoi(v); err != nil { | |
log.Fatal(err) | |
} | |
} | |
return | |
} | |
var tests = []struct { | |
in string | |
ans int | |
}{ | |
{ | |
"1\n1", | |
1, | |
}, | |
{ | |
"3\n2 1 1", | |
2, | |
}, | |
{ | |
"5\n0 1 3 1 0", | |
3, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live code - https://play.golang.org/p/7obhYn3Nzz
Output: