Python solution to Advent of Code, day 3
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
New contributor
add a comment |
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
New contributor
add a comment |
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
New contributor
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
python python-3.x
New contributor
New contributor
New contributor
asked 5 mins ago
Céryl Wiltink
101
101
New contributor
New contributor
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210470%2fpython-solution-to-advent-of-code-day-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210470%2fpython-solution-to-advent-of-code-day-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown