aboutsummaryrefslogtreecommitdiff
path: root/2021/10/second.go
blob: 69bd104efd781983d6e8de142d58191d1f9163ee (plain)
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
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

type stack []byte

func (s *stack) clear() {
	*s = make(stack, 0)
}

func (s *stack) push(b byte) {
	*s = append(*s, b)
}

func (s *stack) pop() *byte {
	l := len(*s)
	if l == 0 {
		return nil
	} else {
		elt := (*s)[l-1]
		*s = (*s)[:l-1]
		return &elt
	}
}

func main() {
	scores := make([]int, 0)
	s := make(stack, 0)

	scanner := bufio.NewScanner(os.Stdin)
out:
	for scanner.Scan() {
		line := scanner.Text()
		s.clear()
		for i := 0; i < len(line); i++ {
			c := line[i]
			if c == '(' || c == '[' || c == '{' || c == '<' {
				s.push(c)
				continue
			}
			b := s.pop()
			switch c {
			case ')':
				if *b != '(' {
					continue out
				}
			case ']':
				if *b != '[' {
					continue out
				}
			case '}':
				if *b != '{' {
					continue out
				}
			case '>':
				if *b != '<' {
					continue out
				}
			}
		}
		score := 0
		for c := s.pop(); c != nil; c = s.pop() {
			score *= 5
			switch *c {
			case '(':
				score += 1
			case '[':
				score += 2
			case '{':
				score += 3
			case '<':
				score += 4
			}
		}
		if score != 0 {
			scores = append(scores, score)
		}
	}
	sort.Ints(scores)
	fmt.Println(scores[len(scores)/2])
}