🌟 Advent of Code (AoC) 2021 🌟

PermalÀnk
Medlem
●

Dag: 1
SprÄk: Golang

DÄligt med tid numera, sÄ fÄr se hur lÀnge jag mÀktar med.

package main import ( "bufio" "fmt" "os" "strconv" ) func getPartOne(numbers []int) int { count := 0 for i := 1; i < len(numbers); i++ { if numbers[i] > numbers[i-1] { count++ } } return count } func getPartTwo(numbers []int) int { count := 0 for i := 3; i < len(numbers); i++ { if sumNumbers(numbers[i-2:i+1]) > sumNumbers(numbers[i-3:i]) { count++ } } return count } func sumNumbers(numbers []int) int { s := 0 for _, val := range numbers { s += val } return s } func getNumbers(filename string) []int { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) numbers := []int{} for scanner.Scan() { row := scanner.Text() val, err := strconv.Atoi(row) if err != nil { panic(err) } numbers = append(numbers, val) } return numbers } func main() { fmt.Println("Part one: ", getPartOne(getNumbers("../input.txt"))) fmt.Println("Part two: ", getPartTwo(getNumbers("../input.txt"))) }

Dold text
PermalÀnk
●
Skrivet av Ingetledigtnamn:

Dag: 1
Ytterligare en Python

l = [int(i.strip()) for i in open("input1").readlines()] print(sum([x < y for x, y in zip(l[:-1], l[1:])])) print(sum([x < y for x, y in zip(l[:-3], l[3:])]))

Dold text

Är ganska bekvĂ€m med python sĂ„ ska försöka med det i Ă„r. Jag tror jag förstĂ„r dina tvĂ„ första rader men den sista? Skulle du kunna förklara kort hur den funkar? Har inte riktigt koll pĂ„ alla smĂ„ funktioner i pyhton Ă€n sĂ„ har lite svĂ„rt att fĂ„ ut hur den dĂ€r fungerar.

Visa signatur

Ryzen 7 5800X3D | Asus b350-f Gaming | Corsair 32GB 3000Mhz CL15 Vengeance LPX | Asus RTX 4070 Dual OC | Corsair RM650x | Samsung 970 EVO 1TB | Samsung 850 EVO 500GB | Fractal Design Meshify C | Acer Predator XB271HU

PermalÀnk
Medlem
●

Dag: 1
SprÄk: Elixir

Första gÄngen jag ger mig pÄ funktionell programmering. KÀnns som att det mest handlar om att kÀnna till vilka funktioner som finns i sprÄket och lÀsa dokumentation typ. Min lösning utgÄr frÄn att man skickar in en lista av nummer.

def part1(args) do Enum.with_index(args, fn element, index -> {element, Enum.at(args, index + 1)} end) |> Enum.filter(&is_tuple(&1)) |> Enum.filter(fn v -> is_number(elem(v, 1)) end) |> Enum.count(fn v -> elem(v, 0) < elem(v, 1) end) end def part2(args) do Enum.with_index(args, fn element, index -> {element, Enum.at(args, index + 1), Enum.at(args, index + 2)} end) |> Enum.filter(&is_tuple(&1)) |> Enum.filter(fn v -> is_number(elem(v, 1)) && is_number(elem(v, 2)) end) |> Enum.map(fn v -> Enum.sum(Tuple.to_list(v)) end) |> part1 end

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

Är ganska bekvĂ€m med python sĂ„ ska försöka med det i Ă„r. Jag tror jag förstĂ„r dina tvĂ„ första rader men den sista? Skulle du kunna förklara kort hur den funkar? Har inte riktigt koll pĂ„ alla smĂ„ funktioner i pyhton Ă€n sĂ„ har lite svĂ„rt att fĂ„ ut hur den dĂ€r fungerar.

Rad 1: gör en lista av alla heltal i filen -> [a,b,c,..., y, z]
Rad 2: zip gör elementvisa par av listorna [a,b,c,..., y] och [b,c,..., y, z] -> [(a,b), (b,c ), ..., (y,z)]. I dessa par jÀmförs elementen med < och vi fÄr en lista med True eller False. Denna lista summeras och vi fÄr antalet par som jÀmförelsen var sann för.
Rad 3: HÀr skall vi kolla A + B + C < B + C + D, men eftersom B + C stÄr pÄ bÄda sidor kan de förkortas bort och vi behöver bara jÀmföra A < D. SÄ hÀr gör vi samma sak som rad 2, men med listorna [a, b, c, ..., w] och [d, e, f, ..., z].

Dold text
PermalÀnk
●
Skrivet av Ingetledigtnamn:

Rad 1: gör en lista av alla heltal i filen -> [a,b,c,..., y, z]
Rad 2: zip gör elementvisa par av listorna [a,b,c,..., y] och [b,c,..., y, z] -> [(a,b), (b,c ), ..., (y,z)]. I dessa par jÀmförs elementen med < och vi fÄr en lista med True eller False. Denna lista summeras och vi fÄr antalet par som jÀmförelsen var sann för.
Rad 3: HÀr skall vi kolla A + B + C < B + C + D, men eftersom B + C stÄr pÄ bÄda sidor kan de förkortas bort och vi behöver bara jÀmföra A < D. SÄ hÀr gör vi samma sak som rad 2, men med listorna [a, b, c, ..., w] och [d, e, f, ..., z].

Dold text

Jaaa, tack! Nu trillade polletten ner.

Visa signatur

Ryzen 7 5800X3D | Asus b350-f Gaming | Corsair 32GB 3000Mhz CL15 Vengeance LPX | Asus RTX 4070 Dual OC | Corsair RM650x | Samsung 970 EVO 1TB | Samsung 850 EVO 500GB | Fractal Design Meshify C | Acer Predator XB271HU

PermalÀnk
Medlem ★
●
Skrivet av Thomas:

Fast man fÄr vÀl knappast poÀngen och sÄnt dÄ, eller?
Om nej, fÄr man poÀng för första december om man skickar in den tredje?

Vet inte om du fÄr poÀng för 2015, men du behöver inte skicka in samma dag för att fÄ poÀng.

PermalÀnk
Medlem
●

Hade tÀnkt satsa pÄ ett nytt sprÄk i Är, men insÄg att jag inte kommer att ha tid, sÄ det fÄr bli gamla hederliga python igen.

with open("input.txt") as fp: m = fp.readlines()
print(sum(m[i] < m[i+1] for i in range(len(m)-1)))
s3 = [sum([int(x) for x in m[i:i+3]]) for i in range(len(m)-2)]
print(sum(s3[i] < s3[i+1] for i in range(len(s3)-1)))

Dold text
Visa signatur

5700X3D | 32GB DDR4 3600 | 3070

PermalÀnk
Medlem ★
●

Dag: 1
SprÄk: python

Är nybörjare pĂ„ programmering överlag och kört java senaste Ă„ret, men tĂ€nkte att python kunde vara bra igen dĂ„ jag inte skrivit det mycket och senast var för ett Ă„r sen ungefĂ€r

Detta Àr lösningen för stjÀrna#1:

Sparade ner djupdatan i en textfil.

f = open("djup.txt", "r") lista = [] for x in f: lista.append(int(x)) djupare = 0 for i in range(len(lista)): if (lista[i-1] < lista[i]): djupare += 1 print(djupare)

Dold text

Lösning för stjÀrna #2

f = open("djup.txt", "r") lista = [] for x in f: lista.append(int(x)) djupare = 0 for i in range(len(lista)-3): if ((lista[i]+lista[i+1]+lista[i+2]) < (lista[i+1]+lista[i+2]+lista[i+3])): djupare += 1 print(djupare)

Dold text

Inga snygga lösningar, men men

PermalÀnk
Medlem ★
●
Skrivet av GLaDER:

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

Jag var sÄ exalterad över att fÄ komma igÄng att jag tillredde kaffet pÄ fel sÀtt.... Aja.

Tabbade mig rejÀlt med ett indenteringsfel... Jag skrev först

def solution_1(input): prev_depth = 0 num_inc = 0 for v1 in input: if v1 > prev_depth: num_inc += 1 prev_depth = v1 return num_inc - 1

Notera nÀst sista raden... jag tÀnkte att djupet bara skulle uppdateras med avseende pÄ tidigare djupaste djupet; men i texten stÄr det ju tydligt att vi alltid bryr oss om senaste djupet.

Dold text

Dag: 2
SprÄk: Python 3
Lösning: GitHub, men logiken finns i Utils.

IgÄr hade jag nÄgot att skylla pÄ, men nÀr 5 minuter pÄ första och 7 minuter pÄ andra "bara" rÀcker till rank 2831/1541 börjar man förstÄ hur mÄnga som sitter och försöker göra snabba lösningar Wow.

Eric Wastl gick up pÄ Twitter igÄr och skrev att det nog kan komma vÀl till hands med en ubÄt i Ärets AoC. [LÀnk]. Vi spekulerade i Kodsnacks Slack om inte flera dagar det hÀr Äret kommer handla om att implementera de olika styrfunktionaliteterna en ubÄt har. (Varför jag la lite extra tid pÄ att faktiskt skriva en submarine.py.)

Kan bli spÀnnande. Jag minns en uppgift frÄn ett tidigare Är dÀr vi skulle styra en bÄt, jag tyckte det var kul.

Dold text
Visa signatur

:(){ :|:& };:

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

PermalÀnk
Medlem ★
●

Dag: 2
SprÄk: Python

def f1(): def up (x, p): return (p[0], p[1] - x) def down (x, p): return (p[0], p[1] + x) def forward(x, p): return (p[0] + x, p[1] ) p = (0, 0) for x in [l.split() for l in open("input02").readlines()]: p = eval(x[0])(int(x[1]), p) print(p[0] * p[1]) def f2(): def up (x, p): return (p[0], p[1], p[2] - x) def down (x, p): return (p[0], p[1], p[2] + x) def forward(x, p): return (p[0] + x, p[1] + p[2] * x, p[2] ) p = (0, 0, 0) for x in [l.split() for l in open("input02").readlines()]: p = eval(x[0])(int(x[1]), p) print(p[0] * p[1]) f1() or f2()

Dold text

eller om man slÄr ihop de tvÄ berÀkningarna i en:

def up (x, p): return (p[0], p[1] - x, p[2], p[3] - x) def down (x, p): return (p[0], p[1] + x, p[2], p[3] + x) def forward(x, p): return (p[0] + x, p[1], p[2] + p[3] * x, p[3] ) p = (0, 0, 0, 0) for x in [l.split() for l in open("input02").readlines()]: p = eval(x[0])(int(x[1]), p) print(p[0] * p[1], p[0] * p[2])

Dold text
PermalÀnk
●

Dag: 2
SprÄk: Scala

val (hor, _, dep) = lines.foldLeft((0, 0, 0)) { case ((h, a, d), s"$command ${int(amount)}") => command match { case "forward" => (h + amount, a, d + a * amount) case "up" => (h, a - amount, d) case "down" => (h, a + amount, d) } } println(dep * hor)

Dold text

Eller i imperativ form (som jag sÄklart gjorde först )

var depth = 0 var aim = 0 var horizontal = 0 for(s"$command ${int(amount)}" <- lines) { command match { case "forward" => horizontal += amount depth += aim * amount case "up" => aim -= amount case "down" => aim += amount } } println(depth * horizontal)

Dold text
PermalÀnk
●

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

import std/[strutils, sequtils, strscans] proc part1(instructions: seq[string]): int = var depth, horiz: int for instr in instructions: let (success, dir, step) = scanTuple(instr, "$w $i") doAssert success if dir == "forward": horiz += step elif dir == "down": depth += step elif dir == "up": depth -= step else: doAssert false, "Invalid directions: " & dir result = depth * horiz proc part2(instructions: seq[string]): int = var depth, horiz, aim: int for instr in instructions: let (success, dir, step) = scanTuple(instr, "$w $i") doAssert success if dir == "forward": horiz += step depth += aim * step elif dir == "down": aim += step elif dir == "up": aim -= step else: doAssert false, "Invalid directions: " & dir result = depth * horiz let inputs = "input.txt".lines.toSeq echo "Part 1: ", part1(inputs) echo "Part 2: ", part2(inputs)

Dold text
PermalÀnk
Medlem
●

Dag: 2
SprÄk: Rust

use std::str::FromStr; pub enum Command { Forward(u32), Down(u32), Up(u32), } impl FromStr for Command { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let (command, value) = s.split_once(' ').ok_or("Felaktig instruktion")?; let value: u32 = value.parse().map_err(|_| "Felaktig siffra")?; match command { "forward" => Ok(Command::Forward(value)), "down" => Ok(Command::Down(value)), "up" => Ok(Command::Up(value)), _ => Err("OkÀnt kommando".into()), } } } #[derive(Debug, Default)] struct Submarine { horizontal: u32, depth: u32, aim: u32, } impl Submarine { pub fn instruction(&mut self, command: &Command) { match command { Command::Forward(value) => self.horizontal += value, Command::Down(value) => self.depth += value, Command::Up(value) => self.depth -= value, } } pub fn instruction_with_aim(&mut self, command: &Command) { match command { Command::Forward(value) => { self.horizontal += value; self.depth += self.aim * value; } Command::Down(value) => self.aim += value, Command::Up(value) => self.aim -= value, } } pub fn product(&self) -> u32 { self.horizontal * self.depth } } fn main() { let input = std::fs::read_to_string("input.txt"); let commands: Vec<Command> = input .unwrap() .lines() .filter_map(|s| s.parse::<_>().ok()) .collect(); // Part 1 let mut submarine = Submarine::default(); for command in commands.iter() { submarine.instruction(command); } println!("{}", submarine.product()); // 2027977 //Part 2 let mut submarine = Submarine::default(); for command in commands.iter() { submarine.instruction_with_aim(command); } println!("{}", submarine.product()); // 1903644897 }

Dold text
Visa signatur

AMD Ryzen 3700X, Gigabyte Elite X570, 32GB Ballistix Sport, NH-D15S, SAPPHIRE NITRO+ RX 7900 XTX, Corsair AX760, LG OLED C2 42"

PermalÀnk
●
PermalÀnk
Medlem
●

Dag: 2
SprÄk: C#

internal class Puzzle2 : Puzzle<int> { private record Instruction(string Command, int Amount); private record Position(int HorPos = 0, int Depth = 0, int Aim = 0) { internal int FinalPosition { get => HorPos * Depth; } } private readonly List<Instruction> _instructions = File.ReadAllLines("Inputs/Puzzle2.txt") .Select(x => { var parts = x.Split(' '); return new Instruction(parts[0], int.Parse(parts[1])); }) .ToList(); public override int One() => _instructions .Aggregate(new Position(), (c, i) => i.Command switch { "forward" => c with { HorPos = c.HorPos + i.Amount }, "down" => c with { Depth = c.Depth + i.Amount }, "up" => c with { Depth = c.Depth - i.Amount }, _ => c }).FinalPosition; public override int Two() => _instructions .Aggregate(new Position(), (c, i) => i.Command switch { "forward" => c with { HorPos = c.HorPos + i.Amount, Depth = c.Depth + c.Aim * i.Amount }, "down" => c with { Aim = c.Aim + i.Amount }, "up" => c with { Aim = c.Aim - i.Amount }, _ => c }).FinalPosition; }

Dold text
PermalÀnk
Medlem
●

Dag: 2
SprÄk: Golang

package main import ( "bufio" "fmt" "os" "strconv" "strings" ) type Position struct { X int Y int } func getPartOne(moves []Position) int { var pos Position for _, move := range moves { pos.X += move.X pos.Y += move.Y } return pos.X * pos.Y } func getPartTwo(moves []Position) int { var pos Position var aim int for _, move := range moves { aim += move.Y pos.X += move.X pos.Y += aim * move.X } return pos.X * pos.Y } func getMoves(filename string) []Position { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) var moves []Position for scanner.Scan() { row := scanner.Text() fields := strings.Fields(row) dir := fields[0] val, err := strconv.Atoi(fields[1]) if err != nil { panic(err) } switch dir { case "up": moves = append(moves, Position{ Y: -1 * val, }) case "down": moves = append(moves, Position{ Y: val, }) case "forward": moves = append(moves, Position{ X: val, }) } } return moves } func main() { fmt.Println("Part one: ", getPartOne(getMoves("../input.txt"))) fmt.Println("Part two: ", getPartTwo(getMoves("../input.txt"))) }

Dold text
Fixar litt pÄ loopen
PermalÀnk
Medlem
●
Visa signatur

Make the world a better place, make it open source

PermalÀnk
Medlem ★
●

Dag: 2
SprÄk: Python

Lösningen för stjÀrna#1:

f = open("dag2.txt", "r") navigation = [] depth = 0 horizontal = 0 for line in f: navigation.append([(n) for n in line.split(" ")]) for pair in navigation: x, y = str(pair[0]),int(pair[1]) if (x == "forward"): horizontal = horizontal + y elif (x == "down"): depth = depth + y elif (x == "up"): depth = depth - y print (horizontal * depth)

Dold text

Lösning för stjÀrna #2

f = open("dag2.txt", "r") navigation = [] aim = 0 depth = 0 horizontal = 0 for line in f: navigation.append([(n) for n in line.split(" ")]) for pair in navigation: x, y = str(pair[0]),int(pair[1]) if (x == "down"): aim = aim + y elif (x == "up"): aim = aim - y elif (x == "forward"): horizontal = horizontal + y depth = depth + (aim * y) print (horizontal * depth)

Dold text

Inga snygga lösningar, men men

PermalÀnk
Medlem
●

Dag: 2
SprÄk: Go
Lösning: Github

package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func part1(Coordinates []string) int { x, y := 0, 0 for _, Coords := range Coordinates{ splitString := strings.Fields(Coords) depth, _ := strconv.Atoi(splitString[1]) switch splitString[0] { case "forward": x += depth case "up": y -= depth case "down": y += depth } } return x * y } func part2(Coordinates []string) int { x, y, aim := 0, 0, 0 for _, Coords := range Coordinates{ splitString := strings.Fields(Coords) depth, _ := strconv.Atoi(splitString[1]) switch splitString[0] { case "forward": x += depth y += aim * depth case "up": aim -= depth case "down": aim += depth } } return x * y } func getInput() []string { file, _ := os.Open("input.txt") defer file.Close() scanner := bufio.NewScanner(file) var input []string for scanner.Scan() { input = append(input, scanner.Text()) } return input } func main() { Input := getInput() fmt.Println("Part one:", part1(Input)) fmt.Println("Part two:", part2(Input)) }

Dold text
PermalÀnk
Medlem
●

Dag: 2
SprÄk: Python
Lösning: github

def fileReader(): with open('inputDay2.txt') as file: lines = [line.split() for line in file] for i in range(len(lines)): lines[i][1] = int(lines[i][1]) return lines def day2_part1(lines): horizontal = 0 vertical = 0 for group in lines: x, y = str(group[0]), int(group[1]) if (x == "forward"): horizontal = horizontal + y elif (x == "up"): vertical = vertical - y elif (x == "down"): vertical = vertical + y return horizontal * vertical; def day2_part2(lines): horizontal = 0 vertical = 0 aim = 0 for group in lines: x, y = str(group[0]), int(group[1]) if (x == "forward"): horizontal = horizontal + y vertical = vertical + (aim * y) elif (x == "up"): aim = aim - y elif (x == "down"): aim = aim + y return horizontal * vertical; print('Day Two part 1:', day2_part1(fileReader())) print('Day Two part 2:', day2_part2(fileReader()))

Dold text

not the prettiest thing.

PermalÀnk
Medlem
●

Dag: 2
SprÄk: C++
Lösning:

int solve(vector<string> data, bool can_aim) { int result; /* Variable for submarine state: [x_pos, aim, y_pos] if can_aim == true [x_pos, y_pos, aim] if can_aim == false */ int state[3] {0,0,0}; std::string regex_string = "^(\\w+)\\s([0-9]+)$"; regex regex(regex_string); smatch matches; for (int i = 0, n = data.size(); i < n; i++) { regex_search(data[i],matches,regex); string dir = matches.str(1); int length = stoi(matches.str(2)); if (dir == "forward") { state[0] += length; state[2] += length * state[1]; //dummy value if can_aim == false } else if (dir == "up") { state[1] -= length; } else if (dir == "down") { state[1] += length; } } can_aim? result = state[0]*state[2] : result = state[0]*state[1]; return result; }

Dold text

Eller hÀr: https://github.com/gbroll/AoC-2021

PermalÀnk
Medlem
●

Dag: 2
SprÄk: Python

with open("input.txt") as fp:
commands = fp.readlines()

distance = 0
depth = 0
for c in commands:
d = c.split()
if d[0] == "forward":
distance += int(d[1])
if d[0] == "down":
depth += int(d[1])
if d[0] == "up":
depth -= int(d[1])

print(distance*depth)

distance = 0
depth = 0
aim = 0
for c in commands:
d = c.split()
if d[0] == "forward":
distance += int(d[1])
depth += int(d[1])*aim
if d[0] == "down":
aim += int(d[1])
if d[0] == "up":
aim -= int(d[1])

print(distance*depth)

Dold text
Visa signatur

5700X3D | 32GB DDR4 3600 | 3070

PermalÀnk
●

Dag: 2
SprÄk: C++

int task1(std::vector<std::pair<std::string,int>>& data){ int x, y; for(auto& pair:data){ if(pair.first == "forward") { x += pair.second; } else if(pair.first == "up"){ y = std::max(0,y-pair.second); } else { y += pair.second; } } return x*y; } int task2(std::vector<std::pair<std::string,int>>& data){ int x,y,aim; for(auto& pair:data){ if(pair.first == "forward"){ x += pair.second; y = std::max(0,y+pair.second*aim); } else if(pair.first == "up"){ aim -= pair.second; } else { aim += pair.second; } } return x * y; }

Dold text
PermalÀnk
Medlem ★
●

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

from utils import fetch def part_one(directions): horizontal = 0 depth = 0 for i in range(len(directions)): if directions[i] == 'forward': horizontal += int(directions[i + 1]) elif directions[i] == 'down': depth += int(directions[i + 1]) elif directions[i] == 'up': depth -= int(directions[i + 1]) return f'Horizontal: {horizontal}, Depth: {depth}, Total: {horizontal * depth}' def part_two(directions): horizontal = 0 depth = 0 aim = 0 for i in range(len(directions)): if directions[i] == 'forward': horizontal += int(directions[i + 1]) depth += int(directions[i + 1]) * aim elif directions[i] == 'down': aim += int(directions[i + 1]) elif directions[i] == 'up': aim -= int(directions[i + 1]) return f'Horizontal: {horizontal}, Depth: {depth}, Total: {horizontal * depth}' input = fetch('https://adventofcode.com/2021/day/2/input') print(part_one(input)) print(part_two(input))

Dold text
Visa signatur

EndeavourOS: Your search for the best Arch distro ends here
7800X3D » RX6950XT » G.SKILL 32GB » LG OLED42C35LA

PermalÀnk
Medlem
●

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

input0 = [] with open("dive.dat") as f: for line in f: line = line.rstrip('\n') input0.append(line) class SubmarineAlfa: def __init__(self): self.horizontal = 0 self.depth = 0 def dive(self, dir, amount): if "forward" in dir: self.horizontal += amount elif "down" in dir: self.depth += amount elif "up" in dir: self.depth -= amount def __str__(self): return f"Horizontal = {self.horizontal} Depth = {self.depth}\n\ Product = {self.horizontal * self.depth}" class SubmarineBeta: def __init__(self): self.horizontal = 0 self.depth = 0 self.aim = 0 def dive(self, dir, amount): if "forward" in dir: self.horizontal += amount self.depth += self.aim * amount elif "down" in dir: self.aim += amount elif "up" in dir: self.aim -= amount def __str__(self): return f"Horizontal = {self.horizontal} Depth = {self.depth} Aim = {self.aim}\n\ Product = {self.horizontal * self.depth}" yellowSubmarine = SubmarineBeta() for data in input0: d2 = data.split() yellowSubmarine.dive(d2[0], int(d2[1])) print(yellowSubmarine)

Dold text

Gjorde en klass per del, alfa och beta

Blev nÀstan tokig pÄ andra delen dÄ jag först trodde man skulle Àndra bÄda depth och aim vid up/down.

PermalÀnk
●

Dag 2 Del 2
SprÄk: TypeScript

import { readFile } from "../utils"; interface IDirection { command: "up" | "down" | "forward"; value: number; } function runDay2() { let depth = 0; let horizontal = 0; let aim = 0; const directions: IDirection[] = readFile(__dirname).map((s) => { const split = s.split(" "); return { command: split[0], value: parseInt(split[1], 10), } as unknown as IDirection; }); directions.forEach((d) => { if (d.command === "up") { aim -= d.value; } else if (d.command === "down") { aim += d.value; } else if (d.command === "forward") { depth += d.value * aim; horizontal += d.value; } }); console.log("Solution: " + depth * horizontal); }

Dold text
Visa signatur

Moderkort: ASUS PRIME Z690M-PLUS D4 | Proccesor: i5 12600K @ 3.6Ghz | Kylare: Cooler Master Hyper 212 EVO V2 | Ram: Corsair Vengeance LPX Black 32GB @ 3200Mhz | Chassi: Fractal Design Define Mini C | Grafikkort: ASUS GeForce RTX 4070 DUAL OC 12GB | NÀtagg: Corsair TX750M 80+ GOLD | Lagring: WD Black SN850 M.2 SSD - 1TB | SkÀrm: MSI 27" Optix MAG274QRF-QD IPS QHD @ 165 Hz

PermalÀnk
Medlem ★
●

c#

int v = 0, h = 0, v2 = 0; for (int i = 0; i < input.Length; i++) { var d = input[i].Split(' '); var x = int.Parse(d[1]); switch (d[0]) { case "up": v += -x; break; case "down": v += x; break; case "forward": h += x; v2 += v * x; break; default: throw new Exception(); } } (v * h).Dump("Part 1"); (v2 * h).Dump("Part 2");

Dold text
PermalÀnk
Datavetare ★
●

Dag 2:
SprÄk: Rust

use crate::solution::Solution; use crate::parse::*; use nom::{ branch::alt, bytes::complete::tag, character::complete::char, IResult, multi::many1, sequence::{separated_pair, terminated}, }; struct Day2 { commands: Vec<Command>, } #[derive(Debug, PartialEq)] enum Command { Forward(u32), Down(u32), Up(u32), } #[derive(Default, Debug)] struct Submarine { depth: u32, position: u32, aim: u32, } impl Submarine { fn from_commands(commands: &[Command], execute: fn(&mut Self, &Command)) -> Self { let mut submarine = Submarine::default(); for command in commands { execute(&mut submarine, command); } submarine } fn product(&self) -> u32 { self.depth * self.position } } fn command_part1(submarine: &mut Submarine, command: &Command) { match command { Command::Forward(amount) => submarine.position += amount, Command::Down(amount) => submarine.depth += amount, Command::Up(amount) => submarine.depth -= amount, } } fn command_part2(submarine: &mut Submarine, command: &Command) { match command { Command::Forward(amount) => { submarine.position += amount; submarine.depth += submarine.aim * amount; }, Command::Down(amount) => submarine.aim += amount, Command::Up(amount) => submarine.aim -= amount, } } impl Solution for Day2 { fn part1(&self) -> String { Submarine::from_commands(&self.commands, command_part1) .product() .to_string() } fn part2(&self) -> String { Submarine::from_commands(&self.commands, command_part2) .product() .to_string() } } pub fn new(input: &str) -> Box<dyn Solution> { Box::new(Day2{ commands: input_parser(input), }) } fn input_parser(str: &str) -> Vec<Command> { many1(line_parser)(str) .expect("Invalid input format") .1 } fn line_parser(str: &str) -> IResult<&str, Command> { terminated(command_parser, line_ending_or_eof)(str) } fn command_parser(str: &str) -> IResult<&str, Command> { separated_pair( alt((tag("forward"), tag("down"), tag("up"))), char(' '), u32_parser)(str) .map(|(input, (command, amount))| ( input, match command { "forward" => Command::Forward(amount), "up" => Command::Up(amount), "down" => Command::Down(amount), _ => panic!("Nom bug!"), } ) ) }

Dold text

Den hÀr Àr definitivt "over engineered". Men vill ha ett mÄl med varje Ärs AoC, oftast har det varit att lÀra sig ett nytt sprÄk. I Är Àr mÄlet att lÀra mig viktiga bibliotek i Rust, specifikt Nom för extremsnabb parsning av data.

Ett annat mÄl Àr att i slutÀndan ha ett program som löser alla 25 dagar pÄ <1 sekund pÄ en modern laptop. AnvÀnt ~10”s av den budgeten sÄ hÀr lÄngt, vilket kanske behövs dÄ det brukar komma 2-4 problem som ÀndÄ krÀver en del berÀkningskraft.

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
●

Dag: 2
SprÄk: Carth

Passade pÄ att lÀgga till en implementation av words (inklusive behov) till standardbiblioteket, baserad pÄ Haskellfunktionen med samma namn. Tror det kan vara en ganska allmÀnt praktisk funktion nÀr man jobbar med space-separarad data.

(import std) (define main (do io/bind (<- inp (io/map unwrap! (read-file "inputs/day2.txt"))) (let1 cmds (map parse-cmd (lines inp))) (display "Part 1:") (display (show-int (let1 [x y] (exec1 cmds) (* x y)))) (display "Part 2:") (display (show-int (let1 [x y _aim] (exec2 cmds) (* x y)))))) (data Cmd (Forward Int) (Down Int)) (define (parse-cmd line) (let ((ss (words line)) ([s1 ss] (unwrap! (next ss))) ([s2 _] (unwrap! (next ss))) (val (unwrap! (parse-int s2)))) (match s1 (case "forward" (Forward val)) (case "down" (Down val)) (case "up" (Down (neg val))) (case _ (panic "unreachable"))))) (define (exec1 cmds) (define (go [x y]) (fmatch (case (Forward dx) [(+ dx x) y]) (case (Down dy) [x (+ dy y)]))) (foldl go [0 0] cmds)) (define (exec2 cmds) (define (go [x y aim]) (fmatch (case (Forward dx) [(+ dx x) (+ (* dx aim) y) aim]) (case (Down daim) [x y (+ daim aim)]))) (foldl go [0 0 0] cmds))

Dold text
Visa signatur

Arbets- / Spelstation: Arch Linux - Ryzen 5 3600 - RX 7900 XT - 32G DDR4
Server: Arch Linux - Core i5-10400F - 16G DDR4

PermalÀnk
Medlem ★
●

Skulle inte ens göra nÄgot i Är eftersom jag har lite för mycket annat. Har hittills aldrig tagit mig mer Àn 6 dagar sÄ kom fram till att jag kanske kan göra de första tvÄ i varje fall nu nÀr de sÄg relativt chill ut och jag dessutom rÄkade ha VS code öppet för att peta pÄ ett script sÄ...

Dag: 2
SprÄk: Powershell

Del 1

[CmdletBinding()] param () $import = Get-Content input2.csv $depth = 0 $horizontal = 0 foreach ($line in $import) { Write-Verbose "Got instruction $line" $parts = $line -split " " $direction = $parts[0] $len = $parts[1] if ($direction -eq "forward") { $horizontal += $len Write-Verbose "Adding $len to horizontal, it is now $horizontal" } elseif ($direction -eq "down") { $depth += $len Write-Verbose "Adding $len to depth, it is now $depth" } elseif ($direction -eq "up") { $depth -= $len Write-Verbose "Subtracting $len from depth, it is now $depth" } } return $horizontal * $depth

Del 2

[CmdletBinding()] #för att fÄ -verbose att fungera param () $import = Get-Content input2.csv $aim = 0 $depth = 0 $horizontal = 0 foreach ($line in $import) { Write-Verbose "Got instruction $line" $parts = $line -split " " $direction = $parts[0] $len = $parts[1] if ($direction -eq "forward") { $horizontal += $len Write-Verbose "Added $len to horizontal, it is now $horizontal" $depthchange = [int]$len * [int]$aim $depth += $depthchange Write-Verbose "Added $depthchange to depth, it is now $depth" } elseif ($direction -eq "down") { $aim += $len Write-Verbose "Added $len to aim, it is now $aim" } elseif ($direction -eq "up") { $aim -= $len Write-Verbose "Subtracted $len from aim, it is now $aim" } } return $horizontal * $depth

Dold text
Visa signatur

PrimÀr: R9 3900X | ASUS X570-F Gaming | NH-D15 | 64GB@3200MHz | RTX 3080 10GB | Seasonic 850W | Fractal Define R6 |
Gamla bettan: i5 750@3.8GHz | 8GB | HD5770 | Corsair VS 550W | FD R2 |