Skip to content

Instantly share code, notes, and snippets.

@PirosB3
Created June 1, 2014 23:46
Show Gist options
  • Select an option

  • Save PirosB3/98b1952101fc4d1c4797 to your computer and use it in GitHub Desktop.

Select an option

Save PirosB3/98b1952101fc4d1c4797 to your computer and use it in GitHub Desktop.
Problem A. Store Credit
package main
import (
"fmt"
"flag"
"bufio"
"strconv"
"strings"
"sync"
"os"
)
type MyReader struct {
*bufio.Reader
}
func ReadInt(s string) int {
num, _ := strconv.ParseInt(strings.TrimRight(s, "\n"), 0, 64)
return int(num)
}
func (r *MyReader) ReadNextNumber() int {
line, _ := r.ReadString('\n')
return ReadInt(line)
}
func (r *MyReader) ReadNextNumbers() (int, map[int]int) {
money := r.ReadNextNumber()
length := r.ReadNextNumber()
line, _ := r.ReadString('\n')
line = strings.TrimRight(line, "\n")
lines := strings.Split(line, " ")
res := make(map[int]int, length)
for i := 0; i < length; i++ {
num, _ := strconv.ParseInt(lines[i], 0, 64)
res[int(num)] = i+1
}
return money, res
}
func main() {
path := flag.String("path", "path", "the path")
flag.Parse()
fi, _ := os.Open(*path)
myReader := &MyReader{bufio.NewReader(fi)}
defer fi.Close()
nCases := myReader.ReadNextNumber()
wg := sync.WaitGroup{}
result := make([][2]int, nCases)
for i:=0; i < nCases; i++ {
wg.Add(1)
money, items := myReader.ReadNextNumbers()
go func(i int, money int, items map[int]int) {
defer wg.Done()
for num, index := range items {
remain := money - num
if items[remain] > 0 {
result[i][0] = index -1
result[i][1] = items[remain] -1
break
}
}
}(i, money, items)
}
wg.Wait()
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment