Fun programming puzzles to practice your problem solving skills, come and challenge
This article is from the emergence of code: solving your problems with Python by Yuchuan.
Code puzzles are designed to be accessible to anyone interested in solving problems. You do not need a strong computer science background to participate. Instead, the advent of code is a great place to learn new skills and test new Python features.
Programming confusion?
Dealing with puzzles seems like a waste of your available programming time. After all, you don’t really seem to be producing anything useful or advancing your current project.
However, spending some time practicing programming puzzles has several benefits:
-
Programming challenges are often more specific and informative than your regular work tasks. They give you the opportunity to practice logical thinking on simpler problems than you would normally have to deal with in your daily work.
-
You can often challenge yourself with a few similar puzzles. This allows you to build procedural memory, like muscle memory, and gain experience building certain types of code.
-
Puzzles are often designed with a view to solutions. They enable you to learn about and apply tried and tested algorithms that are an important part of any programmer’s toolbox.
-
For some puzzle solutions, even the most powerful supercomputers can be too slow if the algorithms are inefficient. You can analyze the performance of your solution and gain experience to help you understand when a simple approach is fast enough and when a more optimized program is needed.
-
Most programming languages are well suited to solving programming puzzles. This gives you a good opportunity to compare different programming languages for different tasks. Puzzles are also a great way to learn about a new programming language or try out some of the latest features of your favorite language.
Best of all, challenging yourself with programming puzzles is often fun! When you add everything up, it’s very helpful to have some time for puzzles.
Explore options for solving programming puzzles online
Fortunately, there are many web sites where you can find programming puzzles and try to solve them. These sites often differ in the type of problems they have, the way you submit solutions, and the type of feedback and community they can provide. Therefore, you should take some time to look around and find the ones that appeal to you the most.
In this tutorial, you’ll learn about code coming, including what puzzles you can find there and what tools and tricks you can use to solve them. However, there are other places where you can start solving programming puzzles:
-
Exercism has many different paths to learning in different programming languages. Each learning track offers mini-tutorials on different programming concepts, coding challenges, and mentors to give you feedback on solutions.
-
Euler’s plan has been around for a long time. The site offers hundreds of puzzles, often in the form of mathematical problems. You can solve problems in any programming language, and once you’ve solved the puzzle, you have access to the community thread, where you can discuss your solution with others.
-
Code Wars offers a number of coding challenges they call KatAs. You can use many different programming languages to solve puzzles with built-in editors and automated tests. After that, you can compare your solution to others’ solutions and discuss strategies in the forum.
-
If you’re looking for a job, HackerRank has great features. They offer certifications in a number of different skills, including problem solving and Python programming, as well as a workboard that allows you to demonstrate your puzzle solving skills in job applications.
There are many other sites where you can practice your puzzle solving skills. For the rest of this tutorial, you’ll focus on what Advent of Code must provide.
Get Ready for Code: 25 New Christmas puzzles
Now it’s time for code! It was founded by Eric Wastl in 2015. Since then, a new emergence calendar with 25 new programming puzzles has been released every December. Over the years, puzzles have become more and more popular. Since 2020, more than 170,000 people have solved at least one of these problems.
** Note: ** Traditionally, advent calendars are calendars used to count advent days while waiting for Christmas. Over the years, advent calendars have become more commercial and lost some of their Christian ties.
Most Advent calendars begin on December 1 and end on December 24 (Christmas Eve) or December 25 (Christmas Day). Today, there are all kinds of Advent calendars, including Lego calendars, tea calendars and makeup calendars.
In the traditional Advent calendar, you open a door each day to reveal the contents. The Advent of Code mimics this by having you open a puzzle every day from December 1 to December 25. For each puzzle you solve, you get gold stars, and you can keep those stars.
In this section, you’ll become more familiar with Advent of Code and get a glimpse of your first puzzle. Later, you’ll learn more about how to solve these puzzles and practice solving some of them yourself.
The appearance of code puzzles
The Advent of Code is an online Advent calendar that releases a new puzzle each day from December 1 to December 25. Each puzzle is available at midnight EASTERN time. Advent of Code puzzles have several typical characteristics:
-
Each puzzle is made up of two parts, but the second part is not shown until you have completed the first.
-
For each section you complete, you will receive a gold star (⭐). This means that if you solve all your problems in a year, you can earn two stars and fifty stars a day.
-
Everyone’s puzzle is the same, but you’ll need to solve it based on personalized input from the Advent of Code website. This means that your answer to a puzzle will be different from everyone else’s, even if you use the same code to calculate it.
You can enter global competitions to be the first to solve every problem. However, it is usually crowded with highly skilled, competitive programmers. It can be more fun if you use Code of Code as an exercise for yourself, or if you start small friendly contests with your friends and colleagues.
To understand how code problems work, consider the first day of 2020 puzzle:
Before you leave, the accounting genie just needs you to correct your expense report (your jigsaw input); Obviously, something doesn’t quite add up.
Specifically, they want you to find two entries that add up to 2020 and then multiply the two numbers.
Every year, there’s a really silly backstory that ties the puzzle together. The story of 2020 describes you trying to go away and have a well-deserved vacation because you’ve saved Christmas for years in a row. The story usually has no effect on the puzzle, but it’s still fun to follow.
Between the plot elements of the story, you’ll find the puzzle itself. In this example, you look for two entries in the puzzle input that add up to 2,020. After describing the explanation of the problem, you will usually find an example that shows the calculation you need to perform:
For example, suppose your expense report contains the following:
1721
979
366
299
675
1456
Copy the code
In this list, the two entries add up to 1721 and 299 for 2020. Multiplying them produces 1721 * 299 = 514,579, so the correct answer is 514,579.
This example shows you the answer to this particular list of numbers. If you’re going to start solving this puzzle, now you’ll start thinking about how to find these two entries in any list of significant numbers. Before delving into this conundrum, however, you’ll explore how to use the Advent of Code site.
How to participate in the emergence of code
You’ve seen examples of code problems. Next, you’ll learn how to submit an answer. You will never submit any code to solve a puzzle. You simply submit the answer, usually a numeric or text string.
Typically, you will follow a series of steps to solve a problem on a web site:
-
Go to Advent of Code. You can do this using credentials from another service, such as GitHub, Google, Twitter, or Reddit.
-
Read the puzzle text and pay special attention to the given example. You should make sure you understand the solution for sample data.
-
Download personalized input for the puzzle. You will need this input to find the unique answer to the question.
-
Write your solution. This is the fun part, and you’ll get plenty of practice throughout the rest of the tutorial.
-
Enter your answer to the puzzle on the puzzle page. If your answer is correct, you receive a gold star and open the second part of the puzzle.
-
Repeat steps 2 through 4 for the second part of the puzzle. Part 2 is similar to Part 1, but it usually adds a few twists that require you to adjust your code.
-
Enter your second answer on the puzzle page to get a second star and complete the puzzle.
Remember, you’re not submitting any code — just your puzzle answers. This means that code problems can be solved in any programming language. Many people use Advent of Code to practice and learn a new programming language. Eric Wastl, founder of the Advent of Code, gave a talk in 2019 about the diverse backgrounds and motivations of those involved.
Note: There is an Advent of Code leaderboard. In general, you should ignore this leaderboard! It only shows who submitted the top 100 solutions after the puzzle was opened. You need a lot of preparation, dedication, and experience with competitive programming to get to the top.
Instead, you should look at private leaderboards. These are available after you log in, and they give you the opportunity to invite your friends and colleagues to a more relaxed community. You can choose to be based on either scoring your private leaderboards when puzzles are solved or simply the number of puzzles people have solved.
You can also link your name in private leaderboards to your GitHub account so you can share your solution with friends. Once logged in, you can do so by clicking Settings in the Menu of the Advent of Code site.
Advent of Code is completely free to use, but you can still support the project in several different ways:
-
You can share information about Advent of Code on your social media to promote it.
-
You can help others by participating in the R/Adventofcode subreddit or other forums.
-
You can invite your friends to join Advent of Code to share your results on private leaderboards.
-
You can make a donation to Advent of Code. If you do, then you will see a **AoC++** badge next to your name on the site.
In the sections that follow, you’ll see some suggestions on how to prepare Python to solve problems in your code. There’s also a great list where you can view links to many different resources related to Advent of Code, including many other people’s solutions.
Solve code occurrences in Python
Code of Code has become the highlight of the year for many coders around the world. In 2020, more than 170,000 people submitted their solutions. More than 380,000 programmers have participated in Advent of Code since its launch in 2015. Many of them use Python to solve difficult problems.
Well, now it’s your turn! Head over to the Advent of Code website to check out the latest puzzles. Then, return to this tutorial for some tips and help to get started using Python to troubleshoot code problems.
The anatomy of the puzzle
In this section, you’ll explore typical profiling of code that presents a problem. In addition, you’ll learn about the tools you can use to interact with it.
Each Advent of Code puzzle is divided into two parts. When you start working on the puzzle, you will only see the first part. Once you have submitted the correct answer for part 1, part 2 will be unlocked. This is usually the turning point for the problem you solved in Part 1. Sometimes you’ll find it necessary to refactor your solution from the first part, and sometimes you can quickly solve the second part based on what you’ve already done.
Both parts always use the same puzzle input. You can download puzzle input from the puzzle page of the day. You will find a link after the puzzle description.
** Note: ** As mentioned earlier, your jigsaw input is personalized. This means that if you discuss a solution with someone else, their final answer may be different from yours.
All operations required to submit a puzzle solution (except the actual puzzle solving) can be performed on the Advent of Code website. You should use it to submit your first solution so you can familiarize yourself with the process.
Later, you can use a variety of tools to organize your Advent of Code setup and increase productivity. For example, you can download data using the advent-of-code-data package. Here is a Python package that can be installed using PIP:
$ python -m pip install advent-of-code-data
Copy the code
You can use the advent of code-data’s AOCD tool to download specific jigsaw input sets on the command line. Another interesting possibility is to automatically download and cache your personalized puzzle inputs in your Python code:
>>>
>>> from aocd.models import Puzzle
>>> puzzle = Puzzle(year=2020, day=1)
>>> # Personal input data. Your data will be different.
>>> puzzle.input_data[:20]
'1753\n1858\n1860\n1978\n'
Copy the code
You need to set the session ID in the environment variable or file before you can use the advent of code-data. You’ll find an explanation of this in the documentation. If you are interested, you can also submit your solution and view your previous answers using advent of code-data or AOCD.
As part of the puzzle text, you’ll also find one or more examples, which are often calculated from smaller data than your personalized input data. Before you start coding, you should read through these examples and make sure you understand what you are being asked to do.
You can use these examples to set up tests for your code. One way is to run your solution manually on the sample data and verify that you get the answers you expect. Alternatively, you can use a similar tool, PyTest, to automate the process.
Note: Test-driven development (TDD) is the process of writing tests before implementing the code. Since Advent of Code gives you the expected answers to small examples, it gives you the perfect opportunity to try test-driven development on your own.
You’ll learn more about TDD later when you try to solve some of the puzzles yourself.
You can solve all the Advent of Code puzzles using simple Python and the standard library. However, there are some packages that can help you organize your solution:
-
Advent -of-code-data can download your input data and submit your solution.
-
Pytest can automatically check for solutions on sample data.
-
Parse can parse strings with a simpler syntax than regular expressions.
-
Numpy effectively computes numeric arrays.
-
Colorama can animate your solution in the terminal.
If you create a virtual environment and install these packages, you will have a very reliable toolbox for your Advent of Code adventures. Later, you’ll see examples of how you use Parse, Numpy and Colorama to solve puzzles.
Structure of the solution
In the previous section, you became familiar with how to read and understand the Advent of Code puzzle. In this section, you’ll learn how to resolve these issues. You don’t have to do a lot of setup before you solve the “code appears” conundrum.
Have you ever wondered how to solve a problem you’ve seen before? Recall that you are looking for the product of two numbers in a list that add up to 2,020. Before continuing, consider — and perhaps write code — how to find which two entries in the following list add up to 2,020:
numbers = [1721, 979, 366, 299, 675, 1456]
Copy the code
The following script shows one way to solve the first part of the Day 1 puzzle of 2020:
1for num1 in numbers:
2 for num2 in numbers:
3 if num1 < num2 and num1 + num2 == 2020:
4 print(num1 * num2)
Copy the code
The nested for loop looks for all combinations of two numbers from the list. The test in line 3 is actually a little more complicated than it needs to be: you just need to test if the numbers add up to 2,020. However, num2 can avoid finding a solution twice by adding the condition that num1 should be less than.
In this example, a solution looks like num1 = 1721 and num2 = 299, but since you can add numbers in any order, it means also num1 = 299 and num2 = 1721 form the solution. With additional checks, only the latter combination is reported.
Once you have this solution, you can copy your personalized input data into the Numbers list and calculate your puzzle answers.
** Note: ** there are more efficient ways to calculate this answer than trying all the possibilities. However, it’s usually a good idea to start with the basics. To quote Joe Armstrong:
Make it work, then make it beautiful, then if you really, really have to, make it fast. Ninety percent of the time, if you make it pretty, it’s already fast. So really, just make it pretty! “– Joe Armstrong
Now that you’ve seen an effective solution to the puzzle, can you do it beautifully?
As you solve more of the puzzle, you may start to find it annoying to copy data into code and rewrite it as valid Python. Similarly, adding functions to your code gives you more flexibility. For example, you can use them to add tests to your code.
Python has many powerful string parsing capabilities. In the long run, it’s better to keep the input data at download time and let Python parse it into usable data structures. In fact, it is often beneficial to split your code into two functions. One function will parse the string input, and the other will solve the puzzle. You can rewrite your code based on these principles:
1# aoc202001.py
2
3import pathlib
4import sys
5
6def parse(puzzle_input):
7 """Parse input"""
8 return [int(line) for line in puzzle_input.split()]
9
10def part1(numbers):
11 """Solve part 1"""
12 for num1 in numbers:
13 for num2 in numbers:
14 if num1 < num2 and num1 + num2 == 2020:
15 return num1 * num2
16
17if __name__ == "__main__":
18 for path in sys.argv[1:]:
19 print(f"\n{path}:")
20 puzzle_input = pathlib.Path(path).read_text().strip()
21
22 numbers = parse(puzzle_input)
23 print(part1(numbers))
Copy the code
In lines 12 through 15, you will identify your previous solution. First, you’ve wrapped it in a function. This makes it easier to add automated tests to your code later. You also added a parse() function that converts a string line into a list of numbers.
In line 20, you use pathlib to read the contents of the file as text and remove any trailing blank lines. The loop sys.argv gives you all the file names you entered on the command line.
These changes give you more flexibility as you work with your solution. Suppose you have stored your sample data in a file named example.txt and your personalized input data in a file named input.txt. You can then run your solution on either or both of them by providing their names on the command line:
$ python aoc202001.py example.txt input.txt
example.txt:
514579
input.txt:
744475
Copy the code
514579 is indeed the answer to the question when using the sample input data. Keep in mind that your solution for personalizing input data will be different from the solution shown above.
Now it’s time for the Advent of Code to show it off! Go to the 2020 Advent of Code Calendar and find the puzzle for Day 1. If you haven’t already, download the solution to enter the data and calculate the puzzle. Then, enter your solution on the web site and click Submit.
Starting template
As you saw above, code puzzles appear to follow a structure. Therefore, it makes sense to create a template for yourself that you can use as a starting point when you start writing your solution. How much structure you want in such a template is a matter of personal taste. First, you’ll explore an example template based on the principles you saw in the previous section:
1# aoc_template.py
2
3import pathlib
4import sys
5
6def parse(puzzle_input):
7 """Parse input"""
8
9def part1(data):
10 """Solve part 1"""
11
12def part2(data):
13 """Solve part 2"""
14
15def solve(puzzle_input):
16 """Solve the puzzle for the given input"""
17 data = parse(puzzle_input)
18 solution1 = part1(data)
19 solution2 = part2(data)
20
21 return solution1, solution2
22
23if __name__ == "__main__":
24 for path in sys.argv[1:]:
25 print(f"{path}:")
26 puzzle_input = pathlib.Path(path).read_text().strip()
27 solutions = solve(puzzle_input)
28 print("\n".join(str(solution) for solution in solutions))
Copy the code
The template has separate functions for parsing the input and solving the two parts of the puzzle. You don’t need to touch lines 15 through 27 at all. They take care of reading text from input files, asking parse(), part1() and part2() before reporting to the solution console.
You can create a similar template to test your solution.
** Note: ** As mentioned earlier, sample data is useful for creating tests because they represent known data with corresponding solutions.
The following template pyTest is used as a test runner. It has three different tests to prepare each function parse(), part1() and Part2 () :
1# test_aoc_template.py
2
3import pathlib
4import pytest
5import aoc_template as aoc
6
7PUZZLE_DIR = pathlib.Path(__file__).parent
8
[email protected]
10def example1():
11 puzzle_input = (PUZZLE_DIR / "example1.txt").read_text().strip()
12 return aoc.parse(puzzle_input)
13
[email protected]
15def example2():
16 puzzle_input = (PUZZLE_DIR / "example2.txt").read_text().strip()
17 return aoc.parse(puzzle_input)
18
[email protected](reason="Not implemented")
20def test_parse_example1(example1):
21 """Test that input is parsed properly"""
22 assert example1 == ...
23
[email protected](reason="Not implemented")
25def test_part1_example1(example1):
26 """Test part 1 on example input"""
27 assert aoc.part1(example1) == ...
28
[email protected](reason="Not implemented")
30def test_part2_example2(example2):
31 """Test part 2 on example input"""
32 assert aoc.part2(example2) == ...
Copy the code
You will see an example of how you use this template later. Until then, you should note the following:
-
As shown in line 1, you should name your files with the test_ prefix pyTest.
-
Similarly, each test is implemented in a function named with the test_ prefix. You can see these examples in lines 20, 25, and 30.
-
You should change the import in line 5 to import your solution code.
-
This template assumes that sample data is stored in example2.txt in files named example1.txt and example1.txt.
-
When you are ready to start testing, you should remove the skip flags in lines 19, 24, and 29.
-
You need to… Fill in the ellipsis () for lines 22, 27, and 32 based on the sample data and the corresponding solution.
For example, if you were to adapt this template as a rewrite solution for part 1 of the day 1 2020 puzzle from the previous section, you would need to create a file example1.txt containing the following:
1721
979
366
299
675
1456
Copy the code
Next, you will remove the skip flags for the first two tests and implement them as follows:
def test_parse_example1(example1):
"""Test that input is parsed properly"""
assert example1 == [1721, 979, 366, 299, 675, 1456]
def test_part1_example1(example1):
"""Test part 1 on example input"""
assert aoc.part1(example1) == 514579
Copy the code
Finally, you need to ensure that you are importing your solution. If you used filename aoc202001.py, you should change line 5 to import aOC202001:
5import aoc202001 as aoc
Copy the code
You will then run PyTest to check your solution. If you implement your solution correctly, you will see something like this:
$ pytest ====================== test session starts ===================== collected 3 items test_aoc202001.py .. S [100%] = = = = = = = = = = = = = = = = = 2 passed, 1 skipped in 0.02 s = = = = = = = = = = = = = = = = =Copy the code
Note that… The first two points (alpha) s. They represent two tests that passed. If the test fails, you’ll see F instead of every point, along with a detailed explanation of what went wrong.
Tools like Cookiecutter and Copier can work with such templates more easily. If you have Copier installed, you can use templates similar to the one you see here by running the following command:
$ copier gh:gahjelle/template-aoc-python advent_of_code
Copy the code
This will set the template for a specific puzzle in a subdirectory of the advent_OF_code directory on your computer.
Resolution strategy
Code puzzles come in a variety of ways. As the calendar progresses, you will solve many different problems and discover many different strategies for solving them.
Some of these strategies are very generic and can be applied to any puzzle. If you find yourself stuck on a puzzle, you can try to solve the following:
-
Reread the instructions. The emergence of code puzzles is often very explicit, but some of them can contain a lot of information. Make sure you don’t miss important pieces of the puzzle.
-
Actively use sample data. Make sure you understand how these results are achieved, and check that your code can reproduce the examples.
-
Some puzzles may involve some. Break the problem down into smaller steps and implement and test each step individually.
-
If your code works for sample data but not for your personalized input data, you can build additional test cases based on numbers you can manually calculate to see if your code covers all the extremes.
-
If you’re still stuck, contact your friends and other puzzle solvers on some of the forums dedicated to code appearances and ask them for tips on how to solve the puzzle.
As you do more and more puzzles, you’ll start to recognize some recurring general puzzles.
Some puzzles involve text and passwords. Python has several powerful tools for working with text strings, including many string methods. To read and parse strings, it helps to know the basics of regular expressions. However, you can often use third-party Parse libraries as well.
For example, suppose you have the string “shiny gold bags contain 2 dark red bags.” and you want to parse the relevant information. You can use Parse and its schema syntax:
>>>
>>> import parse
>>> string = "shiny gold bags contain 2 dark red bags."
>>> pattern = "{outer_color} bags contain {num:d} {inner_color} bags."
>>> match = parse.search(pattern, string)
>>> match.named
{'outer_color': 'shiny gold', 'num': 2, 'inner_color': 'dark red'}
Copy the code
Behind the scenes, Parse builds a regular expression, but you use a simpler syntax similar to that used by F-strings.
In some of these text problems, you are explicitly required to use code and parsers, often to build small custom assembly languages. After parsing the code, you usually need to run the given program. In practice, this means that you have built a small state machine that can track its current state, including the contents of its memory.
You can use classes to keep state and behavior together. In Python, data classes are great for setting up state machines quickly. The following example shows an implementation of a small state machine that can handle two different instructions:
1from dataclasses import dataclass
2
3@dataclass
4class StateMachine:
5 memory: dict[str, int]
6 program: list[str]
7
8 def run(self):
9 """Run the program"""
10 current_line = 0
11 while current_line < len(self.program):
12 instruction = self.program[current_line]
13
14 # Set a register to a value
15 if instruction.startswith("set "):
16 register, value = instruction[4], int(instruction[6:])
17 self.memory[register] = value
18
19 # Increase the value in a register by 1
20 elif instruction.startswith("inc "):
21 register = instruction[4]
22 self.memory[register] += 1
23
24 # Move the line pointer
25 current_line += 1
Copy the code
The two instructions set and inc perform analysis and internal processing. Run (). Note that the types in lines 5 and 6 suggest an updated syntax, which only works with Python 3.9 and later. If you are using older versions of Python, you can use importDict and Listfromtyping instead.
To run your state machine, you first initialize it with initial memory and load the program into the machine. Next, you call.run(). After the program is complete, you can check.memory to see the new state of the machine:
>>>
>>> state_machine = StateMachine(
... memory={"g": 0}, program=["set g 44", "inc g"]
... )
>>> state_machine.run()
>>> state_machine.memory
{'g': 45}
Copy the code
The program first sets g to the value of 44 and then increments it so that its final value is 45.
Some interesting puzzles involve grids and mazes. If your grid has a fixed size, you can use NumPy to get a valid representation of it. Mazes are often good for visualization. You can draw directly in your terminal using Colorama:
import numpy as np
from colorama import Cursor
grid = np.array(
[
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 0, 1],
[1, 0, 0, 2, 1],
[1, 1, 1, 1, 1],
]
)
num_rows, num_cols = grid.shape
for row in range(num_rows):
for col in range(num_cols):
symbol = " #o"[grid[row, col]]
print(f"{Cursor.POS(col + 1, row + 2)}{symbol}")
Copy the code
This script shows an example of storing a grid using a NumPy array and then using cursor.posFROM Colorama to position the Cursor in a terminal to print out the grid. When you run this script, you should see the following output:
#####
# #
### #
# o#
#####
Copy the code
Visualizing your code at run time can be fun, and can also give you some great insights. It can also be a valuable help when you’re debugging and don’t know much about what’s going on.
So far in this tutorial, you’ve gotten some general tips on how to use Advent of Code puzzles. In the sections that follow, you’ll get clearer information and solve two of the puzzles from earlier years.
Code Practices: Day 1 of 2019
The first puzzle you’ll try to solve on your own is day 1 of 2019, called the tyranny of the Rocket Equation. This is a typical day 1 problem because the solution is not very complicated. This is a good exercise to get used to the way Advent of Code works and check that your environment is set up correctly.
Part 1: Puzzle description
In the 2019 storyline, you’ll rescue Santa Trapped on the edge of the solar system. In the first puzzle, you are preparing to launch a rocket:
The elves quickly load you into the spaceship and prepare you for launch.
In the first Go/No Go poll, every Elf was Go until Fuel counter-upper. They have not yet determined the amount of fuel needed.
The fuel required to launch a given module is based on its mass. Specifically, to find the fuel needed for the module, take its mass, divide it by 3, round it down, and subtract 2.
Example data is as follows:
-
For the mass 12, divide by 3 and round down to get 4, and then subtract 2 to get 2.
-
For mass 14, dividing by 3 and rounding still yields 4, so the fuel required is also 2.
-
For a mass of 1969, the fuel required was 654.
-
For a mass of 100756, the fuel required is 33,583.
You need to calculate the total fuel requirements of the spacecraft:
Fuel counter-upper needs to know the total Fuel demand. To find it, calculate the fuel required for the mass of each module (your puzzle input) separately, and then add all the fuel values together.
What is the total fuel requirement for all the modules on your spacecraft?
Now it’s time to try and solve the puzzle yourself! It may be most fun to download your personalized input data and check out your solution on Advent of Code so you can earn stars. However, if you’re not ready to log on to Advent of Code, feel free to solve puzzles based on the sample data provided above.
Part 1: Solutions
After completing the puzzle and earning the stars, you can expand the fold to see a discussion of puzzle solutions:
Day 1 of 2019 solution, Part 1 shows hide
You have now solved the first part of the puzzle. However, before moving on to the second part of the puzzle, the next section will show you how to use the template you saw earlier when solving this problem.
Part 1: A solution using templates
Expand the foldout below to see another solution to the first part of the day 1 code problem in 2019 — this time using the template you saw earlier to organize your code and simplify your tests:
The templated solution for Part 1 of Day 1 2019 shows hide
You can now move on to the second part of the puzzle. Are you ready to turn it around?
Part 2: Puzzle description
Each Advent of Code puzzle consists of two parts, and the second part is shown only after you have solved the first. The second part is always related to the first part and will use the same input data. However, you may often need to rethink your approach to solving the first half of the puzzle in order to consider the second half.
Expand the collapsed block below to see the second part of the code puzzle from Day 1 of 2019:
Day 1 of 2019, Part 2 shows hide
You’ll see a possible solution for Part 2 in the next section. But first try to solve the puzzle yourself. If you need a start prompt, expand the box below:
Tips for day 1 of 2019, Part 2 shows hide
How did you do that? Is your rocket ready to launch?
Part 2: Solutions
This section shows how to solve the second part, continuing with the template seen above:
Day 1 of 2019 solution, Part 2 shows hide
A: congratulations! You have now solved the entire Advent of Code puzzle. Are you ready for something more challenging?
Code Practices: Day 5 of 2020
The second puzzle you’ll try to solve is the one on day 5 of 2020, called Binary Boarding. This puzzle is more challenging than the previous one, but the final solution doesn’t require a lot of code. First look at the puzzle instructions in part 1.
Part 1: Puzzle description
In 2020, you’re on your way to the vacation destination you deserve. On day 5, when trouble starts coming, you’ll be boarding:
You board your plane only to find a new problem: you’ve lost your boarding pass! You’re not sure which seat is yours, and all the flight attendants are busy dealing with the sudden rush of people passing through passport control.
You write a quick program that uses your phone’s camera to scan all nearby boarding passes (your jigsaw input); Maybe you can find your seat through the elimination process.
The airline uses binary partitions to arrange seats, rather than zones or groups. A seat may be designated FBFBBFFRLR, where F means “forward”, B means “back”, L means “left”, and R means “right”.
The first seven characters will be F or B; These specify exactly one plane on line 128 (numbered 0 through 127). Each letter tells you which half of the area a given seat is located in.
Start with the entire row list; The first letter indicates whether the seat is in the front (0 through 63) or behind (64 through 127). The next letter indicates which half of the area the seat is in, and so on, until you have only one row left.
For example, consider only the first seven characters FBFBBFFRLR:
-
First consider the entire range, rows 0 through 127.
-
F means to take the lower half, keeping line 0 through 63.
-
B means take the top half and keep line 32 through 63.
-
F means to take the lower half, keeping line 32 through 47.
-
B means take the top half and keep line 40 through 47.
-
B keeps line 44 through 47.
-
F keeps line 44 through 45.
-
FinalF retains the lower of the two, Row44.
The last three characters will be L or R; These specify exactly one of the eight rows of seats on the plane (numbered 0 through 7). Repeat the same process, this time in just three steps. L represents the lower part and R represents the upper part.
For example, consider only the last three characters FBFBBFFRLR:
-
First consider the entire range, columns 0 through 7.
-
R means take the top half, keeping column 4 through 7.
-
L means to take the lower half, keeping column 4 through 5.
-
FinalR reserves the higher of the two, column5.
Therefore, decoding FBFBBFFRLR shows it is the seat of Row 44, column5.
Each seat also has a unique seat ID: multiply rows by 8, then add columns. In this example, the seat has ID 44 * 8 + 5 = 357.
Here are some other boarding passes:
-
BFFFBBFRRR: Row 70, column 7, seat ID 567.
-
FFFBBBFRRR: row 14, column 7, seat ID 119
-
BBFFBBFRLL: Row 102, column 4, seat ID 820.
As a sanity check, check your boarding pass list. What is the maximum seat ID on your boarding pass?
There’s a lot of information in the puzzle instructions! Most of the content, however, deals with how binary space partitions work for that particular airline.
Now, try to solve the problem yourself! Keep in mind that the transition from boarding pass specifications to seat IDS is not as complicated as it first seems, if you think about it from the right perspective. If you find yourself having trouble with this section, expand the box below for hints on how to get started.
Hints for day 5 of 2020, Part 1 shows hide
Once the solution is complete, check out the next section for a discussion of the puzzle.
Part 1: Solutions
Now that you’ve tried it out for yourself, you can expand the following block to see one way to solve the puzzle:
Day 5 of 2020 solutions, Part 1 shows hide
It’s time for the second piece of the puzzle. Can you board the plane?
Part 2: Puzzle description
Once you have the second piece of the puzzle ready, expand the following:
Day 5 of 2020, Part 2 shows hide
Take some time to research the solution for Part 2.
Part 2: Solutions
When you are ready to compare your solution to another solution, open the box below:
Day 5 of 2020 solutions, Part 2 shows hide
A: congratulations! So far, you have solved at least two Advent of Code puzzles. Luckily, there are hundreds more waiting for you!
Click to follow, the first time to learn about Huawei cloud fresh technology ~