Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)
Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots
This one was pretty simple, just parse the numbers into sets and check the size of the intersection. Part 2 just made the scoring mechanism a little more complicated.
I'm rather spoiled by python, so I feel like it could be more elegant. xD
But yeah, I do like how this one turned out, and nim runs a whole lot faster than python does. I really like nim's "method call syntax". Instead of having methods associated with an individual type, you can just call any procedure as x.f(remaining_args) to call f with x as its first argument. Makes it easy to chain procedures. Since nim is strongly typed, it'll know which procedure you mean to use by the signature.
Hi there! Looks like you linked to a Lemmy community using a URL instead of its name, which doesn't work well for people on different instances. Try fixing it like this: !nim@programming.dev
This one wasn't too bad. The example for part 2 even tells you how to process everything by visiting each card once in order. Another option could be to recursively look at all won copies, but that's probably much less efficient.
I'm using this years' AoC to learn (Dyalog) APL, so this is probably terrible code. I'm happy to receive pointers for improvement, particularly if there is a way to write the same logic with tacit functions or inner/outer products that I missed.
I haven't heard of Uiua before, but I can read some things :D I like the idea of rotating the vector instead of manually padding it with the required number of leading zeroes!
import pathlib
base_dir = pathlib.Path(__file__).parent
filename = base_dir / "day4_input.txt"
with open(base_dir / filename) as f:
lines = f.read().splitlines()
score = 0
extra_cards = [0 for _ in lines]
n_cards = [1 for _ in lines]
for i, line in enumerate(lines):
_, numbers = line.split(":")
winning, have = numbers.split(" | ")
winning_numbers = {int(n) for n in winning.split()}
have_numbers = {int(n) for n in have.split()}
have_winning_numbers = winning_numbers & have_numbers
n_matches = len(have_winning_numbers)
if n_matches:
score += 2 ** (n_matches - 1)
j = i + 1
for _ in range(n_matches):
if j >= len(lines):
break
n_cards[j] += n_cards[i]
j += 1
answer_p1 = score
print(f"{answer_p1=}")
answer_p2 = sum(n_cards)
print(f"{answer_p2=}")
I enjoyed this one. It was a nice simple break after Days 1 and 3; the type of basic puzzle I expect from the first few days of Advent of Code. Pretty simple logic in this one, I don't think I would change too much. I'm sure I'll find a way to clean up how it's written a bit, but I'm happy with this one today.
-- SPDX-FileCopyrightText: 2023 Jummit
--
-- SPDX-License-Identifier: GPL-3.0-or-later
local function nums(str)
local res = {}
for num in str:gmatch("%d+") do
res[num] = true
end
return res
end
local cards = {}
local points = 0
for line in io.open("4.input"):lines() do
local winning, have = line:match("Card%s*%d+: (.*) | (.*)")
winning = nums(winning)
have = nums(have)
local first = true
local score = 0
local matching = 0
for num in pairs(have) do
if winning[num] then
matching = matching + 1
if first then
first = false
score = score + 1
else
score = score * 2
end
end
end
points = points + score
table.insert(cards, {have=have, wins=matching, count=1})
end
print(points)
local cardSum = 0
for i, card in ipairs(cards) do
cardSum = cardSum + card.count
for n = i + 1, i + card.wins do
cards[n].count = cards[n].count + card.count
end
end
print(cardSum)
I personally would prefer the if check and return 0 in most instances just because it's clearer and more readable. But the two previous functions were one-liners so it just looked better if get_winnings() also was.
Another day of parsing, another day of strsep() to the rescue. Today was one of those satisfying days where the puzzle text is complicated but the solution is simple once well understood.
Sets really came in handy for this challenge, as did recognizing that you can use powers of two to compute the points for each card. I tried using a regular expression to parse each card, but ended up just doing it manually with split :|
Numbers = set[int]
Card = list[Numbers]
def read_cards(stream=sys.stdin) -> Iterator[Card]:
for line in stream:
yield [set(map(int, n.split())) for n in line.split(':')[-1].split('|')]
def main(stream=sys.stdin) -> None:
cards = [numbers & winning for winning, numbers in read_cards(stream)]
points = sum(2**(len(card)-1) for card in cards if card)
print(points)
Part 2
This took me longer than I wished... I had to think about it carefully before seeing how you can just keep track of the counts of each card, and then when you get to that card, you add to its copies your current count.
def main(stream=sys.stdin) -> None:
cards = [numbers & winning for winning, numbers in read_cards(stream)]
counts = defaultdict(int)
for index, card in enumerate(cards, 1):
counts[index] += 1
for copy in range(index + 1, index + len(card) + 1):
counts[copy] += counts[index]
print(sum(counts.values()))
Today was the easiest day so far IMHO. Today, I coded in PHP, a horrible language that produces even worse code. (Ok, full confession, I fed my family for about half a decade on PHP. I seemed to have gotten stuck with it, and so I earned a PhD to escape it.)
Anyway, the only trouble I had was I forgot about the explode function's capacity to return empty strings. Once I filtered those I had the correct answer on the first one, and then 10 minutes later I had the second part. I wrote my code true to raw php's awful idioms, though I didn't make it web based. I read from stdin.
Today I learnt how to get multiple captures out of the same group in Regex. I also learnt how much a console line write slows down your app.... (2 seconds without, never finished with)
Task1
internal class Day4Task1 : IRunnable
{
public void Run()
{
var inputLines = File.ReadAllLines("Days/Four/Day4Input.txt");
var regex = new Regex("Card\\s*\\d*: ([\\d\\s]{2} )*\\|( [\\d\\s]{2})*");
int sumScore = 0;
foreach (var line in inputLines)
{
int lineScore = 0;
var winningSet = new HashSet();
var matches = regex.Match(line);
foreach(Capture capture in matches.Groups[1].Captures) {
winningSet.Add(capture.Value.Trim());
}
foreach (Capture capture in matches.Groups[2].Captures)
{
if(winningSet.Contains(capture.Value.Trim()))
{
lineScore = lineScore == 0 ? 1 : lineScore * 2;
}
}
sumScore += lineScore;
Console.WriteLine(lineScore.ToString());
}
Console.WriteLine("Sum:"+sumScore.ToString());
}
}
Task2
internal class Day4Task2 : IRunnable
{
private Regex _regex = new Regex("Card\\s*\\d*: ([\\d\\s]{2} )*\\|( [\\d\\s]{2})*");
private Dictionary _matchCountCache = new Dictionary();
private int _maxDepth = 0;
public void Run()
{
var inputLines = File.ReadAllLines("Days/Four/Day4Input.txt");
int sumScore = 0;
for (int i = 0; i < inputLines.Length; i++)
{
sumScore += ScoreCard(i, inputLines, 0);
Console.WriteLine("!!!" + i + "!!!");
}
Console.WriteLine("Sum:"+sumScore.ToString());
Console.WriteLine("Max Recursion Depth:"+ _maxDepth.ToString());
}
private int ScoreCard(int lineId, string[] inputLines, int depth)
{
if( depth > _maxDepth )
{
_maxDepth = depth;
}
if(lineId >= inputLines.Length)
{
return 0;
}
int matchCount = 0;
if (!_matchCountCache.ContainsKey(lineId)) {
var winningSet = new HashSet();
var matches = _regex.Match(inputLines[lineId]);
foreach (Capture capture in matches.Groups[1].Captures)
{
winningSet.Add(capture.Value.Trim());
}
foreach (Capture capture in matches.Groups[2].Captures)
{
if (winningSet.Contains(capture.Value.Trim()))
{
matchCount++;
}
}
_matchCountCache[lineId] = matchCount;
}
matchCount = _matchCountCache[lineId];
int totalCards = 1;
while(matchCount > 0)
{
totalCards += ScoreCard(lineId+matchCount, inputLines, depth+1);
matchCount--;
}
//Console.WriteLine("Finished processing id: " + lineId + " Sum is: " + totalCards);
return totalCards;
}
}
My solution to this one runs slow, but it gets the job done. I didn't actually need the CardInfo struct by the time I was done, but couldn't be bothered to remove it. Previously, it held more than just count.
late because I had to skip two days of aoc. Fairly easy
input = File.read("input.txt").lines
sum = 0
winnings = Array.new(input.size) {[1, 0]}
input.each_with_index do |line, i|
card, values = line.split(":")
nums = values.split("|").map(&.split.map(&.to_i))
points = 0
nums[1].each do |num|
if nums[0].includes?(num)
points = points == 0 ? 1 : points * 2
winnings[i][1] += 1
end end
sum += points
end
puts sum
winnings.each_with_index do |card, i|
next if card[1] == 0
(1..card[1]).each do |n|
winnings[i+n][0] += card[0]
end end
puts winnings.sum(&.[0])
[JavaScript] Swapped over to javascript from rust since I want to also practice some js. Managed to get part 1 in 4 minutes and got top 400 on the global leaderboard. Second part took a bit longer and took me 13 mins since I messed up by originally trying to append to the card array. (eventually swapped to keeping track of amounts in a separate array)
Part 1
// Part 1
// ======
function part1(input) {
const lines = input.split("\n");
let sum = 0;
for (const line of lines) {
const content = line.split(":")[1];
const winningNums = content.split("|")[0].match(/\d+/g);
const myNums = content.split("|")[1].match(/\d+/g);
let cardSum = 0;
for (const num of winningNums) {
if (myNums.includes(num)) {
if (cardSum == 0) {
cardSum = 1;
} else {
cardSum = cardSum * 2;
}
}
}
sum = sum + cardSum;
}
return sum;
}
Part 2
// Part 2
// ======
function part2(input) {
let lines = input.split("\n");
let amount = Array(lines.length).fill(1);
for (const [i, line] of lines.entries()) {
const content = line.split(":")[1];
const winningNums = content.split("|")[0].match(/\d+/g);
const myNums = content.split("|")[1].match(/\d+/g);
let cardSum = 0;
for (const num of winningNums) {
if (myNums.includes(num)) {
cardSum += 1;
}
}
for (let j = 1; j <= cardSum; j++) {
if (i + j >= lines.length) {
break;
}
amount[i + j] += amount[i];
}
}
return lines.reduce((acc, line, i) => {
return acc + amount[i];
}, 0);
}
I'll only post the actual parsing and solution. I have written some helpers which are in other files, as is the main function. For the full code, please see my github repo.
I'm pretty sure that implementing part 2 in a naive way would cause Lean to demand a proof of termination, what might not be that easy to supply in this case... Luckily there's a way more elegant and way faster solution than the naive one, that can use structural recursion and therefore doesn't need an extra proof of termination.
Solution
structure Card where
id : Nat
winningNumbers : List Nat
haveNumbers : List Nat
deriving Repr
private def Card.matches (c : Card) : Nat :=
flip c.haveNumbers.foldl 0 λo n ↦
if c.winningNumbers.contains n then o + 1 else o
private def Card.score : Card → Nat :=
(· / 2) ∘ (2^·) ∘ Card.matches
abbrev Deck := List Card
private def Deck.score : Deck → Nat :=
List.foldl (· + ·.score) 0
def parse (input : String) : Option Deck := do
let mut cards : Deck := []
for line in input.splitOn "\n" do
if line.isEmpty then
continue
let cs := line.splitOn ":"
if p : cs.length = 2 then
let f := String.trim $ cs[0]'(by simp[p])
let g := String.trim $ cs[1]'(by simp[p])
if not $ f.startsWith "Card " then
failure
let f := f.drop 5 |> String.trim
let f ← f.toNat?
let g := g.splitOn "|"
if q : g.length = 2 then
let winners := String.trim $ g[0]'(by simp[q])
let draws := String.trim $ g[1]'(by simp[q])
let toNumbers := λ(s : String) ↦
s.split (·.isWhitespace)
|> List.filter (not ∘ String.isEmpty)
|> List.mapM String.toNat?
let winners ← toNumbers winners
let draws ← toNumbers draws
cards := {id := f, winningNumbers := winners, haveNumbers := draws : Card} :: cards
else
failure
else
failure
return cards -- cards is **reversed**, that's intentional. It doesn't affect part 1, but makes part 2 easier.
def part1 : Deck → Nat := Deck.score
def part2 (input : Deck) : Nat :=
-- Okay, doing this brute-force is dumb.
-- Instead let's compute how many cards each original card is worth, and sum that up.
-- This relies on parse outputting the cards in **reverse** order.
let multipliers := input.map Card.matches
let sumNextN : Nat → List Nat → Nat := λn l ↦ (l.take n).foldl (· + ·) 0
let rec helper : List Nat → List Nat → List Nat := λ input output ↦ match input with
| [] => output
| a :: as => helper as $ (1 + (sumNextN a output)) :: output
let worths := helper multipliers []
worths.foldl (· + ·) 0