You will write an algorithm that opens a file input.txt and follows a series of motions for the head of a rope. The rope comprises a series of knots that move per the rope's rules. You will track the movement of the tail of the rope throughout the motions.
Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far away from the tail, the tail is pulled toward the head. You can model the positions of the knots on a two-dimensional grid. Following a series of motions for the head, you will determine how the tail will move.
Your goal is to simulate a rope consisting of ten knots. One knot is the head of the rope and moves according to the series of motions. Each knot further down the rope follows the knot in front of it using the same rules above. You must keep track of the positions that the new tail, 9, visits.
You will compute the number of positions that the tail of the rope visits at least once. Encapsulate your answer in flag braces, i.e., flag{36}. Hint: The start point is arbitrary.
This is an exciting challenge. There are many ways to solve this, and my solution is not the best. I want to use this challenge to demonstrate my thought process in solving challenges. Although the most efficient solution may not come out the first time, that doesn't discount it as a working solution. If you want to practice writing more space-efficient solutions, I challenge you to track with a linked list and check for unique points before you enter them into the list. Ensure you don't inadvertently write an O(n^2 log n) solution; mine runs in O(n log n) time.
If you have spare time at the end, this is the time to polish solutions. I have submitted some weird solutions during competitions that worked but were far less efficient. I then spent time at the end or while I was polishing my write-ups to improve them.
Our goal is to track the number of unique points in the graph. A static array does this perfectly.
struct to represent a point on the graph.struct to represent a vector between two points. This will help us track the distance between each knot to see if we must move any knot to catch up.struct is not intuitive. I didn't think about making one until most of the way through my solution. I'll mention when I decided to add this to my solution. It is perfectly valid to solve it without one, but it made sense in my head at the time of writing.The current action plan is to read each line, perform the instruction, and then add the tail's position to the list. Then, we can sort the list of tail positions and count the unique points. If you're comfortable, try to solve this by checking for unique points before adding to the list, but watch for exponential time complexity.
We'll begin with the basics. We need to open the file and initialize the data.
1FILE* fp = fopen("input.txt", "r");
2if (fp == NULL)
3 exitIn this stage, we must also define our struct Point and struct Vector.
1struct Point {
2 int x;
3 int y;
4} Point_default = {0This syntax allows us to set a default value. Note that _default is not required, but I use this to distinguish that this object is the default for each struct. If I want to initialize a struct Point with the default, I can do the following:
struct Point point = Point_default;Now, we need to initialize the chain. The chain contains 10 points. We can initialize them all to the default value.
1struct Point* chain = malloc(10 * sizeof(struct Point));
2for (size_t i We also need to hold the list of points that the tail visits. As stated previously, we are using a static array to do this.
struct Point* tail_visits = malloc(20000 * sizeof(struct Point));We can use the same getline function used in the previous challenge to read each line. Since we know the length of each line and it doesn't matter to us, we don't need to store read.
while (getline(&line, &len, fp) != -1) { ... }Each line has two items: a direction and a number of steps. We can use strtok to parse each line.
1size_t count = 0;
2while (getline(&line, *&len, fp) != -1We need to process each instruction times times. For each instruction, we should determine which direction we travel and move the head of the chain. We must then adjust the rest of the chain to follow the head. Finally, we need to record the tail's position in the list.
1// read the directional changes
2size_t count = 0;
3while (getline(We make a call to adjust to move each link of the chain. I chose to make this a free function because we must do it for each chain link, and it makes the code a lot cleaner. This method must determine if the provided chain links are two far, then move the tail closer to the head.
Let's think about how we might do this. Below is a diagram of all the cases that you need to move the tail:
.TTT.
T...T
T.H.T
T...T
.TTT.I chose to break this down by side. The end state is that the tail is in one of four positions:
.....
..T..
.THT.
..T..
.....Given each side, we are guaranteed one move for the tail: moving inward. Then, based on the perpendicular direction, we see if we need to move laterally to reach this position. We use a struct Vector to represent the distance between head and tail. We use this difference to determine how we must move.
1struct Point adjust(struct Point head, struct Point tail)
2{This completes the processing of the instructions.
Now that our data is complete and processed, we must compute the flag. The flag is the number of unique positions that the tail visited. We can do this by sorting the list of points the tail visited. If duplicates are in the list, they will be adjacent. As we iterate across the list, we'll check for unique lists.
First, let's sort the data.
qsort(tail_visits, count, sizeof(struct Point), compare);We need to define the comparison function. We'll arbitrarily compare the x values first, then the y values.
1int compare(const void* a, const void* b)
2{
3 Once our data is sorted, we can iterate and count the number of unique points. We'll define a function called equal that returns 1 if two points are equal and 0 otherwise.
1int equal(struct Point a, struct Point b)
2{
3 return (a.x ==Then, we check if adjacent points are equal and count the unique points.
1size_t visited = 1;
2for (size_t i = 1; i < count; ++i) {
3We can use this to print the flag! Remember to free your memory.
1printf("flag{%zd}\n", visited);
2
3free(chain);
4free(tail_visits);The full solution is below:
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5struct Point {
6 int x;
7 int y;
8} Point_default = {0, 0};
9
10struct Vector {
11 int x;
12 int y;
13} Vector_default = {0, 0};
14
15struct Vector build_vector(struct Point head, struct Point tail)
16{
17 struct Vector* ret = malloc(sizeof(struct Vector));
18 ret->x = head.x - tail.x;
19 ret->y = head.y - tail.y;
20 return *ret;
21}
22
23int compare(const void* a, const void* b)
24{
25 struct Point* first = (struct Point*)a;
26 struct Point* second = (struct Point*)b;
27
28 if (first->x < second->x)
29 return -1;
30 else if (first->x > second->x)
31 return 1;
32 else {
33 if (first->y < second->y)
34 return -1;
35 if (first->y > second->y)
36 return 1;
37 else
38 return 0;
39 }
40}
41
42int equal(struct Point a, struct Point b)
43{
44 return (a.x == b.x && a.y == b.y);
45}
46
47struct Point adjust(struct Point head, struct Point tail)
48{
49 struct Vector distance = build_vector(head, tail);
50
51 // adjust tail location based on vector
52 if (distance.x == 2) {
53 ++tail.x;
54 if (distance.y == 1)
55 ++tail.y;
56 if (distance.y == -1)
57 --tail.y;
58 }
59 if (distance.x == -2) {
60 --tail.x;
61 if (distance.y == 1)
62 ++tail.y;
63 if (distance.y == -1)
64 --tail.y;
65 }
66 if (distance.y == 2) {
67 ++tail.y;
68 if (distance.x == 1)
69 ++tail.x;
70 if (distance.x == -1)
71 --tail.x;
72 }
73 if (distance.y == -2) {
74 --tail.y;
75 if (distance.x == 1)
76 ++tail.x;
77 if (distance.x == -1)
78 --tail.x;
79 }
80
81 return tail;
82}
83
84int main(void)
85{
86 FILE* fp = fopen("input.txt", "r");
87 if (fp == NULL)
88 exit(EXIT_FAILURE);
89
90 char* line = NULL;
91 size_t len = 0;
92
93 // build the chain
94 struct Point* chain = malloc(10 * sizeof(struct Point));
95 for (size_t i = 0; i < 10; ++i)
96 chain[i] = Point_default;
97
98 // list of points
99 struct Point* tail_visits = malloc(20000 * sizeof(struct Point));
100
101 // read the directional changes
102 size_t count = 0;
103 while (getline(&line, &len, fp) != -1) {
104 char dir = strtok(line, " ")[0];
105 int times = atoi(strtok(NULL, " "));
106 while (times-- > 0) {
107 // adjust the head coordinate
108 if (dir == 'U')
109 ++chain[0].y;
110 else if (dir == 'D')
111 --chain[0].y;
112 else if (dir == 'L')
113 --chain[0].x;
114 else if (dir == 'R')
115 ++chain[0].x;
116 else {
117 printf("Bad\n");
118 exit(EXIT_FAILURE);
119 }
120
121 // adjust the links of the chain
122 for (size_t i = 0; i < 9; ++i)
123 chain[i + 1] = adjust(chain[i], chain[i + 1]);
124
125 // record tail location in list
126 tail_visits[count++] = chain[9];
127 }
128 }
129
130 // sort the list of points
131 qsort(tail_visits, count, sizeof(struct Point), compare);
132
133 // count non-duplicates
134 size_t visited = 1;
135 for (size_t i = 1; i < count; ++i) {
136 if (!equal(tail_visits[i], tail_visits[i - 1])) {
137 ++visited;
138 }
139 }
140
141 printf("flag{%zd}\n", visited);
142
143 exit(EXIT_SUCCESS);
144}