Marketing Pitch and Impressions#

Crystal is a general-purpose, object-oriented programming language. With syntax inspired by Ruby, it’s a compiled language with static type-checking. Types are resolved by an advanced type inference algorithm.

crystal-lang.org

Crystal uses LLVM to compile to native code, without the verbose syntax usually associated with systems languages.

Visual Studio Code support for Crystal is available, but not as complete as some other languages. I understand from googling around that LSP support is more complex because of the syntactic flexibility.

The Code#

Like Ruby, Crystal lends itself to code-golfing. The snippet below is what I ended up with after a bit of mucking around once I had a working version.

The algorithm for part 1 is pretty basic. I parse the input into ranges and ingredients, and then just count the ingredients that are included in any of the ranges.

The algorithm for part 2 is likewise pretty straightforward: sort the ranges and then merge adjacent ones. Once this is done, we just sum up the size of each range.

Crystal’s lexical flexibility has some quirks. This code compiles and runs just fine:

  foo ?
    bar : baz

…however, this fails compilation with Error: unexpected token: "?":

  foo
    ? bar : baz

It may also be worth noting that this is the shortest piece of code in the first 11 days. The problems are all different, so it would be hard to read too much into this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
ranges_str, ingredients_str = File.read("y25d05.txt").split("\n\n")

ranges = ranges_str.lines.map { |l| a, b = l.split('-').map(&.to_i64); a..b }
ingredients = ingredients_str.lines.map(&.to_i64)

result1 = ingredients.count { |i| ranges.any?(&.includes?(i)) }
puts "Result1: #{result1}"

sorted = ranges.sort_by(&.begin)
merged = sorted.each_with_object([] of Range(Int64, Int64)) do |r, acc|
  (l = acc.last?) && l.end >= r.begin ?
    (acc[-1] = l.begin..Math.max(l.end, r.end)) :
    (acc << r)
end

result2 = merged.sum { |r| r.end - r.begin + 1 }
puts "Result2: #{result2}"

Install Crystal and run#

The Crystal web site suggests that you run their installer script as root on your machine. I really don’t recommend this— running downloaded snippets of bash scripts on machines as non-root makes me uneasy, but running them as root is really problematic IMO. Use your package manager.

# I installed via Homebrew
brew install crystal

# Run random scripts as root!
# Maybe don't do this, but it's from the website.
# Use your package manager instead.
# curl -fsSL https://crystal-lang.org/install.sh | sudo bash

# Execute the code
crystal run d05.cr