Today's challenge (Day 2) is a little bit more complicated than Day 1, of course, but not much: still something that SQL can handle very nicely. Let's see how.

The challenge in brief

The puzzle gives a "program", a string like this one:

yygoyovgyovyorrrorvovyv... 

Each letter is a waypoint, identified by a color, that a robot must reach. The colors are red (r), orange (o), yellow (y), green (g), blue (b), and violet (v), and the robot starts at a red waypoint. The catch is that the robot can only move forward, following the sequence roygbv. So if it is at g and the next waypoint is y, it can't go back: it has to go all the way around, g → b → v → r → o → y.

In other words, the roygbv sequence works like a ring (or a round robin, if you prefer): once you move past the last color, you start again from the first one. Part 1 asks for the total number of steps the robot takes.

Loading the input

This time the input is a single string, so there is no need to upload a file. I'm storing it in a session variable, which is super convenient for quick experiments like this one:

SET v = 'vbgyor'; 

Here I'm using a short sample string, so that it's easy to check the results by hand; to get the real answer, just replace it with the puzzle input.

Now I need to turn the string into a table with one row per color. My first thought was SPLIT_TO_TABLE, but it needs a delimiter, and here there is none. So I went the usual way: use ARRAY_GENERATE_RANGE (with FLATTEN) to create a list of numbers, and then SUBSTR to extract one letter for each of them:

CREATE OR REPLACE SCHEMA DAY02; CREATE OR REPLACE TEMPORARY TABLE DAY02.INPUT AS SELECT f.value::INT AS row_id, SUBSTR($v, row_id, 1) AS ch FROM TABLE(FLATTEN(input => ARRAY_GENERATE_RANGE(1, LENGTH($v) + 1))) f; 

Something I truly like about Snowflake, something tiny and simple if you want, but that makes my life easier as a developer, is the ability to use column aliases in the same SELECT statement where they are defined. So cool!

That's it: the program is now a table, and the puzzle is pretty much solved already.

Part 1

The idea is to turn each color into its position in the roygbv string, using the POSITION function, and then compute how many forward steps are needed to go from the current position to the next one. Since the program string tells the robot where it must go next, the current position is simply the previous row's position, which LAG gives for free. For the first row there is no previous row, so COALESCE makes it start at red, position 1:

CREATE OR REPLACE TEMPORARY TABLE DAY02.STEPS AS SELECT row_id, ch, POSITION(ch IN 'roygbv') AS next_pos, COALESCE(LAG(next_pos) OVER (ORDER BY row_id), 1) AS cur_pos, -- the colors are a ring: once you move past the last one, you start again from the first MOD(next_pos - cur_pos + 5, 6) + 1 AS distance FROM DAY02.INPUT; 

The interesting bit is the MOD expression, which is what makes the six colors behave like a ring. Here's why each piece is there:

  • next_pos - cur_pos goes from -5 to 5. A negative value means the target is "behind" the robot, so it must wrap around to reach it.
  • + 5 shifts that range to 0..10, so the value is never negative and I don't have to worry about how MOD handles negative numbers.
  • MOD(..., 6) folds 0..10 back into 0..5. This is the round-robin part.
  • + 1 shifts the result to 1..6.

This also handles repeated colors: when the next color is the same as the current one, the robot does a full lap and the result is 6 instead of 0. A few examples:

Move Difference Distance
r → o 1 1
r → v 5 5
v → r -5 1 (wraps)
b → o -3 3 (b → v → r → o)
b → b 0 6 (full lap)

I started with a more explicit IFF(next_pos - cur_pos <= 0, next_pos - cur_pos + 6, next_pos - cur_pos), which does exactly the same thing, but it didn't look elegant or easy to understand. I like the MOD version more: it says "ring" much more clearly, at least to me.

Now the answer is just a sum away:

SELECT SUM(distance) FROM DAY02.STEPS; 

And if you want to "see" how the robot is moving, to debug or just for fun, query the steps directly:

SELECT * FROM DAY02.STEPS ORDER BY row_id; 

Part 1, done.

Part 2

Part 2 looked much more complicated at first read: it asks to rearrange the program string so that the robot travels the longest possible distance. The puzzle gives this example:

The program vrvbvg could be rearranged into rvvvbg, a total distance of 33.

At first I was tricked into thinking that, for every row, I had to look at all the steps after the current position to find the furthest one, and then do the same for the next row, and so on. That's obviously a very resource-consuming process, as it is potentially O(n²). That didn't feel right.

Then I realized there is no need for that. The longest possible move is when the next waypoint has the same color as the current one: the robot has to do a full lap, 6 steps. So, to make the robot travel as far as possible, all the waypoints of the same color must be kept together.

But in which order should the groups come? The robot starts from red (r), so the red waypoints go first: each of them is a full lap. Then the groups should follow the roygbv sequence backwards: violet, then blue, then green, and so on. That way, every time the robot moves to a new group, the next color is just behind the current one, and it has to travel almost a full lap (5 steps) to reach it.

The easy way to get that order is to calculate, for each waypoint, how far its color is from r going forward (with red itself being a full lap, 6), and then sort the waypoints from the furthest to the closest. In the example above, that's exactly what turns vrvbvg into rvvvbg.

So the overall process becomes:

  1. Split the input string into rows, and transform each letter into its numerical position.
  2. For each row, calculate the distance from r (position 1), and use it to sort the table.
  3. Calculate the distance the robot has to travel, using the new sorting.
  4. Sum all the distances to get the final answer.

Since the steps come one after the other and are connected together, I decided to experiment with DYNAMIC TABLES.

Oh my, what a fantastic tool!

A dynamic table is basically a CTAS ("create table as select") that Snowflake can refresh automatically every time the data in the underlying tables changes. And dynamic tables can be built on top of other dynamic tables too! Very cool.

With that, the solution is very easy. First, I create a table with the original program string:

CREATE OR REPLACE SCHEMA DAY02; --cleanup all objects from Part 1 CREATE TABLE IF NOT EXISTS DAY02.RAW_INPUT (s STRING); INSERT INTO DAY02.RAW_INPUT VALUES ($v); 

Then the first step: generate one row per color and decode it to its numerical position:

CREATE OR REPLACE DYNAMIC TABLE DAY02.INPUT TARGET_LAG = DOWNSTREAM WAREHOUSE = COMPUTE_WH AS SELECT f.value::INT AS row_id, SUBSTR(r.s, f.value::INT, 1) AS ch, POSITION(ch IN 'roygbv') AS pos FROM DAY02.RAW_INPUT r, LATERAL FLATTEN(input => ARRAY_GENERATE_RANGE(1, LENGTH(r.s) + 1)) f; 

Now a dynamic table for step 2, which generates a new row_id to re-sort the program string so that it gives the furthest possible total distance:

CREATE OR REPLACE DYNAMIC TABLE DAY02.STEPS TARGET_LAG = DOWNSTREAM WAREHOUSE = COMPUTE_WH AS SELECT row_id AS original_row_id, ch, pos, MOD(pos + 5 - 1, 6) + 1 AS r_to_pos_distance, ROW_NUMBER() OVER (ORDER BY r_to_pos_distance DESC, row_id) AS row_id FROM DAY02.INPUT; 

Good old MOD helps here too. MOD(pos + 5 - 1, 6) + 1 is exactly the same formula used in Part 1, MOD(next_pos - cur_pos + 5, 6) + 1, with the current position fixed to red: cur_pos is always 1, and that's the - 1 in the code. So it gives the number of forward steps from r to each color, again wrapping around the ring: o is 1 step away, y 2, g 3, b 4, v 5, and r itself is a full lap, 6. Sorting by it in descending order puts red first, then violet, blue, and so on, which is just the order I need.

And the last step, which calculates the distance between each color and the next, exactly like in Part 1:

CREATE OR REPLACE DYNAMIC TABLE DAY02.MAX_STEPS TARGET_LAG = DOWNSTREAM WAREHOUSE = COMPUTE_WH AS SELECT row_id, ch, r_to_pos_distance, COALESCE(LAG(pos) OVER (ORDER BY row_id), 1) AS cur_pos, pos AS next_pos, MOD(next_pos - cur_pos + 5, 6) + 1 AS distance FROM DAY02.STEPS; 

Done! Now I can take a look at the new program string:

SELECT * FROM DAY02.MAX_STEPS ORDER BY row_id; 

And then just sum the distances to get the result of Part 2:

SELECT SUM(distance) FROM DAY02.MAX_STEPS; 

Of course, I first tested everything with the small sample programs provided by the challenge. To switch to the real program string, I just have to insert it into the base table:

INSERT OVERWRITE INTO DAY02.RAW_INPUT VALUES ($v); 

Thanks to INSERT OVERWRITE, I don't have to worry about deleting the existing data myself: OVERWRITE cleans the table automatically. Then I manually refresh the dynamic tables:

ALTER DYNAMIC TABLE DAY02.MAX_STEPS REFRESH; 

I went for a manual refresh because I didn't want the dynamic tables to keep monitoring my tables for changes (and thus consume credits), since I know there won't be any more changes once the challenge is done. With all of them set to TARGET_LAG = DOWNSTREAM, none of them refreshes on its own schedule, and refreshing MAX_STEPS takes care of the whole pipeline.

Part 2, done. Much less complicated than it looked at first read. 😄

Conclusion

Day 2 brought the exploration of quite a few very interesting Snowflake features: a session variable to hold the input, ARRAY_GENERATE_RANGE and FLATTEN to split a string with no delimiter into rows, column aliases used right in the same SELECT, and dynamic tables. Dynamic tables are really fantastic: they make building a pipeline super easy. Just write the SELECT for each step, and Snowflake takes care of the rest. Together with INSERT OVERWRITE to swap the input in one go, they helped a lot to make the code for Part 2 clean and very easy to understand.

And, on a more personal note, it looks like my ghost writer is working nicely. This post is exactly what I would have written myself...just better: better English, better flow, better sentences. And, most importantly, it took only a few minutes, not the hour I would have had to spend otherwise. 😅

See you tomorrow for Day 3, if I can keep up with the challenges!