I enjoy Advent of Code every year. I like the small daily puzzles, and I certainly wouldn't want anything long and complicated every day. However, in order to add a bit of challenge, without resorting to racing, this year I'm using a language I don't really know. That's right, it's time for a periodic return to my Attempt to Learn Julia!
I've gotten a bit further than my last attempt. However, as with then, the tutorials/documentation are still not all that I'd hope. (I notice that they have many videos; however, when I'm trying to find the syntax for something, I don't want to watch a whole video hoping they'll mention it.) So here's a cheatsheet of some basic things I've figured out so far.
Loading data from a file
To read the whole file, as one long string:
open("filename.txt", "r") do f data = read(f, String) end
To read the file line by line:
open("filename.txt", "r") do f for ln in eachline(f) ... end end
Once you've read that data, you might want to split it appart into a list:
mylist = split(ln) # Defaults to splitting on whitespace mylist = split(ln, ',') # Or, provide a delimiter
If you had numbers in that data file of yours, you'll probably want to convert them from strings into numbers:
intval = parse(Int, stringval) floatval = parse(Float64, stringval)
Searching in your string or array
Now that you have your data loaded, maybe you'll want to find a particular value. To check if a value is in your array (or a character in your string):
val in myarray
If you want to know where is the array your value is, you can use
findnext. Note that these will both return
nothing if you search value is not in the array, and
nothing cannot be used as a boolean, so if you want to go through all the occurences of your value, you'll need to check for it:
index = findfirst(isequal(val), myarray) while index != nothing println(index) index = findnext(isequal(val), myarray, index+1) end
These can be used with other conditions in place of
isequal, including user defined predicates.
There are various tutorials online for using Regular Expressions in Julia, but they are mostly incorrect. It looks like the methods changed name at some point, so the examples in the tutorial no longer work. For version 1.5.3, you can find if a regular expression matches on your string with
Substitions can be done with
replace on arrays and strings, with a slight variation between the two. For arrays:
replace([1, 2, 3, 4, 5, 6], 1=>10, 2=>20)
For strings, the same format applies, but only one substition can be done. You can apply multiple rules by nesting calls to
replace(replace("abcdef", "a"=>"x"), "b"=>"y")
However, for strings,
replace can also be used with regular expression, which would allow more complicated substitutions, such as reordering substrings.