= open("../../DATA/2023/input_day01.txt", "r");
input_file = readline(input_file);
line
= Int32[];
all_numbers while line != ""
= split(line, "");
split_line = [];
current_numbers for sign ∈ split_line
try
push!(current_numbers, parse(Int, sign));
catch err
end
end
= parse(
out_number Int,
string(first(current_numbers), last(current_numbers))
)push!(all_numbers, out_number);
# read the next line:
global line = readline(input_file);
end
close(input_file);
Day 1
The input
There are some numbers in each line, hidden between characters.
data_in="../../DATA/2023/input_day01.txt"
head $data_in
wc -l $data_in
PART 1
The puzzle
I need to find the numbers in each line and re-create them. Next, I need to add up all the numbers in the document.
The solution
Now, I have all the numbers:
all_numbers
1000-element Vector{Int32}:
22
99
16
77
66
54
22
72
66
15
25
41
73
⋮
76
14
79
15
16
33
34
72
11
37
72
26
The sum of these numbers is 54388.
PART 2
The task is more difficult than I thought! :D
The numbers can also be spelled: one
, two
, three
, four
, five
, six
, seven
, eight
, or nine
.
= open("../../DATA/2023/input_day01.txt", "r");
input_file = readline(input_file);
line
= Int32[];
all_numbers = Dict(
all_spelled_numbers "one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5,
"six" => 6, "seven" => 7, "eight" => 8, "nine" => 9
);while line != ""
= DataFrame(
current_numbers = -1;
index = -1
number
);# first - check spelled numbers
for spelled_num ∈ keys(all_spelled_numbers)
if occursin(spelled_num, line)
= first(findfirst(spelled_num, line));
first_idx = first(findlast(spelled_num, line));
last_idx = all_spelled_numbers[spelled_num];
cur_number if first_idx != last_idx
append!(current_numbers, DataFrame(
= [first_idx, last_idx],
index = [cur_number, cur_number]
number
));else
append!(current_numbers, DataFrame(
= first_idx,
index = cur_number
number
));end
end
end
# then - check digits
for digit_num ∈ values(all_spelled_numbers)
if occursin(string(digit_num), line)
= first(findfirst(string(digit_num), line));
first_idx = first(findlast(string(digit_num), line));
last_idx if first_idx != last_idx
append!(current_numbers, DataFrame(
= [first_idx, last_idx],
index = [digit_num, digit_num]
number
));else
append!(current_numbers, DataFrame(
= first_idx,
index = digit_num
number
));end
end
end
# first row was used only to set the types of columns correctly
deleteat!(current_numbers, 1)
sort!(current_numbers, order(:index))
= parse(Int, string(first(current_numbers.number), last(current_numbers.number)))
out_number push!(all_numbers, out_number);
# read the next line:
global line = readline(input_file);
end
close(input_file);
The solution
Now, I have all the numbers:
all_numbers
1000-element Vector{Int32}:
32
19
16
16
16
55
72
52
86
25
18
46
53
⋮
75
94
19
14
16
33
34
77
91
87
58
26
The sum of these numbers is 53515.