What I learned (or recalled) thanks to Advent of Code
Language: Ruby
Day 1 TIL about
- Capturing groups and lookahead in regexp
In regular expressions, checking for overlapping strings (also known as overlapping matches) can be challenging because once a portion of the string is matched, it is consumed, and the regex engine moves forward in the input string. This means that the same portion of the string cannot be part of multiple matches.
input_string = "ababab"
pattern = /(?=(aba))/
matches = []
input_string.scan(pattern) do
matches << Regexp.last_match[1]
end
puts "Overlapping Matches: #{matches}"In this example, the regex pattern (?=(aba)) uses a positive lookahead to find occurrences of "aba" in the input string. The capturing group (aba) captures the matched portion.
Understanding negative and positive lookahead
Day 2
I should have not chosen that kind of data structure for storing the games. Probably using the colors as keys and associating game / hand / number might have ended up in fewer cycles.
I should have also found a way to initialize the keys that weren't present once so to avoid using .fetch all the time.
Day 3 If you want to add an element to a hash where the value is an empty array, you can write:
# Create an empty hash with an empty array as the default value
my_hash = Hash.new { |hash, key| hash[key] = [] }
# Add an element to the array in the hash
my_hash[:key1] << 'value1'
puts "Updated hash: #{my_hash}"Language: Ruby
Day 1 TIL about
.sort_by { |calories| -calories }Language: Ruby
Day 12 TIL about
Day 10 TIL about
- Flood Fill Algorithm
- use an hash to represent a matrix: for each element, the key is the coordinates, the value is the element itself
Day 7 TIL about
- Geometric median as minimizing distances
- sum of the first n numbers
Language: Ruby
Day 5 TIL about