/
main.go
97 lines (82 loc) · 1.48 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
func main() {
sortToys()
}
type Data struct {
canBuy int32
totalToys int32
totalFunds int32
toys []int
}
func sortToys() {
var d Data
reader := bufio.NewReaderSize(os.Stdin, 1024*1024)
d.setTotals(readLine(reader))
if err := d.setToys(readLine(reader)); err != nil {
d.printResult()
return
}
if d.totalFunds == 0 || len(d.toys) == 0 {
d.printResult()
}
d.countToBuy()
d.printResult()
}
func (d *Data) countToBuy() {
var sum int32
for _, toy := range d.toys {
sum += int32(toy)
if sum <= d.totalFunds {
d.canBuy++
}
if sum >= d.totalFunds {
return
}
}
}
func (d Data) printResult() {
_, err := fmt.Fprintf(os.Stdout, "%d", d.canBuy)
if err != nil {
return
}
}
func (d *Data) setTotals(input string) {
data := strings.Split(input, " ")
tTotal, err := strconv.ParseInt(data[0], 10, 32)
if err != nil {
return
}
fTotal, err := strconv.ParseInt(data[1], 10, 32)
if err != nil {
return
}
d.totalToys = int32(tTotal)
d.totalFunds = int32(fTotal)
}
func (d *Data) setToys(input string) error {
for _, toy := range strings.Split(input, " ") {
toyP, err := strconv.ParseInt(toy, 10, 64)
if err != nil {
return err
}
d.toys = append(d.toys, int(toyP))
}
sort.Ints(d.toys)
return nil
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}