kadobot's blog

By kadobot, history, 3 years ago, In English

I'm starting with Go, and decided to tackle this problem. I believe the code is correct, but for some reason, I'm getting different Exit Code's when running the tests. Can someone help me figuring out how to fix this?

Link to submission

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

type ii int
type oo int

var scanner = bufio.NewScanner(os.Stdin)
var cache = make(map[string]oo)

// SplitNums splits a string into a slice of integers
func SplitNums(s string) []ii {
	nums := strings.Split(strings.TrimSpace(s), " ")
	var result []ii
	for _, n := range nums {
		result = append(result, ParseInt(n))
	}
	return result
}

// ParseInt converts a string into an integer
func ParseInt(s string) ii {
	num, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
	if err != nil {
		log.Fatal(err)
	}
	return ii(num)
}

// ReadInput reads the input and returns the text
func ReadInput() string {
	scanner.Scan()
	return scanner.Text()
}

func solve(qty, boys, girls []ii) oo {
	g := make(map[ii]oo)
	b := make(map[ii]oo)
	for i := ii(0); i < qty[2]; i++ {
		g[boys[i]]++
		b[girls[i]]++
	}

	var total oo
	for i := ii(0); i < qty[2]; i++ {
		total += ((oo(qty[2]) - 1) - (g[boys[i]] - 1) - (b[girls[i]] - 1))
	}
	return total / 2
}

func main() {
	input := ReadInput()
	test_cases := ParseInt(input)

	for i := ii(0); i < test_cases; i++ {
		qty := SplitNums(ReadInput())
		boys := SplitNums(ReadInput())
		girls := SplitNums(ReadInput())
		fmt.Println(solve(qty, boys, girls))
	}
}
  • Vote: I like it
  • +5
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You can see the input on which your program breaks and run your program locally with this input. It is truncated, true, but enough is shown to make a guess that your program does not work well with long lines.

Consider checking the result of scanner.Scan() and using https://golang.org/pkg/bufio/#Scanner.Buffer