How to read a textfile directly as `Matrix{Char}`

it’s that time of the year again, say we have:

467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..

in a file, and we want:

julia> mapreduce(permutedims∘collect, vcat, readlines("./a.txt"))
10×10 Matrix{Char}:
 '4'  '6'  '7'  '.'  '.'  '1'  '1'  '4'  '.'  '.'
 '.'  '.'  '.'  '*'  '.'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '3'  '5'  '.'  '.'  '6'  '3'  '3'  '.'
 '.'  '.'  '.'  '.'  '.'  '.'  '#'  '.'  '.'  '.'
 '6'  '1'  '7'  '*'  '.'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '.'  '.'  '.'  '+'  '.'  '5'  '8'  '.'
 '.'  '.'  '5'  '9'  '2'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '.'  '.'  '.'  '.'  '7'  '5'  '5'  '.'
 '.'  '.'  '.'  '$'  '.'  '*'  '.'  '.'  '.'  '.'
 '.'  '6'  '6'  '4'  '.'  '5'  '9'  '8'  '.'  '.'

is there easier way to do this? I was hoping DelimitedFiles can split “everything” but I can’t get it to work

1 Like
julia> stack(collect.(readlines(b)); dims=1)
10×10 Matrix{Char}:
 '4'  '6'  '7'  '.'  '.'  '1'  '1'  '4'  '.'  '.'
 '.'  '.'  '.'  '*'  '.'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '3'  '5'  '.'  '.'  '6'  '3'  '3'  '.'
 '.'  '.'  '.'  '.'  '.'  '.'  '#'  '.'  '.'  '.'
 '6'  '1'  '7'  '*'  '.'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '.'  '.'  '.'  '+'  '.'  '5'  '8'  '.'
 '.'  '.'  '5'  '9'  '2'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '.'  '.'  '.'  '.'  '7'  '5'  '5'  '.'
 '.'  '.'  '.'  '$'  '.'  '*'  '.'  '.'  '.'  '.'
 '.'  '6'  '6'  '4'  '.'  '5'  '9'  '8'  '.'  '.'

No need to collect:

stack(readlines(file); dims=1)
7 Likes

I slightly prefer eachline over readline for AoC problems.

Also sometimes it helps to have something lime the following at the ready in case you need to customize processing.

julia> using Chain

julia> input = IOBuffer(raw"""
       467..114..
       ...*......
       ..35..633.
       ......#...
       617*......
       .....+.58.
       ..592.....
       ......755.
       ...$.*....
       .664.598..
       """);

julia> @chain input begin
           read
           Char.(_)
           reshape(_, findfirst(==('\n'), _), :)
           _[1:end-1, :]
           permutedims(_, (2,1))
       end
10×10 Matrix{Char}:
 '4'  '6'  '7'  '.'  '.'  '1'  '1'  '4'  '.'  '.'
 '.'  '.'  '.'  '*'  '.'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '3'  '5'  '.'  '.'  '6'  '3'  '3'  '.'
 '.'  '.'  '.'  '.'  '.'  '.'  '#'  '.'  '.'  '.'
 '6'  '1'  '7'  '*'  '.'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '.'  '.'  '.'  '+'  '.'  '5'  '8'  '.'
 '.'  '.'  '5'  '9'  '2'  '.'  '.'  '.'  '.'  '.'
 '.'  '.'  '.'  '.'  '.'  '.'  '7'  '5'  '5'  '.'
 '.'  '.'  '.'  '$'  '.'  '*'  '.'  '.'  '.'  '.'

I actually prefer to leave out the permutedims.