source code migrating from gitlab
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
all:
|
||||
odin build . -out:main
|
||||
|
||||
clean:
|
||||
rm main
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import "core:fmt"
|
||||
import "core:os"
|
||||
import "core:strconv"
|
||||
import "core:strings"
|
||||
import "core:unicode/utf8"
|
||||
|
||||
main :: proc() {
|
||||
|
||||
if len(os.args) < 2 {
|
||||
fmt.println("Error: file required")
|
||||
os.exit(-1)
|
||||
}
|
||||
filename := os.args[1]
|
||||
|
||||
sum, ok := getSum(filename)
|
||||
if !ok {
|
||||
os.exit(-1)
|
||||
}
|
||||
fmt.println(sum)
|
||||
|
||||
}
|
||||
|
||||
|
||||
getSum :: proc(filename: string) -> (int, bool) {
|
||||
data, err := os.read_entire_file(filename, context.allocator)
|
||||
if err != nil {
|
||||
fmt.println("error opening file", err)
|
||||
return -1, false
|
||||
}
|
||||
defer delete(data, context.allocator)
|
||||
sum := 0
|
||||
|
||||
iter := string(data)
|
||||
|
||||
for line in strings.split_lines_iterator(&iter) {
|
||||
first := getFirst(line)
|
||||
last := getLast(line)
|
||||
|
||||
// convert to rune array
|
||||
digits := []rune{first, last}
|
||||
// convert rune array to string first?
|
||||
str := utf8.runes_to_string(digits, context.allocator)
|
||||
// covert string to int..
|
||||
val, ok := strconv.parse_int(str)
|
||||
if !ok {
|
||||
fmt.println("error converting to int")
|
||||
continue
|
||||
}
|
||||
sum += val
|
||||
|
||||
}
|
||||
|
||||
return sum, true
|
||||
}
|
||||
|
||||
getFirst :: proc(line: string) -> rune {
|
||||
first: rune
|
||||
|
||||
for ch in line {
|
||||
if ch >= '0' && ch <= '9' {
|
||||
first = ch
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return first
|
||||
}
|
||||
|
||||
getLast :: proc(line: string) -> rune {
|
||||
last: rune
|
||||
|
||||
length := len(line) - 1
|
||||
for i := length; i >= 0; i -= 1 {
|
||||
if line[i] >= '0' && line[i] <= '9' {
|
||||
last = rune(line[i])
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
return last
|
||||
}
|
||||
Reference in New Issue
Block a user