Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active November 1, 2016 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caelifer/89a08f81562ed0badd7f51aaf339ae4c to your computer and use it in GitHub Desktop.
Save caelifer/89a08f81562ed0badd7f51aaf339ae4c to your computer and use it in GitHub Desktop.
// 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,
},
}
@caelifer
Copy link
Author

caelifer commented Sep 14, 2016

Live code - https://play.golang.org/p/7obhYn3Nzz

Output:

Input:
1
1
[OK] Got correct asnwer: 1

Input:
3
2 1 1
[OK] Got correct asnwer: 2

Input:
5
0 1 3 1 0
[OK] Got correct asnwer: 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment