Följ Black Week pÄ SweClockers

🌟 Advent of Code (AoC) 2022 🌟

PermalÀnk
Medlem ★
●

Dag: 8
SprÄk: Python

Detta Àr nog det hemskaste jag skrivit pÄ lÀnge. Det blev nÀstan en oneliner.

import numpy as np from functools import reduce def get_shorter(l, level): for i in l: yield i if i >= level: return print((lambda a, fs: [(lambda a, f1, f2, f3: f1(reduce(f2, [np.rot90(f3(np.rot90(a, k = i)), k = -i) for i in range(4)]))) (a, *f) for f in fs])( np.array([[int(c) for c in l.strip()] for l in open("input08").readlines()]), [(np.sum, np.logical_or, lambda a: (a > np.insert(np.maximum.accumulate(a, axis = 0)[:-1,:], 0, -1, axis = 0))), (np.max, np.multiply, lambda a: np.array([[len(list(get_shorter(l[i+1:], l[i]))) for i in range(len(l))] for l in a]))]))

Dold text

Det intressanta lambdat Àr en funktion som roterar matrisen sÄ f3 appliceras frÄn alla fyra hÄll. Resultat-matriserna ORas eller multipliceras och sedan appliceras sum eller max. Fick inte ihop tvÄan i numpy, sÄ det fick bli en liten hjÀlpgenerator för det testet.

PermalÀnk
Medlem ★
●

Dag: 8
SprÄk: js

Det hÀr blev ju inte sÄ grannt men det funkade.
Fick lite game of life vibbar pÄ att iterera över en matris

import {readFileSync} from 'fs'; const trees = readFileSync("08data","utf8") .split("\n") .map(line => line.split("").map( height => Number(height)) ); const amountOfVisibleTrees = (y,x, part) => { const baseTreeHeight = trees[y][x]; let visibleFromLeft = true; let visibleTreesLookingLeft = 0; for(let _x = x - 1; _x >= 0 && visibleFromLeft; _x--){ visibleTreesLookingLeft++; visibleFromLeft = trees[y][_x] < baseTreeHeight; } let visibleFromRight = true; let visibleTreesLookingRight = 0; for(let _x = x + 1; _x < trees[y].length && visibleFromRight; _x++){ visibleTreesLookingRight++; visibleFromRight = trees[y][_x] < baseTreeHeight ; //visibleFromRight = !(trees[y][_x] >= baseTreeHeight ); } let visibleFromUp = true; let visibleTreesLookingUp = 0; for(let _y = y - 1; _y >= 0 && visibleFromUp; _y--){ visibleTreesLookingUp++; visibleFromUp = trees[_y][x] < baseTreeHeight; } let visibleFromDown = true; let visibleTreesLookingDown = 0; for(let _y = y + 1; _y < trees[x].length && visibleFromDown; _y++){ visibleTreesLookingDown++; visibleFromDown = trees[_y][x] < baseTreeHeight; } return part ? (visibleFromLeft || visibleFromRight|| visibleFromUp || visibleFromDown) : visibleTreesLookingLeft * visibleTreesLookingRight * visibleTreesLookingUp * visibleTreesLookingDown; }; let totalVisisble = 0; let highestScore = 0; for(let y = 0; y < trees[0].length; y++){ for(let x = 0; x < trees[y].length; x++){ totalVisisble += amountOfVisibleTrees(y,x,1) ? 1:0; const visibleTrees = amountOfVisibleTrees(y,x); if (visibleTrees>highestScore){ highestScore = visibleTrees; } } } console.log("Part 1:",totalVisisble); console.log("Part 2:",highestScore);

Dold text
Visa signatur

Att föresprÄka Mac pÄ Swec Àr som att föresprÄka hybridbilar pÄ en raggartrÀff i Mora.

Nuvarande stationÀr: 7800X3D, 128Gb ram, 4Tb nvme, 3x8Tb sata-ssd, 4070 Ti S

PermalÀnk
Medlem ★
●

Dag 8, uppgift 1
SprÄk: Python
Framförallt nöjd med lÀsbarheten

with open("8.txt") as f: a = [[*map(int, r)] for r in f.read().splitlines()] v = lambda t: (t[0], [[1 if (j == 0 or t[0][i][j] > max(t[0][i][:j])) else t[1][i][j] for j in range(len(t[0][0]))] for i in range(len(t[0]))]) h = lambda t: [[list(r) for r in zip(*m[::-1])] for m in t] sum(sum(w) for w in v(h(v(h(v(h(v((a, [[0 for _ in r] for r in a]))))))))[1])

Dold text
Visa signatur

1

PermalÀnk
Medlem
●

Var lite sen pÄ bollen, fÄr se om man gör ett par till

Dag: 1
SprÄk: Basic v2.0 (Commodore 64)

0 DIMB(5):FORX=0TO13:READA:B(C)=B(C)+A:IFA=0THENC=C+1
1 NEXT:FORC=0TO5:IFD<B(C)THEND=B(C):E=C+1
2 NEXT:PRINTE,D:DATA1000,2000,3000, ,4000, ,5000,6000, ,7000,8000,9000, ,10000

Dold text

Dag: 2
SprÄk: Basic v2.0 (Commodore 64)

0 FORX=0TO2:READA$:READB$:L=1:IFA$="A"ANDB$="Y"THENC=C+8:L=0
1 IFA$="B"ANDB$="Z"THENC=C+8:L=0
2 IFA$="C"ANDB$="X"THENC=C+8:L=0
3 IFASC(A$)=ASC(B$)-23THENC=C+6:L=0
4 C=C+L:NEXT:PRINTC:DATA"A","Y","B","X","C","Z"

Dold text

Dag: 3
SprÄk: Basic v2.0 (Commodore 64)
(Nedan kod mÄste knappas in som Upper/Lower case)

0 FORX=0TO5:READA$:L=LEN(A$)/2:B$=LEFT$(A$,L):C$=RIGHT$(A$,L):FORA=1TOL
1 FORB=1TOL:IFMID$(B$,A,1)=MID$(C$,B,1)THEND$=MID$(C$,B,1)
2 NEXT:NEXT:V=ASC(D$)-64:IFV>100THENV=V-102
3 R=R+V:NEXT:PRINTR
4 DATA"vJrwpWtwJgWrhcsFMMfFFhFp","jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL"
5 DATA"PmmdzqPrVvPwwTWBwg","wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn"
6 DATA"ttgJtRGJQctTZtZT","CrZsJsPPZsGzwwsLwLmpwMDw"

Dold text

Dag: 4
SprÄk: Basic v2.0 (Commodore 64)

0 FORX=0TO5:READX$:READY$
1 IFLEFT$(X$,1)=>LEFT$(Y$,1)THENIFRIGHT$(Y$,1)=>RIGHT$(X$,1)THENP=P+1
2 IFLEFT$(Y$,1)=>LEFT$(X$,1)THENIFRIGHT$(X$,1)=>RIGHT$(Y$,1)THENP=P+1
3 NEXT:PRINTP
4 DATA"2-4","6-8","2-3","4-5","5-7","7-9","2-8","3-7","6-6","4-6","2-6","4-8"

Dold text

Dag: 5
SprÄk: Basic v2.0 (Commodore 64)

0 DIMA$(8):DIMB$(3):DIMC$(2):FORI=0TO2:READC$(I):FORZ=0TO2
1 IFMID$(C$(I),(Z*3)+2,1)<>" " THENA$(Z)=A$(Z)+MID$(C$(I),(Z*3)+2,1)
2 NEXT:NEXT:FORI=0TO3:READB$(I):S=VAL(MID$(B$(I),6,1))-1
3 F=VAL(MID$(B$(I),13,1))-1:T=VAL(RIGHT$(B$(I),1))-1:FORQ=0TOS
4 A$(T)=LEFT$(A$(F),1)+A$(T):A$(F)=RIGHT$(A$(F),(LEN(A$(F))-1)):NEXT:NEXT
5 PRINTLEFT$(A$(0),1);LEFT$(A$(1),1);LEFT$(A$(2),1)
6 DATA" [D] ","[N][C] ","[Z][M][P]","MOVE 1 FROM 2 TO 1"
7 DATA"MOVE 3 FROM 1 TO 3","MOVE 2 FROM 2 TO 1","MOVE 1 FROM 1 TO 2""

Dold text
Visa signatur

‱‱‱‱    ¹˜”°ÂșXTROÂș°”˜¹ ‱‱‱‱ ‱‱‱‱ Letar du efter nĂ„got? ‱‱‱‱ ‱‱‱‱  The Little Ninja  ‱‱‱‱
‱‱‱‱ C64 0.98MHz/64K ‱‱‱‱ ‱‱‱‱   Prova det ultimata!   ‱‱‱‱ ‱‱‱‱ Komplett Cracktro ‱‱‱‱
‱‱‱‱  -Tack för sĂ„sen..  ‱‱‱‱ ‱‱‱‱     GO `GOOGLEÂŽ NOW   ‱‱‱‱ ‱‱‱‱    250bytes Intro   ‱‱‱‱

PermalÀnk
●

Dag: 8
SprÄk: Haskell

Idag hade jag tid över till att putsa till lösningen lite.

-- The program expects the input on stdin, ie -- $ ./solve < input import Data.Char (ord) import Data.List (transpose) main = interact solve solve :: String -> String solve input = "Problem 1: " ++ (show.numVisible) trees ++ "\n" ++ "Problem 2: " ++ (show.maximum.scenicScore) trees ++ "\n" where trees = map (map (\c->ord c-48)) (lines input) :: [[Int]] -- Calculate score for each tree, but return as a flat list. scenicScore :: [[Int]] -> [Int] scenicScore t = zipWith (*) viewHorz viewVert where rowScore t = zipWith (*) (view t) (reverse.view.reverse $ t) viewHorz = concat $ map rowScore t viewVert = concat $ transpose (map rowScore (transpose t)) -- View from each element in list towards the end. view :: [Int] -> [Int] view (t:[]) = [0] view (t:ts) = minimum [length ts, 1+length (takeWhile (<t) ts)] : view ts -- Count the number of visible trees. numVisible :: [[Int]] -> Int numVisible t = length $ filter id (zipWith (||) visHorz visVert) where visHorz = concat $ map visibility t visVert = concat $ transpose (map visibility (transpose t)) -- Visibility of each element in list from either end. visibility :: [Int] -> [Bool] visibility t = zipWith (||) (visFromEnd t) (visFromOtherEnd t) where visFromEnd (t:[]) = [True] visFromEnd (t:ts) = (t > maximum ts) : visFromEnd ts visFromOtherEnd = reverse.visFromEnd.reverse

(Jag anvÀnder highlight som finns i apt för syntaxfÀrgning.)

Dold text
PermalÀnk
Medlem ★
●
Skrivet av GLaDER:

Dag: 6
SprÄk: Python 3
Lösning: GitHub

Idag gick det Àn en gÄng upp för mig varför jag inte Àr sÄ snabb pÄ sÄdana hÀr uppgifter.

Jag tror det har att göra med exponering. Jag behöver luslÀsa texten för att förstÄ vad jag ska göra, men trots att jag lÀste texten förstod jag inte att:

  • Man skulle returnera positionen för slutet av markören (sĂ„ fick off-by-4-fel tvĂ„ gĂ„nger).

  • Man skulle titta pĂ„ buffern mha ett glidande fönster. Jag trodde uppgiften var att returnera "sĂ„ fort du sett 4 olika tecken".

Men men, jag ser det som personlighetstrÀning det Àr bra att det gÄr lite dÄligt ibland.

Dold text

Dag: 7
SprÄk: Python 3
Lösning: GitHub

Gav mig pÄ en rekursiv lösning men körde fast. Blev tipsad om att anvÀnda match och vips blev det en vÀldigt lÀslig och enkel lösning.

Dold text

Dag: 8
SprÄk: Python 3
Lösning: GitHub

Den hÀr gillade jag. Generellt gillar jag grid-uppgifter dÀr det gÄr att visualisera vad som eftersöks.

Dold text
Visa signatur

:(){ :|:& };:

đŸŠđŸ»â€â™‚ïž   đŸšŽđŸ»â€â™‚ïž   đŸƒđŸ»â€â™‚ïž   ☕

PermalÀnk
Datavetare ★
●

Dag: 8
SprÄk: Go

package main import "fmt" type TreePos struct { x, y int } type Forest map[TreePos]int var allDirections = [4]TreePos{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func parseForest(input []string) Forest { forest := Forest{} for y, row := range input { for x, height := range row { pos := TreePos{x, y} forest[pos] = int(height - '0') } } return forest } func (forest Forest) moveAt(pos TreePos, dx, dy int, visitor func(Forest, TreePos) bool) { for { pos.x += dx pos.y += dy if !visitor(forest, pos) { break } } } func (forest Forest) isVisible(pos TreePos) bool { startHeight := forest[pos] visible := false for i := 0; !visible && i < len(allDirections); i++ { d := allDirections[i] forest.moveAt(pos, d.x, d.y, func(f Forest, p TreePos) bool { if height, inForest := f[p]; !inForest { visible = true return false } else { return height < startHeight } }) } return visible } func (forest Forest) numVisibleTrees() int { visibleTrees := 0 for pos := range forest { if forest.isVisible(pos) { visibleTrees++ } } return visibleTrees } func (forest Forest) scenicScore(pos TreePos) int { startHeight := forest[pos] score := 1 for _, d := range allDirections { steps := 0 forest.moveAt(pos, d.x, d.y, func(f Forest, p TreePos) bool { if height, inForest := f[p]; !inForest { return false } else { steps += 1 return height < startHeight } }) score *= steps } return score } func (forest Forest) bestScenicScore() int { bestScore := 0 for pos := range forest { score := forest.scenicScore(pos) if bestScore < score { bestScore = score } } return bestScore } func day8(input []string) { forest := parseForest(input) fmt.Println(forest.numVisibleTrees()) fmt.Println(forest.bestScenicScore()) } func init() { Solutions[8] = day8 }

Lösning
Visa signatur

Care About Your Craft: Why spend your life developing software unless you care about doing it well? - The Pragmatic Programmer

PermalÀnk
Medlem
●
Skrivet av Yoshman:

Dag: 8
SprÄk: Go

package main import "fmt" type TreePos struct { x, y int } type Forest map[TreePos]int var allDirections = [4]TreePos{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func parseForest(input []string) Forest { forest := Forest{} for y, row := range input { for x, height := range row { pos := TreePos{x, y} forest[pos] = int(height - '0') } } return forest } func (forest Forest) moveAt(pos TreePos, dx, dy int, visitor func(Forest, TreePos) bool) { for { pos.x += dx pos.y += dy if !visitor(forest, pos) { break } } } func (forest Forest) isVisible(pos TreePos) bool { startHeight := forest[pos] visible := false for i := 0; !visible && i < len(allDirections); i++ { d := allDirections[i] forest.moveAt(pos, d.x, d.y, func(f Forest, p TreePos) bool { if height, inForest := f[p]; !inForest { visible = true return false } else { return height < startHeight } }) } return visible } func (forest Forest) numVisibleTrees() int { visibleTrees := 0 for pos := range forest { if forest.isVisible(pos) { visibleTrees++ } } return visibleTrees } func (forest Forest) scenicScore(pos TreePos) int { startHeight := forest[pos] score := 1 for _, d := range allDirections { steps := 0 forest.moveAt(pos, d.x, d.y, func(f Forest, p TreePos) bool { if height, inForest := f[p]; !inForest { return false } else { steps += 1 return height < startHeight } }) score *= steps } return score } func (forest Forest) bestScenicScore() int { bestScore := 0 for pos := range forest { score := forest.scenicScore(pos) if bestScore < score { bestScore = score } } return bestScore } func day8(input []string) { forest := parseForest(input) fmt.Println(forest.numVisibleTrees()) fmt.Println(forest.bestScenicScore()) } func init() { Solutions[8] = day8 }

Lösning

Om du konverterar string till []rune fÄr du mycket gratis.
https://github.com/johanneslarsson/aoc-2022/blob/main/08/a/ma...

PermalÀnk
Medlem
●

Dag: 8
SprÄk: C

#include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int isVisible(uint8_t *grid, int dim, int x, int y, uint32_t *scenicScore) { uint8_t curHeight = grid[x*dim + y]; int visibleRu = 1, visibleRd = 1, visibleCl = 1, visibleCr = 1; uint32_t sceneRu = 0, sceneRd = 0, sceneCl = 0, sceneCr = 0; // walk grid rows up for (int i=x-1; i>=0; i--) { sceneRu++; if (grid[i*dim + y] >= curHeight) { visibleRu = 0; break; } } // walk grid rows down for (int i=x+1; i<dim; i++) { sceneRd++; if (grid[i*dim + y] >= curHeight) { visibleRd = 0; break; } } // walk grid columns left for (int i=y-1; i>=0; i--) { sceneCl++; if (grid[x*dim + i] >= curHeight) { visibleCl = 0; break; } } // walk grid columns right for (int i=y+1; i<dim; i++) { sceneCr++; if (grid[x*dim + i] >= curHeight) { visibleCr = 0; break; } } *scenicScore = sceneRu * sceneRd * sceneCl * sceneCr; return visibleRu | visibleRd | visibleCl | visibleCr; } int main(void) { char *line = NULL; size_t len = 0; ssize_t nread; uint8_t *grid = NULL; int rowLen = 0; int curRow = 0; FILE *fp = fopen("d8_input.txt", "r"); if (!fp) { perror("Failed to open file"); exit(EXIT_FAILURE); } while ((nread = getline(&line, &len, fp)) != -1) { if (!grid) { rowLen = (nread-1); grid = malloc(sizeof(uint8_t)*rowLen*rowLen); if (!grid) exit(EXIT_FAILURE); } if (nread-1 != rowLen) exit(EXIT_FAILURE); for (int i=0; i<rowLen; i++) grid[curRow + i] = line[i]-'0'; curRow += rowLen; } free(line); fclose(fp); int sum = 0; uint32_t maxScore = 0; for (int i=0; i<rowLen; i++) for (int j=0; j<rowLen; j++) { uint32_t score; sum += isVisible(grid, rowLen, i, j, &score); if (score > maxScore) maxScore = score; } printf("sum: %d\n", sum); printf("maxScore: %u\n", maxScore); free(grid); exit(EXIT_SUCCESS); }

Dold text
PermalÀnk
Medlem ★
●

Dag: 9
SprÄk: C#
Kommentar: Hyfsat nöjd med hur snabbt jag löste problemet. Mindre nöjd med koden sÄklart, men sÄnt gÄr att slipa pÄ!

using System.Diagnostics; using AoCUtils; Console.WriteLine("Mickur's Advent of Code 2022 - Day 9!"); // Setup var input = File.ReadAllLines("input.txt"); const int ropeLength = 10; // Includes the head! // Initialize the positions of the head and tail as a tuple of coordinates var ropeArray = new (int, int)[ropeLength]; var ropeVisitedArray = new Dictionary<string, int>[ropeLength]; // Fill arrays with starting data for (var i = 0; i < ropeLength; i++) { ropeArray[i] = (0, 0); ropeVisitedArray[i] = new Dictionary<string, int> {{"0x0", 1}}; } var sw = new Stopwatch(); sw.Start(); // Loop through each move in the input foreach (var move in input) { var splitMove = move.Split(' '); var steps = Parsing.FastIntParse(splitMove[1]); for (var i = 0; i < steps; i++) { // Loop through rope for (var j = 0; j < ropeLength; j++) { var temp = ropeArray[j]; // Update the position of the rope if(j == 0) ropeArray[j] = UpdateHeadPosition(ropeArray[j], move[0]); else ropeArray[j] = UpdateTailPosition(ropeArray[j-1], ropeArray[j]); // Save visited state if (ropeArray[j] != temp) { var key = $"{ropeArray[j].Item1}x{ropeArray[j].Item2}"; if (ropeVisitedArray[j].TryGetValue(key, out var value)) value++; else { ropeVisitedArray[j].Add(key, 1); } } } } } sw.Stop(); Console.WriteLine($"Finished in {sw.ElapsedMilliseconds} ms ({sw.ElapsedTicks} ticks)"); // Print the final position of the tails for (var i = 0; i < ropeLength; i++) { if (i == 0) Console.WriteLine($"Head visited: {ropeVisitedArray[i].Count} places"); else Console.WriteLine($"Tail {i} visited: {ropeVisitedArray[i].Count} places"); } (int, int) UpdateHeadPosition((int, int) head, char move) { var x = head.Item1; var y = head.Item2; switch (move) { case 'U': y--; break; case 'D': y++; break; case 'L': x--; break; case 'R': x++; break; } return (x, y); } (int, int) UpdateTailPosition((int, int) head, (int, int) tail) { // Get the current positions of the head and tail var headX = head.Item1; var headY = head.Item2; var tailX = tail.Item1; var tailY = tail.Item2; // If tail is close enough to head, don't move if (Math.Abs(headX - tailX) <= 1 && Math.Abs(headY - tailY) <= 1) return tail; // Same X dimension, move in Y dimension if (headX == tailX) tailY = tailY < headY ? headY - 1 : headY + 1; // Same Y dimension, move in X dimension else if (headY == tailY) tailX = tailX < headX ? headX - 1 : headX + 1; // Else move diagonally towards head else { tailX = headX > tailX ? tailX + 1 : tailX - 1; tailY = headY > tailY ? tailY + 1 : tailY - 1; } // Return the new position of the tail as a tuple of coordinates return (tailX, tailY); }

Dold text
Visa signatur

CPU: 7950X | RAM: 32GB | GPU: 3090 w/ AlphaCool Eisblock Aurora
Ljudkort: Modius + Magnius | Lurar: GoldPlanar GL2000 / Sennheiser HD 650 / Philips Fidelio X3

PermalÀnk
Medlem ★
●

Dag: 9
SprÄk: Python

Komplexa tal förenklar matematik i tvÄdimensionella system...

dir = {"U": complex(0,1), "D": complex(0,-1), "L": complex(-1,0), "R": complex(1,0)} parts = [complex(0,0)] * 10 visited = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()] for move in open("input09").readlines(): m = move.strip().split() for _ in range(int(m[1])): parts[0] += dir[m[0]] for i in range(1, len(parts)): if abs(diff := parts[i - 1] - parts[i]) > 1.5: parts[i] += complex(diff.real / abs(diff.real) if diff.real else 0, diff.imag / abs(diff.imag) if diff.imag else 0) visited[i].add(parts[i]) print([len(visited[i]) for i in [1,9]])

Dold text
PermalÀnk
Medlem ★
●
Skrivet av GLaDER:

Dag: 7
SprÄk: Python 3
Lösning: GitHub

Gav mig pÄ en rekursiv lösning men körde fast. Blev tipsad om att anvÀnda match och vips blev det en vÀldigt lÀslig och enkel lösning.

Dold text

Dag: 8
SprÄk: Python 3
Lösning: GitHub

Den hÀr gillade jag. Generellt gillar jag grid-uppgifter dÀr det gÄr att visualisera vad som eftersöks.

Dold text

Dag: 9
SprÄk: Python 3
Lösning: GitHub

Del 1 tog lite lÀngre tid Àn jag hade hoppats (men sÄ Àr det vÀl alltid). Vad som gjorde mig besviken idag var att jag tyckte mig se lösningen pÄ Del 2 och jag hade skrivit min kod pÄ ett bra sÀtt. Det borde bara vara att Àndra mina tvÄ koordinater till en lista av koordinater och loopa över dem.

Gav det 2 minuter men fick fel svar och eftersom jag inte ville bli fast i morgontrafiken Äkte jag till kontoret. VÀl pÄ plats insÄg jag att jag hade ett off-by-one-error....... idx blev idx+1 i min loop och vips sÄ fungerade allt IstÀllet för att ha 5 minuter mellan Del 1 och Del 2 har jag nu 45 minuter

Dold text
Visa signatur

:(){ :|:& };:

đŸŠđŸ»â€â™‚ïž   đŸšŽđŸ»â€â™‚ïž   đŸƒđŸ»â€â™‚ïž   ☕

PermalÀnk
Medlem ★
●

Wohoo, jag startade Àntligen, ska posta senare

JÀklar vad nissarna Àr slarviga

PermalÀnk
Medlem ★
●

Det Àr lite intressant att titta pÄ topplistan. Klar etta just nu Àr betaveros, som verkar koda i ett hemmagjort sprÄk, noulith.
Ganska kul och ganska imponerande

PermalÀnk
Medlem ★
●
Skrivet av jaqob:

Det Àr lite intressant att titta pÄ topplistan. Klar etta just nu Àr betaveros, som verkar koda i ett hemmagjort sprÄk, noulith.
Ganska kul och ganska imponerande

Det jag tycker Àr mest intressant Àr hur snabbt folk lyckas lösa problemen. Jag hinner ju knappt lÀsa klart innan dom Àr klara.

Visa signatur

CPU: 7950X | RAM: 32GB | GPU: 3090 w/ AlphaCool Eisblock Aurora
Ljudkort: Modius + Magnius | Lurar: GoldPlanar GL2000 / Sennheiser HD 650 / Philips Fidelio X3

PermalÀnk
Medlem ★
●

Dag: 9
SprÄk: Kotlin

Rolig dag Hade en Point-klass med lite passande metoder för detta.

main() { println(day9(MutableList(2) {Point(0, 0)}, input.lines())) // Part 1 println(day9(MutableList(10) {Point(0, 0)}, input.lines())) // Part 2 } fun day9(chain: MutableList<Point>, instructions: List<String>): Int{ val usedPositions = mutableSetOf<Point>() for (line in instructions) { val (direction, length) = line.split(" ") for (iterate in 0 until length.toInt()) { chain[0] = chain[0].relativePosition(direction, 1) for (i in 1 until chain.size) { if (chain[i] !in chain[i-1].surroundingPoints() && chain[i] != chain[i-1]) { chain[i] = chain[i].surroundingPoints().intersect(chain[i-1].surroundingPoints()).toList() .minBy{ it.manhattanDistance(chain[i-1]) } } } usedPositions.add(chain.last()) } } return usedPositions.size } data class Point(val x: Int, val y: Int) { fun relativePosition(direction: String, distance: Int):Point { return when (direction) { "U" -> Point(this.x, this.y + distance) "D" -> Point(this.x, this.y - distance) "R" -> Point(this.x + distance, this.y) "L" -> Point(this.x - distance, this.y) else -> throw IllegalArgumentException("Not a valid direction code") } } fun surroundingPoints() = listOf(-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1).chunked(2).map { Point(this.x + it[0], this.y + it[1]) }.toSet() fun manhattanDistance(other:Point):Int { return abs(this.x - other.x) + abs(this.y - other.y) } }

Dold text
Visa signatur

i5-7600k . GTX 1080 . 16 GB

PermalÀnk
Medlem ★
●

Dag 8 fÄr bli min sista för i Är. TvÄ dagar i rad dÀr jag lÀgger alldeles för mycket tid pÄ detta dÀr exempeldatat ger mig rÀtt svar och den skarpa datan inte gör det och Àr pÄ tok för stor för att felsöka riktigt. IgÄr fick jag till slut korrekt svar pÄ del 2 utan att vara helt sÀker pÄ vad som var felet, idag Àr det redan pÄ del 1. Men lycka till till er andra iaf.

Visa signatur

The power of GNU compiles you!
"Often statistics are used as a drunken man uses lampposts -- for support rather than illumination."

PermalÀnk
Medlem ★
●

Dag: 1
SprÄk: ArnoldJS

CHILL OUT input STICK AROUND `<input hÀr>` CHILL OUT sum STICK AROUND GIVE THESE PEOPLE AIR arr ENOUGH TALK => arr I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE reduce GIVE THESE PEOPLE AIR GIVE THESE PEOPLE AIR a, b ENOUGH TALK => a GET UP b, 0 ENOUGH TALK CHILL OUT array STICK AROUND GIVE THESE PEOPLE AIR input ENOUGH TALK => input I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE split GIVE THESE PEOPLE AIR '\n\n' ENOUGH TALK I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE map GIVE THESE PEOPLE AIR row => row I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE split GIVE THESE PEOPLE AIR '\n' ENOUGH TALK I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE map GIVE THESE PEOPLE AIR n => parseInt GIVE THESE PEOPLE AIR n ENOUGH TALK ENOUGH TALK I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE reduce GIVE THESE PEOPLE AIR GIVE THESE PEOPLE AIR a, b ENOUGH TALK => a GET UP b, 0 ENOUGH TALK ENOUGH TALK I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE sort GIVE THESE PEOPLE AIR GIVE THESE PEOPLE AIR a, b ENOUGH TALK => b GET DOWN a ENOUGH TALK TERMINATED TALK TO THE HAND GIVE THESE PEOPLE AIR array GIVE THESE PEOPLE AIR input ENOUGH TALK [0] ENOUGH TALK

Dold text
PermalÀnk
Medlem
●

Dag: 9
SprÄk: C#

namespace AOC2022.Puzzles; internal class Puzzle9 : Puzzle<int> { protected override void Solve(string[] lines) { One = Move(lines, 2); Two = Move(lines, 10); } private static int Move(string[] lines, int knotsAmount) { var knots = new (int x, int y)[knotsAmount]; var visited = new HashSet<(int x, int y)>{ (0, 0) }; foreach (var line in lines) { var split = line.Split(' '); var direction = split[0]; foreach (var _ in Enumerable.Range(0, int.Parse(split[1]))) { knots[0] = MoveHead(direction, knots[0].x, knots[0].y); foreach (var x in Enumerable.Range(1, knotsAmount - 1)) { knots[x] = MoveKnot(knots[x - 1].x, knots[x - 1].y, knots[x].x, knots[x].y); } visited.Add(knots[^1]); } } return visited.Count; } private static (int x, int y) MoveHead(string direction, int x, int y) => direction switch { "U" => (x, y - 1), "D" => (x, y + 1), "L" => (x - 1, y), "R" => (x + 1, y), _ => throw new Exception("Invalid direction") }; private static (int x, int y) MoveKnot(int hx, int hy, int tx, int ty) => (Math.Abs(hx - tx) + Math.Abs(hy - ty) > 2) ? (GetNewPos(hx, tx), GetNewPos(hy, ty)) : (GetNewPos(tx, hx), GetNewPos(ty, hy)); private static int GetNewPos(int first, int second) => (first - second) switch { > 1 => first - 1, < -1 => first + 1, _ => first }; }

Dold text
PermalÀnk
Medlem ★
●

Dag: 9
SprÄk: js

Löste första delen pÄ lunchen men sedan hade jag inte tid förrÀn nu efter jobb med del 2. UpptÀckte till slut att jag kunde kombinera 1 och 2 och bara Àndra antalet knutar i indatan sÄ var resten av logiken samma.
Spontant kÀnns det som man kan göra nÄgot smart i moveTails men jag pallar inte nu och det Àr AW om en halvtimme. Ha en nice fredag

import {readFileSync} from 'fs'; const movements = readFileSync("09data","utf8") .split("\n") .map(line => { const parts = line.split(" "); return [parts[0], Number(parts[1])]; }); function moveTails(currentPositions, visitedPositionsByLastTail){ for(let i = 1; i <= currentPositions.length -1 ; i++){ const currentHeadPosition = currentPositions[i-1]; const currentTailPosition = currentPositions[i]; const xDiff = currentTailPosition[0] - currentHeadPosition[0]; const yDiff = currentTailPosition[1] - currentHeadPosition[1]; if(Math.abs(xDiff) + Math.abs(yDiff) > 2 ){ // means we need to do a diagonal move currentPositions[i] = [currentTailPosition[0] + (xDiff > 0 ? -1 : 1),currentTailPosition[1] + (yDiff > 0 ? -1 : 1) ]; } else if(Math.abs(xDiff) > 1){ currentPositions[i] = [currentTailPosition[0] + (xDiff > 0 ? -1 : 1), currentTailPosition[1]]; } else if(Math.abs(yDiff) > 1){ currentPositions[i] = [currentTailPosition[0], currentTailPosition[1] + (yDiff > 0 ? -1 : 1)]; } if(i === currentPositions.length -1){ //record the position of the last piece of the tail. don't care if it didn't move as it's a Set. visitedPositionsByLastTail.add(`${currentPositions[i][0]},${currentPositions[i][1]}`); } } } const directions = {U:[0,1], R:[1,0], D:[0,-1], L:[-1,0]}; function run(part, currentPositions){ const visitedPositionsByLastTail = new Set(); movements.forEach((movement) => { for(let i = 1; i <= movement[1]; i++){ currentPositions[0] = [ currentPositions[0][0] + directions[movement[0]][0], currentPositions[0][1] + directions[movement[0]][1] ]; moveTails(currentPositions, visitedPositionsByLastTail); } }); console.log(`Part ${part}:`, visitedPositionsByLastTail.size); } const part1StartPositions = [[0,0],[0,0]]; run(1, part1StartPositions); const part2StartPositions = [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]; run(2, part2StartPositions);

Dold text
Visa signatur

Att föresprÄka Mac pÄ Swec Àr som att föresprÄka hybridbilar pÄ en raggartrÀff i Mora.

Nuvarande stationÀr: 7800X3D, 128Gb ram, 4Tb nvme, 3x8Tb sata-ssd, 4070 Ti S

PermalÀnk
Medlem ★
●
Skrivet av Jaevel:

Dag: 1
SprÄk: ArnoldJS

The hell? haha!

Visa signatur

Att föresprÄka Mac pÄ Swec Àr som att föresprÄka hybridbilar pÄ en raggartrÀff i Mora.

Nuvarande stationÀr: 7800X3D, 128Gb ram, 4Tb nvme, 3x8Tb sata-ssd, 4070 Ti S

PermalÀnk
Medlem
●

Dag: 9
SprÄk: Go

LÄngsamt idag, hade en fin bugg som gjorde att alla instruktioner applicerades pÄ alla framför svansen.. Fungerade bra i del1, sÀmre i del2.

pkg: aoc2022/09/a BenchmarkPartOne-8 492 2320240 ns/op BenchmarkPartTwo-8 946 1253295 ns/op

package main import ( "bufio" "fmt" "os" ) type Instruction struct { Direction string Count int } type Pos struct { X int Y int } func up(y int, x int, i int) (int, int) { return y + i, x } func down(y int, x int, i int) (int, int) { return y - i, x } func left(y int, x int, i int) (int, int) { return y, x - i } func right(y int, x int, i int) (int, int) { return y, x + i } func executeSnakeMap(instructions []Instruction, snakeSize int) map[string]int { snake := make([]Pos, snakeSize) head := 0 tail := snakeSize - 1 tailMap := make(map[string]int, 0) updateVisit(tailMap, snake[tail].Y, snake[tail].X) for _, inst := range instructions { for m := 0; m < inst.Count; m++ { switch inst.Direction { case "U": snake[head].Y, snake[head].X = up(snake[head].Y, snake[head].X, 1) break case "D": snake[head].Y, snake[head].X = down(snake[head].Y, snake[head].X, 1) break case "R": snake[head].Y, snake[head].X = right(snake[head].Y, snake[head].X, 1) break case "L": snake[head].Y, snake[head].X = left(snake[head].Y, snake[head].X, 1) break } for h := 0; h < len(snake)-1; h++ { diffX := snake[h].X - snake[h+1].X diffY := snake[h].Y - snake[h+1].Y if abs(diffX) <= 1 && abs(diffY) <= 1 { continue } snake[h+1].X += moveMaxOne(diffX) snake[h+1].Y += moveMaxOne(diffY) if h+1 == tail { updateVisit(tailMap, snake[h+1].Y, snake[h+1].X) } } } } return tailMap } func updateVisit(visit map[string]int, y int, x int) { visit[fmt.Sprintf("%d,%d", y, x)]++ } func abs(i int) int { if i < 0 { return i * -1 } return i } func moveMaxOne(i int) int { if i == 0 { return 0 } else if i < 0 { return -1 } else { return 1 } } func getPartOne(instructions []Instruction) int { snakeSize := 2 tailMap := executeSnakeMap(instructions, snakeSize) return len(tailMap) } func getPartTwo(instructions []Instruction) int { snakeSize := 10 tailMap := executeSnakeMap(instructions, snakeSize) return len(tailMap) } func getRows(filename string) []Instruction { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) moves := make([]Instruction, 0) for scanner.Scan() { var headMove Instruction fmt.Sscanf(scanner.Text(), "%s %d", &headMove.Direction, &headMove.Count) moves = append(moves, headMove) } return moves } func main() { fmt.Println("Part one:", getPartOne(getRows("../input.txt"))) fmt.Println("Part two:", getPartTwo(getRows("../input.txt"))) }

Dold text
PermalÀnk
Medlem ★
●

Dag: 9
SprÄk: Go

type direction string const ( left direction = "L" right direction = "R" up direction = "U" down direction = "D" ) type positions map[coordinate]struct{} type coordinate struct { x, y int } type instruction struct { dir direction steps int } func main() { input, err := helpers.ReadLines(os.Args[1]) if err != nil { panic(err) } visitedPositionsLongRope := make(positions) longRope := make([]coordinate, 10) for i := 0; i < len(longRope); i++ { longRope[i] = coordinate{x: 0, y: 0} } visitedPositionsShortRope := make(positions) shortRope := make([]coordinate, 2) for i := 0; i < len(shortRope); i++ { shortRope[i] = coordinate{x: 0, y: 0} } visitedPositionsShortRope[shortRope[0]] = struct{}{} visitedPositionsLongRope[longRope[0]] = struct{}{} for _, line := range input { instructions := strings.Split(line, " ") ins := instruction{dir: direction(instructions[0]), steps: helpers.GetInt(instructions[1])} shortRope = visitedPositionsShortRope.performSteps(shortRope, ins) longRope = visitedPositionsLongRope.performSteps(longRope, ins) } fmt.Println(len(visitedPositionsShortRope)) fmt.Println(len(visitedPositionsLongRope)) } func (positions positions) performSteps(knots []coordinate, instruction instruction) []coordinate { head := knots[0] for s := 0; s < instruction.steps; s++ { switch instruction.dir { case left: head.x = head.x - 1 case right: head.x = head.x + 1 case up: head.y = head.y - 1 case down: head.y = head.y + 1 } knots[0] = head for t := 0; t < len(knots)-1; t++ { head := knots[t] tail := knots[t+1] dx, dy := head.x-tail.x, head.y-tail.y if math.Abs(float64(dx)) <= 1 && math.Abs(float64(dy)) <= 1 { continue } tail.x += moveTail(dx) tail.y += moveTail(dy) if _, ok := positions[tail]; !ok && t == len(knots)-2 { positions[tail] = struct{}{} } knots[t+1] = tail } } return knots } func moveTail(diff int) int { if diff == 0 { return 0 } else if diff < 0 { return -1 } else { return 1 } }

Dold text
PermalÀnk
Medlem ★
●

Dag: 10
SprÄk: Python

Verkar som aktiviteten i denna trÄd har klingat av ganska ordenligt. Vi fÄr se om den fÄr ett uppsving under helgen.

X, during = 1, [1] for i in open("input10").readlines(): during.append(X) if i[0] == "a": X += int(i[5:]) during.append(X) print(sum([i * during[i] for i in range(20, len(during), 40)])) s = "".join([".#"[during[i] in [(i - 1) % 40, i % 40, (i + 1) % 40]] for i in range(240)]) for i in range(0,240,40): print(s[i:i + 40])

Dold text
PermalÀnk
Medlem ★
●
Skrivet av GLaDER:

Dag: 9
SprÄk: Python 3
Lösning: GitHub

Del 1 tog lite lÀngre tid Àn jag hade hoppats (men sÄ Àr det vÀl alltid). Vad som gjorde mig besviken idag var att jag tyckte mig se lösningen pÄ Del 2 och jag hade skrivit min kod pÄ ett bra sÀtt. Det borde bara vara att Àndra mina tvÄ koordinater till en lista av koordinater och loopa över dem.

Gav det 2 minuter men fick fel svar och eftersom jag inte ville bli fast i morgontrafiken Äkte jag till kontoret. VÀl pÄ plats insÄg jag att jag hade ett off-by-one-error....... idx blev idx+1 i min loop och vips sÄ fungerade allt IstÀllet för att ha 5 minuter mellan Del 1 och Del 2 har jag nu 45 minuter

Dold text

Dag: 10
SprÄk: Python 3
Lösning: GitHub

Taskigt att lÀgga ett U i output pÄ Del 2. Jag trodde det var ett V.

Dold text
Visa signatur

:(){ :|:& };:

đŸŠđŸ»â€â™‚ïž   đŸšŽđŸ»â€â™‚ïž   đŸƒđŸ»â€â™‚ïž   ☕

PermalÀnk
Medlem ★
●

Dag: 10
SprÄk: C#
Kommentar: Börjar bli vÀldigt knepiga problem nu. Tar en stund för mig att ens förstÄ texten. Som vanligt finns det nog en hel del saker som kan förbÀttras med koden.

using System.Diagnostics; using AoCUtils; Console.WriteLine("Mickur's Advent of Code 2022 - Day 10!"); // Setup var input = File.ReadAllLines("input.txt"); var toBeAdded = 0; var shouldBeAdded = false; var register = 1; var cycles = 0; var signalStrengths = new List<int>(); var crt = new char[40, 6]; crt[0, 0] = '#'; var sw = new Stopwatch(); sw.Start(); // Loop through each move in the input for (var i = 0; cycles < 240; i++) { // Cycle Start cycles++; AddSignalStrength(); DrawCrt(); // 2 cycle operation if (input[i] != "noop") { toBeAdded = Parsing.FastIntParse(input[i].AsSpan(5)); shouldBeAdded = true; cycles++; AddSignalStrength(); DrawCrt(); } // Add values if (shouldBeAdded) { register += toBeAdded; shouldBeAdded = false; } } sw.Stop(); Console.WriteLine($"Finished in {sw.ElapsedMilliseconds} ms ({sw.ElapsedTicks} ticks)"); Console.WriteLine($"Part One answer: Sum of signal strengths is {signalStrengths.Sum()}"); Console.WriteLine($"Part Two answer: CRT output below"); for (var y = 0; y < 6; y++) { for (var x = 0; x < 40; x++) { Console.Write(crt[x, y]); } Console.Write(Environment.NewLine); } void AddSignalStrength() { if (cycles == 20 || (cycles + 20) % 40 == 0) { signalStrengths.Add(register * cycles); } } void DrawCrt() { var x = (cycles - 1) % 40; var y = cycles / 40; if(x < 40 && y < 6) if (Math.Abs(register - x) <= 1) crt[x, y] = '#'; else crt[x, y] = '.'; }

Dold text
Visa signatur

CPU: 7950X | RAM: 32GB | GPU: 3090 w/ AlphaCool Eisblock Aurora
Ljudkort: Modius + Magnius | Lurar: GoldPlanar GL2000 / Sennheiser HD 650 / Philips Fidelio X3

PermalÀnk
Medlem
●

Dag: 6
SprÄk: Basic v2.0 (Commodore 64)
(Rad 5-8 kan tas bort, Àr bara exempeldata)

0 READA$:L=LEN(A$):W=3:T=6:FORX=1TOL:FORQ=1TOW:Z=Z+1
1 IFMID$(A$,X,1)=MID$(A$,X+Q,1)THENZ=0:T=T-1
2 IFZ=6THENIFT=6THENPRINTX+1;MID$(A$,X-2,4):END
3 NEXTQ:W=W-1:IFW=0THENW=3:X=X-2:T=6:Z=0
4 NEXTX:DATA"MJQJPQMGBLJSPHDZTNVJFQWRCGSMLB"

5 REM DATA"BVWBJPLBGVBHSRLPGDMJQWFTVNCZ"
6 REM DATA"NPPDVJTHQLDPWNCQSZVFTBRMJLHG"
7 REM DATA"NZNRNFRFNTJFMVFWMZDFJLVTQNBHCPRSG"
8 REM DATA"ZCFZFWZZQFRLJWZLRFNPQDBHTMSCGVJW"

Dold text
Visa signatur

‱‱‱‱    ¹˜”°ÂșXTROÂș°”˜¹ ‱‱‱‱ ‱‱‱‱ Letar du efter nĂ„got? ‱‱‱‱ ‱‱‱‱  The Little Ninja  ‱‱‱‱
‱‱‱‱ C64 0.98MHz/64K ‱‱‱‱ ‱‱‱‱   Prova det ultimata!   ‱‱‱‱ ‱‱‱‱ Komplett Cracktro ‱‱‱‱
‱‱‱‱  -Tack för sĂ„sen..  ‱‱‱‱ ‱‱‱‱     GO `GOOGLEÂŽ NOW   ‱‱‱‱ ‱‱‱‱    250bytes Intro   ‱‱‱‱

PermalÀnk
●

Dag: 10
SprÄk: Nim
Lösning: Github

Var vÀÀldigt satisfying att se outputen pÄ del 2 Den hÀr pÄminde lite om gamla goda IntCode interpretern, fÄr se om det kommer nÄgon följduppgift pÄ den hÀr.

import batteries let duration = {"noop": 1, "addx": 2}.toTable proc parseInput(input: string): seq[tuple[cmd: string, val: int]] = for line in input.splitLines: let s = line.split(" ") let cmd = s[0] let val = if cmd == "noop": 0 else: parseInt(s[1]) result.add (cmd: s[0], val: val) iterator runCommands(commands: seq[tuple[cmd: string, val: int]]): tuple[reg, pos: int] = var register = 1 var currentCycle = 1 for (cmd, value) in commands: for i in 0 ..< duration[cmd]: yield (reg: register, pos: currentCycle - 1) currentCycle += 1 if cmd == "addx": register += value proc part1(input: string) = let commands = parseInput(input) var result = 0 for (reg, pos) in runCommands(commands): let currentCycle = pos + 1 if (currentCycle - 20) mod 40 == 0: result += currentCycle * reg echo "Part 1: ", result proc printCRT(crt: seq[string]) = for row in crt: echo row proc part2(input: string) = let width = 40 let height = 6 var result = newSeq[string](height) let commands = parseInput(input) for (reg, pos) in runCommands(commands): let rowPos = pos div width let colPos = pos mod width if abs(reg - colPos) < 2: result[rowPos] &= '#' else: result[rowPos] &= ' ' echo "Part 2: " result.printCrt when isMainModule: let input = readFile "input.txt" part1(input) part2(input)

Dold text
PermalÀnk
Medlem
●
PermalÀnk
Medlem ★
●

Dag: 9
SprÄk: Rust
Lösning:

use std::{fmt::Display, collections::BTreeSet}; #[derive(Debug, Clone, Default)] struct Board { tail_length: i32, head: (i32, i32), tail: Vec<(i32, i32)>, visited: BTreeSet<(i32, i32)>, } impl Board { fn new(tail_length: i32) -> Self { Self { tail_length, tail: vec![(0, 0); tail_length as usize], ..Default::default() } } fn apply_move(&mut self, m: Move) { for Move(dx, dy) in m.steps() { let (x, y) = self.head; self.head = (x + dx, y + dy); for i in 0..self.tail_length { let head = if i == 0 { self.head } else { self.tail[(i - 1) as usize] }; let mut tail = self.tail[i as usize]; if head != tail { let (hx, hy) = head; let (tx, ty) = tail; let (dx, dy) = (hx - tx, hy - ty); if dx != 0 && dy != 0 && dx.abs() + dy.abs() > 2 { tail = (tx + dx.signum(), ty + dy.signum()); } else if (dx == 0 || dy == 0) && (dx != 0 || dy != 0) { tail = (tx + (dx - dx.signum()), ty + (dy - dy.signum())) } self.tail[i as usize] = tail; } } if let Some(tail) = self.tail.last() { self.visited.insert(*tail); } } } } impl Display for Board { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let min_x = self.head.0 .min(*self.tail.iter().map(|(x, _)| x).min().unwrap_or(&self.head.0)) .min(*self.visited.iter().map(|(x, _)| x).min().unwrap_or(&self.head.0)); let max_x = self.head.0 .max(*self.tail.iter().map(|(x, _)| x).max().unwrap_or(&self.head.0)) .max(*self.visited.iter().map(|(x, _)| x).max().unwrap_or(&self.head.0)); let min_y = self.head.1 .min(*self.tail.iter().map(|(_, y)| y).min().unwrap_or(&self.head.1)) .min(*self.visited.iter().map(|(_, y)| y).min().unwrap_or(&self.head.1)); let max_y = self.head.1 .max(*self.tail.iter().map(|(_, y)| y).max().unwrap_or(&self.head.1)) .max(*self.visited.iter().map(|(_, y)| y).max().unwrap_or(&self.head.1)); for neg_y in min_y..=max_y { let y = (max_y + min_y) - neg_y; for x in min_x..=max_x { if (x, y) == self.head { write!(f, "H")?; } else if self.tail.contains(&(x, y)) { write!(f, "{}", self.tail.iter().position(|(tx, ty)| (x, y) == (*tx, *ty)).unwrap() + 1)?; } else if (x, y) == (0, 0) { write!(f, "s")?; } else if self.visited.contains(&(x, y)) { write!(f, "#")?; } else { write!(f, ".")?; } } writeln!(f)?; } Ok(()) } } #[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)] struct Move(i32, i32); impl Move { fn parse(s: &str) -> Self { let mut chars = s.chars(); let dir = chars.next().unwrap(); chars.next(); let dist = chars.as_str().parse::<i32>().unwrap(); match dir { 'U' => Self(0, dist), 'D' => Self(0, -dist), 'L' => Self(-dist, 0), 'R' => Self(dist, 0), _ => panic!("Invalid direction"), } } fn steps(&self) -> Vec<Move> { let Move(x, y) = self; let mut result = vec![]; for _ in 0..x.abs() { result.push(Move(x.signum(), 0)); } for _ in 0..y.abs() { result.push(Move(0, y.signum())); } result } } pub fn one() { let input = include_str!("input1.txt"); let mut board = Board::new(1); for line in input.lines() { let m = Move::parse(line); println!("{:?}", m); board.apply_move(m); } println!("{}", board); let result = board.visited.len(); println!("Day 9, part 1: {}", result); // 6026 } pub fn two() { let input = include_str!("input1.txt"); let mut board = Board::new(9); for line in input.lines() { let m = Move::parse(line); println!("{:?}", m); board.apply_move(m); } println!("{}", board); let result = board.visited.len(); println!("Day 9, part 2: {:?}", result); }

Dold text

Dag: 10
SprÄk: Rust
Lösning:

use derivative::Derivative; #[derive(Derivative)] #[derivative(Debug)] struct Cpu { result: u32, cycles: u32, x: i32, #[derivative(Debug = "ignore")] crt: [u8; 240] } impl Cpu { fn new() -> Cpu { Self { result: 0, cycles: 0, x: 1, crt: [0; 240], } } fn signal_strength(&self) -> u32 { self.cycles * self.x as u32 } fn run(&mut self, inst: Instruction) { match inst { Instruction::Addx(i) => { self.tick(); self.tick(); self.x += i; }, Instruction::Noop => { self.tick(); }, } } fn tick(&mut self) { match self.cycles { 20 | 60 | 100 | 140 | 180 | 220 => { println!("cycle: {}, signal strength: {}", self.cycles, self.signal_strength()); self.result += self.signal_strength(); } _ => {} } let crt_pos = (self.cycles % 40) as i32; if ((self.x - 1)..=(self.x + 1)).contains(&crt_pos) { self.crt[self.cycles as usize] = 1; } self.cycles += 1; } } #[derive(Debug)] enum Instruction { Addx(i32), Noop, } impl Instruction { fn parse(s: &str) -> Instruction { let mut parts = s.split_whitespace(); let op = parts.next().unwrap(); match op { "addx" => { let arg = parts.next().unwrap().parse::<i32>().unwrap(); Instruction::Addx(arg) }, "noop" => Instruction::Noop, _ => panic!("unknown op: {}", op), } } } pub fn one() { let input = include_str!("input1.txt"); let mut cpu = Cpu::new(); for line in input.lines() { let inst = Instruction::parse(line); // println!("{:?}", inst); cpu.run(inst); // println!("{:?}", cpu); } println!("Day 10, part 1: {}", cpu.result); } pub fn two() { let input = include_str!("input1.txt"); let mut cpu = Cpu::new(); for line in input.lines() { let inst = Instruction::parse(line); cpu.run(inst); } println!("Day 10, part 2:"); for row in 0..6 { for col in 0..40 { let pos = row * 40 + col; if cpu.crt[pos] == 1 { print!("#"); } else { print!("."); } } println!(); } }

Dold text

Idag var första gÄngen jag började Ängra Rust som val.

Behovet av att göra saker under varje tick/cycle istÀllet för efter instruktionen blev messy. Slutade med att jag la allt i Cpu. Hade varit riktigt trevligt om det fanns generator functions sÄ att run hade kunnat returnera en iterator som drev varje tick. Försökte Àven med en on_tick callback men fick aldrig till lifetimes sÄ att jag kunde uppdatera resultatet innifrÄn den.

Dold text
Code-taggar