-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd1.go
113 lines (95 loc) · 1.95 KB
/
d1.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
// func main() {
// var lines []string
// for i, arg := range os.Args {
// if arg == "-f" {
// var err error
// lines, err = readFile2Lines(os.Args[i+1])
// if err != nil {
// fmt.Println(err)
// return
// }
// }
// }
// sum := 0
// for _, l := range lines {
// first, last, found := findFirstLastDigit(l)
// if !found {
// fmt.Println("No digit found in line", l)
// }
// twoDigit := first + last
// x, err := strconv.Atoi(twoDigit)
// if err != nil {
// fmt.Println(err)
// return
// }
// sum += x
// }
// fmt.Println("The sum is:", sum)
// }
func readFile2Lines(fileName string) ([]string, error) {
var lines []string
file, err := os.Open(fileName)
if err != nil {
return lines, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
err = scanner.Err()
if err != nil {
return lines, err
}
return lines, nil
}
func findFirstLastDigit(str string) (string, string, bool) {
var first string
var last string
wordNumber := make(map[string]string)
wordNumber["zero"] = "0"
wordNumber["one"] = "1"
wordNumber["two"] = "2"
wordNumber["three"] = "3"
wordNumber["four"] = "4"
wordNumber["five"] = "5"
wordNumber["six"] = "6"
wordNumber["seven"] = "7"
wordNumber["eight"] = "8"
wordNumber["nine"] = "9"
fmt.Println("Input", str)
strLen := len(str)
for i, char := range str {
if unicode.IsDigit(char) {
if first == "" {
first = string(char)
}
last = string(char)
} else {
for key, value := range wordNumber {
keyLen := len(key)
if i+keyLen <= strLen {
if str[i:i+keyLen] == key {
if first == "" {
first = value
}
last = value
}
}
}
}
}
if first == "" || last == "" {
return first, last, false
}
fmt.Println("First", string(first))
fmt.Println("Last", string(last))
return first, last, true
}