Advent of Code 2022: Day 6

This problem is not too complicated, as it only requires reading a single line of input and scanning the line for a particular condition with the substring.

The condition is checked using character sets: the idea is to count the unique characters over a given substring, reporting if every character in that substring is unique. I do this by checking if the character set for that substring is the same size as the substring:

  if *cset(line[i+:size]) = size then {
    # return value
  }

The only novel piece of syntax I will mention is:

line[i+:size]

which is shorthand for

line[i:i+size]

and a handy way to say we want "size" elements starting from index "i".

Final Program

procedure main(inputs)
  local filename
  
  if *inputs = 1 then {
    filename := inputs[1]

    # Part 1 solution
    write("Part 1 marker is at: ", do_find(filename, 4))

    # Part 2 solution
    write("Part 2 marker is at: ", do_find(filename, 14))
  } else {
    write("Provide a filename of data")
  }
end

procedure do_find(filename, size)
  local file, marker
  
  file := open(filename) | stop("Could not open file")
  marker := find_marker(read(file), size)           # <1>
  close(file)

  return marker
end

procedure find_marker(line, size)
  local i
  
  every i := 1 to (*line-size) do {                 # <2>
    if *cset(line[i+:size]) = size then {           # <3>
      return i+size-1 # -1 for 0 index in answer      <4>
    }
  }
  return -1
end

  1. Process the single line from the input file
  2. Try substrings from the start, where each substring is the required size.
  3. Check the size of the character set.
  4. Return the index for the first "marker" found: unicon is 1-indexed, but the question requires 0-index, so subtract 1.

Page from Peter's Scrapbook, output from a VimWiki on 2024-12-02.