Moderkort: Gigabyte X570 Aorus Master | CPU: AMD Ryzen R9 5900X | CPU-kylare: Noctua NH-D15 chromax.black | RAM: Corsair Vengeance LPX 64 GB (4x16) DDR4-3600 CL18 | GPU: Gigabyte RTX 4080 Eagle OC | SSD: 2 x Samsung 970 EVO Plus 1 TB NVMe + Kingston A400 480 GB + Samsung QVO860 1 TB | PSU: EVGA SuperNOVA G2 1000 W Gold | Chassi: Lian Li O11 Dynamic XL | SkÀrm: BenQ PD3200U @ 3840x2160 + ASUS ROG Strix XG32VQ @ 2560x1440 | Tangentbord: Corsair K68 RGB Cherry MX Red | Mus: Logitech MX Master 2S
đŻïž Advent of Code 2019 đŻïž
@cyklonen: LÀngst ned pÄ sidan med uppgiften sÄ finns en lÀnk "get your puzzle input.". Det Àr denna data du skall utgÄ ifrÄn.
Inte hos mig. Sidan mÄste vara trasig, eller dÄligt kodad. SÄ hÀr ser hela sidan ut (inget utanför bild att scrolla till):
Aha, jaja, det Àr inte noga. Ska ju inte koda, men dÄ vet jag!
Moderkort: Gigabyte X570 Aorus Master | CPU: AMD Ryzen R9 5900X | CPU-kylare: Noctua NH-D15 chromax.black | RAM: Corsair Vengeance LPX 64 GB (4x16) DDR4-3600 CL18 | GPU: Gigabyte RTX 4080 Eagle OC | SSD: 2 x Samsung 970 EVO Plus 1 TB NVMe + Kingston A400 480 GB + Samsung QVO860 1 TB | PSU: EVGA SuperNOVA G2 1000 W Gold | Chassi: Lian Li O11 Dynamic XL | SkÀrm: BenQ PD3200U @ 3840x2160 + ASUS ROG Strix XG32VQ @ 2560x1440 | Tangentbord: Corsair K68 RGB Cherry MX Red | Mus: Logitech MX Master 2S
Dag 2
Del 1 i C#:
public class Program
{
public static async Task Main(string[] args)
{
var input = await File.ReadAllTextAsync("input.txt");
var opCodes = input
.Split(',')
.Select((code, index) => new { index, opCode = int.Parse(code) })
.ToDictionary(x => x.index, x => x.opCode);
var result = PerformOperation(opCodes, 0);
Console.WriteLine($"Result: {string.Join(',', result)}");
}
private static IEnumerable<int> PerformOperation(Dictionary<int, int> opCodes, int index)
{
var operation = (Operation)opCodes[index];
if (operation == Operation.Stop)
{
return opCodes.Values;
}
var firstPosition = opCodes[index + 1];
var secondPosition = opCodes[index + 2];
var resultPosition = opCodes[index + 3];
var firstNumber = opCodes[firstPosition];
var secondNumber = opCodes[secondPosition];
switch (operation)
{
case Operation.Add:
opCodes[resultPosition] = firstNumber + secondNumber;
break;
case Operation.Multiply:
opCodes[resultPosition] = firstNumber * secondNumber;
break;
}
return PerformOperation(opCodes, index + 4);
}
public enum Operation
{
Add = 1,
Multiply = 2,
Stop = 99
}
Och en liten bruteforce-lösning till del 2:
public class Program
{
public static async Task Main(string[] args)
{
var input = await File.ReadAllTextAsync("input.txt");
var opCodes = input
.Split(',')
.Select((code, index) => new { index, opCode = int.Parse(code) })
.ToDictionary(x => x.index, x => x.opCode);
var (noun, verb) = FindNounAndVerb(opCodes);
Console.WriteLine($"Result: {100 * noun + verb}");
}
private static (int noun, int verb) FindNounAndVerb(Dictionary<int, int> opCodes)
{
const int target = 19690720;
for (int noun = 0; noun <= 99; noun++)
{
for (int verb = 0; verb <= 99; verb++)
{
var opCodesCopy = opCodes.ToDictionary(x => x.Key, x => x.Value);
opCodesCopy[1] = noun;
opCodesCopy[2] = verb;
if (PerformOperation(opCodesCopy, 0).First() == target)
{
return (noun, verb);
}
}
}
return (int.MinValue, int.MinValue);
}
private static IEnumerable<int> PerformOperation(Dictionary<int, int> opCodes, int index)
{
var operation = (Operation)opCodes[index];
if (operation == Operation.Stop)
{
return opCodes.Values;
}
var firstPosition = opCodes[index + 1];
var secondPosition = opCodes[index + 2];
var resultPosition = opCodes[index + 3];
var firstNumber = opCodes[firstPosition];
var secondNumber = opCodes[secondPosition];
switch (operation)
{
case Operation.Add:
opCodes[resultPosition] = firstNumber + secondNumber;
break;
case Operation.Multiply:
opCodes[resultPosition] = firstNumber * secondNumber;
break;
}
return PerformOperation(opCodes, index + 4);
}
public enum Operation
{
Add = 1,
Multiply = 2,
Stop = 99
}
Del 1
const { p3 } = require('./puzzle_input');
const [wire1path, wire2path] = p3
.split('\n')
.map(o => {
const path = [];
let x = 0;
let y = 0;
const moves = o.split(',');
moves.forEach(move => {
const direction = move[0];
const steps = parseInt(move.substring(1), 10);
for (let i = 0; i < steps; i++) {
switch (direction) {
case 'R':
x++;
break;
case 'L':
x--;
break;
case 'U':
y++;
break;
case 'D':
y--;
break;
}
path.push(`${x},${y}`);
}
})
return path;
});
const intersections = wire1path.filter(o => wire2path.includes(o));
const distances = intersections.map(o => {
const [x, y] = o.split(',').map(o => parseInt(o, 10));
const d = Math.abs(0 - x) + Math.abs(0 - y);
return d;
});
console.log(Math.min.apply(null, distances));
Del 2
const { p3 } = require('./puzzle_input');
const [wire1path, wire2path] = p3
.split('\n')
.map(o => {
const path = [];
let totalSteps = 0;
let x = 0;
let y = 0;
const moves = o.split(',');
moves.forEach(move => {
const direction = move[0];
const steps = parseInt(move.substring(1), 10);
for (let i = 0; i < steps; i++) {
totalSteps++;
switch (direction) {
case 'R':
x++;
break;
case 'L':
x--;
break;
case 'U':
y++;
break;
case 'D':
y--;
break;
}
path.push([x,y,totalSteps]);
}
})
return path;
});
const signalDelays = wire1path.reduce(
(acc, [x, y, steps]) => {
const intersection = wire2path
.find(([x2, y2]) => x2 === x && y2 === y);
if (intersection) {
return acc.concat(steps+intersection[2]);
}
return acc;
}, [])
console.log(Math.min.apply(null, signalDelays));
J*vlar var det hÀr eskalerade fort! Uppgift #2 Àr lÀngre och mer vÀlskriven Àn genomsnittliga ticketen jag plockar pÄ jobbet
Rust - dag 3
Offrade lunchen pÄ detta, Àr nog nyttigare
Ă
ter igen inget fokus pÄ kortast möjliga lösning, Àr primÀrt ute efter att lÀra mig Rust sÄ kanske lite "over engineered...". Hela projektet finns pÄ github.
use super::Solution;
use regex::Regex;
use std::collections::HashMap;
use Direction::*;
type Distance = u32;
type Coord = i32;
// State required for solve day 3
pub struct State {
line_a: Vec<Movement>,
line_b: Vec<Movement>,
}
#[derive(Clone, Copy, Debug)]
enum Direction {
Up,
Down,
Left,
Right,
}
struct Movement {
dir: Direction,
distance: Distance,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct Pos {
x: Coord,
y: Coord,
}
impl Pos {
// Start position is really arbitrary in this case
fn start() -> Pos {
Pos { x: 0, y: 0 }
}
fn manhattan_distance(&self, pos: Pos) -> Distance {
((self.x - pos.x).abs() + (self.y - pos.y).abs()) as Distance
}
// Move the position n steps in a specific direction, return all position(s)
// along the way, including the final position
fn step_n(&mut self, n: Distance, dir: Direction) -> Vec<Pos> {
let mut path = Vec::new();
let (dx, dy) = match dir {
Up => (0, -1),
Down => (0, 1),
Left => (-1, 0),
Right => (1, 0),
};
for _ in 0..n {
self.x = self.x + dx;
self.y = self.y + dy;
path.push(*self);
}
path
}
}
fn dir_parse(repr: &str) -> Direction {
match repr {
"U" => Up,
"D" => Down,
"R" => Right,
"L" => Left,
_ => panic!("Invalid direction"),
}
}
pub fn solution(lines: Vec<&str>) -> Box<dyn Solution> {
let mut sln = State {
line_a: Vec::new(),
line_b: Vec::new(),
};
let re = Regex::new(r"([UDLR])(\d+)(,|$)").unwrap();
for (idx, line) in lines.iter().enumerate() {
for grp in re.captures_iter(line) {
let mov = Movement {
dir: dir_parse(&grp[1]),
distance: grp[2].parse::<Distance>().unwrap(),
};
if idx == 0 {
sln.line_a.push(mov);
} else {
sln.line_b.push(mov);
}
}
}
Box::new(sln)
}
// Returns all position a line passes through and the distance from start for
// each position.
fn line_trace(line: &Vec<Movement>) -> HashMap<Pos, Distance> {
let mut trace = HashMap::new();
let mut p = Pos::start();
let mut distance = 0;
for m in line.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
distance = distance + 1;
trace.insert(*pos, distance);
}
}
trace
}
impl Solution for State {
fn part1(&self) -> String {
let trace = line_trace(&self.line_a);
let mut intersections = Vec::new();
let mut p = Pos::start();
for m in self.line_b.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
if let Some(_) = trace.get(pos) {
intersections.push(pos.manhattan_distance(Pos::start()));
}
}
}
intersections.sort();
intersections[0].to_string()
}
fn part2(&self) -> String {
let trace = line_trace(&self.line_a);
let mut trace_distance = Vec::new();
let mut p = Pos::start();
let mut dist_b = 0;
for m in self.line_b.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
dist_b = dist_b + 1;
if let Some(dist_a) = trace.get(pos) {
trace_distance.push(dist_a + dist_b);
}
}
}
trace_distance.sort();
trace_distance[0].to_string()
}
}
Jag hakade pÄ det hÀr i morse. Jag sitter mellan konsultuppdrag just nu sÄ jag tar tillfÀllet i akt att lÀra mig Rust, som jag har tÀnkt pÄ i ett par Är nu. SvÄrt men kul! Ska kolla pÄ hur @Yoshman har löst grejerna nÀr jag klarar dem sjÀlv. Jag Àr datalog och har kodat sedan jag började pÄ Teknis 2011 men jag har alltid varit dÄlig pÄ att ta mig för sÄdana hÀr saker.
TÀnk pÄ att jag Àr riktigt grön pÄ Rust, men kollar gÀrna in dina lösningar för att fÄ insperation av en annan nybörjare i sprÄket!
Care About Your Craft: Why spend your life developing software unless you care about doing it well? - The Pragmatic Programmer
Dag: 3
SprÄk: Haskell
Lösning: 1 & 2
{-# LANGUAGE LambdaCase, TupleSections #-}
module Day3 (part1, part2) where
import Data.List.Split
import qualified Data.Map as Map
import Lib
data Dir
= DUp
| DDown
| DLeft
| DRight
deriving Show
type Move = (Dir, Int)
data Point = Point Int Int deriving (Eq, Ord)
type Length = Int
type Path = [(Point, Length)]
-- Part 1
part1 :: IO Int
part1 = fmap (closestIntersectionBy manhattanDist) readInput
readInput :: IO String
readInput = readFile "inputs/day-3"
manhattanDist :: (Point, (Length, Length)) -> Int
manhattanDist ((Point x y), _) = abs x + abs y
closestIntersectionBy
:: Ord a => ((Point, (Length, Length)) -> a) -> String -> a
closestIntersectionBy f =
minimum
. map f
. uncurry fastIntersect
. both (coveredPoints . parseMoves)
. head2
. lines
parseMoves :: String -> [Move]
parseMoves = map parseMove . splitOn ","
where
parseMove s = (parseDir (head s), read (tail s))
parseDir = \case
'U' -> DUp
'D' -> DDown
'L' -> DLeft
'R' -> DRight
_ -> error "parseDir"
coveredPoints :: [Move] -> Path
coveredPoints = tail . scanl move ((Point 0 0), 0) . (interpolate =<<)
where
move (p, l) d = (move' p d, l + 1)
move' p d = addPoint p $ case d of
DUp -> (0, 1)
DDown -> (0, -1)
DLeft -> (-1, 0)
DRight -> (1, 0)
interpolate (d, n) = replicate n d
addPoint :: Point -> (Int, Int) -> Point
addPoint (Point x y) (dx, dy) = Point (x + dx) (y + dy)
-- | O(n * log n), unlike Data.List.intersect, which is O(n^2)
fastIntersect :: Path -> Path -> [(Point, (Length, Length))]
fastIntersect p q =
Map.toList (Map.intersectionWith (,) (Map.fromList p) (Map.fromList q))
-- Part 2
part2 :: IO Int
part2 = fmap (closestIntersectionBy combinedPathLength) readInput
combinedPathLength :: (Point, (Length, Length)) -> Length
combinedPathLength = uncurry (+) . snd
Arbets- / Spelstation: Arch Linux - Ryzen 5 3600 - RX 7900 XT - 32G DDR4
Server: Arch Linux - Core i5-10400F - 16G DDR4
Offrade lunchen pÄ detta, Àr nog nyttigare
Ă
ter igen inget fokus pÄ kortast möjliga lösning, Àr primÀrt ute efter att lÀra mig Rust sÄ kanske lite "over engineered...". Hela projektet finns pÄ github.
use super::Solution;
use regex::Regex;
use std::collections::HashMap;
use Direction::*;
type Distance = u32;
type Coord = i32;
// State required for solve day 3
pub struct State {
line_a: Vec<Movement>,
line_b: Vec<Movement>,
}
#[derive(Clone, Copy, Debug)]
enum Direction {
Up,
Down,
Left,
Right,
}
struct Movement {
dir: Direction,
distance: Distance,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct Pos {
x: Coord,
y: Coord,
}
impl Pos {
// Start position is really arbitrary in this case
fn start() -> Pos {
Pos { x: 0, y: 0 }
}
fn manhattan_distance(&self, pos: Pos) -> Distance {
((self.x - pos.x).abs() + (self.y - pos.y).abs()) as Distance
}
// Move the position n steps in a specific direction, return all position(s)
// along the way, including the final position
fn step_n(&mut self, n: Distance, dir: Direction) -> Vec<Pos> {
let mut path = Vec::new();
let (dx, dy) = match dir {
Up => (0, -1),
Down => (0, 1),
Left => (-1, 0),
Right => (1, 0),
};
for _ in 0..n {
self.x = self.x + dx;
self.y = self.y + dy;
path.push(*self);
}
path
}
}
fn dir_parse(repr: &str) -> Direction {
match repr {
"U" => Up,
"D" => Down,
"R" => Right,
"L" => Left,
_ => panic!("Invalid direction"),
}
}
pub fn solution(lines: Vec<&str>) -> Box<dyn Solution> {
let mut sln = State {
line_a: Vec::new(),
line_b: Vec::new(),
};
let re = Regex::new(r"([UDLR])(\d+)(,|$)").unwrap();
for (idx, line) in lines.iter().enumerate() {
for grp in re.captures_iter(line) {
let mov = Movement {
dir: dir_parse(&grp[1]),
distance: grp[2].parse::<Distance>().unwrap(),
};
if idx == 0 {
sln.line_a.push(mov);
} else {
sln.line_b.push(mov);
}
}
}
Box::new(sln)
}
// Returns all position a line passes through and the distance from start for
// each position.
fn line_trace(line: &Vec<Movement>) -> HashMap<Pos, Distance> {
let mut trace = HashMap::new();
let mut p = Pos::start();
let mut distance = 0;
for m in line.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
distance = distance + 1;
trace.insert(*pos, distance);
}
}
trace
}
impl Solution for State {
fn part1(&self) -> String {
let trace = line_trace(&self.line_a);
let mut intersections = Vec::new();
let mut p = Pos::start();
for m in self.line_b.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
if let Some(_) = trace.get(pos) {
intersections.push(pos.manhattan_distance(Pos::start()));
}
}
}
intersections.sort();
intersections[0].to_string()
}
fn part2(&self) -> String {
let trace = line_trace(&self.line_a);
let mut trace_distance = Vec::new();
let mut p = Pos::start();
let mut dist_b = 0;
for m in self.line_b.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
dist_b = dist_b + 1;
if let Some(dist_a) = trace.get(pos) {
trace_distance.push(dist_a + dist_b);
}
}
}
trace_distance.sort();
trace_distance[0].to_string()
}
}
TÀnk pÄ att jag Àr riktigt grön pÄ Rust, men kollar gÀrna in dina lösningar för att fÄ insperation av en annan nybörjare i sprÄket!
Om du Àr intresserad av kritik sÄ kan jag peka ut ett par grejer.
Du behöver inte anropa .iter()
/.into_iter()
i en for
-loop om typen redan har lÀmplig IntoIterator
implementation. Explicit anrop kan vara att föredra om typerna Àr otydliga, men det Àr oftast mer ideomatiskt att skippa.
// Följande 2 stycken Àr ekvivalenta:
let xs: Vec<Foo> = ...;
for x in &xs { ... } // x : &Foo
let xs: Vec<Foo> = ...;
for x in xs.iter() { ... } // x : &Foo
// och Àven detta Àr ekvivalent, förutsatt att `xs` Àr ok att konsumera hÀr
let xs: Vec<&Foo> = ...;
for x in xs { ... } // x : &Foo
Personligen hade jag nog skrivit om dina loopar mer funktionellt med, men det Àr vÀl mer en smaksak.
// FrÄn
let mut intersections = Vec::new();
for m in self.line_b.iter() {
let path = p.step_n(m.distance, m.dir);
for pos in path.iter() {
if let Some(_) = trace.get(pos) {
intersections.push(pos.manhattan_distance(Pos::start()));
}
}
}
intersections.sort();
intersections[0].to_string()
// Till
self
.line_b
.iter()
.flat_map(|m| p.step_n(m.distance, m.dir))
.filter(|pos| trace.contains(pos))
.map(|pos| pos.manhattan_distance(Pos::start()))
.min()
.to_string()
Arbets- / Spelstation: Arch Linux - Ryzen 5 3600 - RX 7900 XT - 32G DDR4
Server: Arch Linux - Core i5-10400F - 16G DDR4
@Bryal: Tackar!
Finns ju mer saker som man kan klaga pÄ. T.ex finns ju ingen anledning att spara alla punkter dÀr linjerna korsas, man Àr ju bara intresserad av lÀgsta vÀrdet. HÀr Àr det bÄde tunnelseende frÄn att allt Àr nytt, men ocksÄ lite önskan att anvÀnda saker som "sort" och "if let"...
Ăr inte puritan pĂ„ funktionell vs imperativ, Ă€r frĂ„n fall till fall. HĂ€r föredrar jag nog pipeline-modellen som du visar (hade gjort nĂ„got betydligt mer likt din lösning om jag kört C++17, men det kan jag ju till skillnad frĂ„n Rust...).
Care About Your Craft: Why spend your life developing software unless you care about doing it well? - The Pragmatic Programmer
Dag 3 i Kotlin
fun parse(line: String): List<Pair<Char, Int>> =
line.split(",").map { Pair(it[0], it.drop(1).toInt()) }
fun walk(instructions: List<Pair<Char, Int>>, position: Pair<Int, Int> = Pair(0, 0), stepCount: Int = 0, trail: MutableMap<Pair<Int, Int>, Int> = mutableMapOf()): MutableMap<Pair<Int, Int>, Int> {
return if (instructions.isEmpty()) {
trail
} else {
val (direction, steps) = instructions[0]
val newSteps = when (direction) {
'U' -> sequence {
(1..steps).forEach {
yield(Triple(position.first, position.second + it, stepCount + it))
}
}
'D' -> sequence {
(1..steps).forEach {
yield(Triple(position.first, position.second - it, stepCount + it))
}
}
'L' -> sequence {
(1..steps).forEach {
yield(Triple(position.first - it, position.second, stepCount + it))
}
}
'R' -> sequence {
(1..steps).forEach {
yield(Triple(position.first + it, position.second, stepCount + it))
}
}
else -> throw RuntimeException("Unknown direction")
}
val (x, y, newStepCount) = newSteps.last()
newSteps.forEach { (x, y, c) ->
trail.putIfAbsent(Pair(x, y), c)
}
walk(instructions.drop(1), Pair(x, y), newStepCount, trail)
}
}
fun part1(input: List<String>): Int? {
val line1 = walk(parse(input[0])).keys
val line2 = walk(parse(input[1])).keys
return line1.filter(line2::contains).map { abs(it.first) + abs(it.second) }.min()
}
fun part2(input: List<String>): Int? {
val line1 = walk(parse(input[0]))
val line2 = walk(parse(input[1]))
return line1.filter { line2.containsKey(it.key) }.map { it.value + line2.getOrDefault(it.key, 0) }.min()
}
"Knowledge amplification. What he learns, we all learn. What he knows, we all benefit from."
Dag: 3
SprÄk: Scala
case class Point(x: Int, y: Int) {
def +(that: Point): Point = Point(x + that.x, y + that.y)
}
val Array(l1, l2) = Using
.resource(Source.fromFile(filePath.toFile))(
_.mkString.split("\n").map(_.trim.split(",").map(str => str.head -> str.tail.toInt).toList))
val move = Map('L' -> Point(-1, 0), 'R' -> Point(1, 0), 'U' -> Point(0, 1), 'D' -> Point(0, -1))
def path(xs: List[(Char, Int)]) =
xs.iterator
.flatMap { case (dir, n) => Iterator.fill(n)(move(dir)) }
.scanLeft(Point(0, 0))(_ + _)
.toList
val p1 = path(l1)
val p2 = path(l2)
val intersection = (p1.toSet & p2.toSet) - Point(0, 0)
intersection.map(p => p.x.abs + p.y.abs).min.pipe(println)
intersection.map(p => p1.indexWhere(_ == p) + p2.indexWhere(_ == p)).min.pipe(println)
Fy tusan, kÀnner att det blir mer och mer spagetti fort nu men kÀnns ocksÄ som att jag lÀr mig en hel del pÄ ett roligt sÀtt. Idag fick jag faktiskt fuska lite och ta en titt pÄ de första minuterna av en lösningsvideo pÄ twitch för att se exempel pÄ förflyttning i ett koordinatsystem men sen löpte det pÄ riktigt bra men krÀvde lite googlande om mÀngdlÀra.
Dag: 3
SprÄk: Python
Lösning: 1 & 2
Lösning 1:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
file_path = dir_path + "\\input.txt"
with open(file_path) as inputfile:
lines = [line.strip() for line in inputfile.readlines()]
def calculate_line_coords(line):
line_coords = []
pos = (0,0)
instructions = line.split(",")
for instruction in instructions:
direction = instruction[0]
steps = int(instruction[1:])
dx = 0
dy = 0
if direction == 'U':
dy += 1
elif direction == 'D':
dy -= 1
elif direction == 'L':
dx -= 1
elif direction == 'R':
dx += 1
else:
raise ValueError
for _ in range(steps):
pos = (pos[0] + dx, pos[1] + dy)
line_coords.append(pos)
return line_coords
line_1_coords = set(calculate_line_coords(lines[0]))
line_2_coords = set(calculate_line_coords(lines[1]))
intersections = line_1_coords.intersection(line_2_coords)
min_manhattan = 0
for index, intersection in enumerate(intersections):
if index == 0:
min_manhattan = abs(intersection[0]) + abs(intersection[1])
manhattan_distance = min_manhattan
else:
manhattan_distance = abs(intersection[0]) + abs(intersection[1])
if manhattan_distance < min_manhattan:
min_manhattan = manhattan_distance
print(min_manhattan)
Lösning 2:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
file_path = dir_path + "\\input.txt"
with open(file_path) as inputfile:
lines = [line.strip() for line in inputfile.readlines()]
#Intersections gotten from part 1
intersections = [(6210, -3834), (5242, -2310), (5658, -2214), (5242, -2336), (5087, -2002), (4240, -1117), (4143, -3904), (5450, -1492), (6722, -4214), (5242, -2363), (6618, -3042), (4240, -1131), (4522, -3564), (4240, -1676), (5242, -2170), (6067, -3126), (5340, -2297), (4691, -3564), (6100, -2930), (6210, -4079), (5242, -2446), (5087, -1855), (5421, -1492), (5996, -2930), (4318, -1131), (6210, -3928), (4240, -1730), (6365, -4214), (6709, -2082), (5024, -2363), (6100, -3834), (5162, -1855), (5165, -2446), (5658, -2297), (5672, -1882), (6100, -3675), (5672, -2214), (5165, -2336), (4737, -1676), (5084, -3035), (5165, -2310), (4143, -4417), (4318, -1272), (6067, -2930), (4514, -1676), (6100, -3126), (5165, -2363), (5447, -2544), (6311, -4214), (5996, -3126), (6927, -3698), (6210, -3814), (5447, -2924), (6210, -3920), (6100, -3814), (6835, -2903), (5643, -3733), (5084, -3426), (5024, -2310), (6927, -3454), (6001, -3716), (5024, -2120), (6835, -2492), (4240, -1272), (5102, -1492), (5162, -2002), (6835, -2730), (5672, -2297), (6835, -2527), (6835, -2443)]
def calculate_steps_to_intersections(line, intersections):
output = {x:0 for x in intersections}
pos = (0,0)
instructions = line.split(",")
step_counter = 0
for instruction in instructions:
direction = instruction[0]
steps = int(instruction[1:])
dx = 0
dy = 0
if direction == 'U':
dy += 1
elif direction == 'D':
dy -= 1
elif direction == 'L':
dx -= 1
elif direction == 'R':
dx += 1
else:
raise ValueError
for _ in range(steps):
step_counter += 1
pos = (pos[0] + dx, pos[1] + dy)
if pos in intersections:
output[pos] = step_counter
return output
def calculate_lowest_steps(steps_line_1,steps_line_2,intersections):
lowest_steps = steps_line_1[intersections[0]] + steps_line_2[intersections[0]]
for intersection in intersections:
total_steps = steps_line_1[intersection] + steps_line_2[intersection]
if total_steps < lowest_steps:
lowest_steps = total_steps
return lowest_steps
steps_line_1 = calculate_steps_to_intersections(lines[0], intersections)
steps_line_2 = calculate_steps_to_intersections(lines[1], intersections)
lowest = calculate_lowest_steps(steps_line_1, steps_line_2, intersections)
print(lowest)
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 |
Dag: 3
SprÄk: Powershell
Lösning: Del 1
Nu börjar det plötsligt bli mycket svÄrare. Och det börjar bli Ànnu mer uppenbart att PowerShell kanske inte Àr det optimala sprÄket för att implementera denna sortens problem.
Jag försökte mig pÄ en optimerad algoritm istÀllet för att bruce-forcea in alla punkterna i en datastruktur. Den blev hyfsat snabb (sÀrskilt nÀr jag optimerade för multipla kÀrnor) men koden blev hemsk:
function Get-Directions {
Param($PuzzleInput)
[regex]$re = '([URDL])(\d+)'
$re.Matches($PuzzleInput) | % {
$Direction = $_.Groups[1].Value
[int]$Distance = $_.Groups[2].Value
[pscustomobject]@{
Direction=$Direction
Distance=$Distance
}
}
}
# Guarantees x1 -le x2 and y1 -le y2
function Get-LineSegment {
param(
[parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$Direction,
[parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$Distance
)
begin {
$x = 0
$y = 0
}
process {
switch ($Direction) {
U {
$y_new = $y + $Distance
[pscustomobject]@{ x_min=$x; y_min=$y; x_max=$x; y_max=$y_new }
$y = $y_new
}
D {
$y_new = $y - $Distance
[pscustomobject]@{ x_min=$x; y_min=$y_new; x_max=$x; y_max=$y }
$y = $y_new
}
L {
$x_new = $x - $Distance
[pscustomobject]@{ x_min=$x_new; y_min=$y; x_max=$x; y_max=$y }
$x = $x_new
}
R {
$x_new = $x + $Distance
[pscustomobject]@{ x_min=$x; y_min=$y; x_max=$x_new; y_max=$y }
$x = $x_new
}
default {
throw "Unknown direction $Direction"
}
}
}
}
function manhattan {
Param($x, $y)
return [math]::abs($x) + [math]::abs($y)
}
#$PuzzleInput = @('R75,D30,R83,U83,L12,D49,R71,U7,L72', 'U62,R66,U55,R34,D71,R55,D58,R83')
#$PuzzleInput = @('R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51', 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7')
$PuzzleInput = Get-Content (Join-Path $PSScriptRoot "aoc2019-3-input")
$Directions1 = Get-Directions -PuzzleInput $PuzzleInput[0]
$Directions2 = Get-Directions -PuzzleInput $PuzzleInput[1]
$LineSegments1 = $Directions1 | Get-LineSegment
$LineSegments2 = $Directions2 | Get-LineSegment
# Build line segment dictionaries for easilly finding candidate line segments running with a specific x or y coordinate
$HorizontalLineSegments2 = @{}
$VerticalLineSegments2 = @{}
$LineSegments2 | % {
if ($_.x_min -eq $_.x_max) {
$d = $VerticalLineSegments2
$k = $_.x_min
} else {
$d = $HorizontalLineSegments2
$k = $_.y_min
}
if (-not $d.ContainsKey($k)) {
$d[$k] = @()
}
$d[$k] += @($_)
}
$Threads = 12
$Buckets = @{}
foreach ($i in 0..($threads-1)) {
$buckets[$i] = @(@())
}
$i = 0
$LineSegments1 | % {
$Buckets[$i] += @($_)
$i = ($i + 1) % $threads
}
$IntersectionJobs = 0..($threads-1) | % {
Start-Job {
Param($LS1s, $VLS2, $HLS2)
# Optimization: Only gets the coordinate closest to the origin. This is only what we care about anyway.
function Get-LineSegmentIntersection {
param($LineSegment1, $LineSegment2)
if ($LineSegment1.x_min -le $LineSegment2.x_max -and $LineSegment2.x_min -le $LineSegment1.x_max) {
$x = [math]::max($LineSegment1.x_min, $LineSegment2.x_min)
} else {
# No overlap on X
return
}
if ($LineSegment1.y_min -le $LineSegment2.y_max -and $LineSegment2.y_min -le $LineSegment1.y_max) {
$y = [math]::max($LineSegment1.y_min, $LineSegment2.y_min)
} else {
# No overlap on Y
return
}
[pscustomobject]@{x=$x; y=$y}
}
foreach ($LS1 in $LS1s) {
foreach ($x in $LS1.x_min .. $LS1.x_max) {
$VLS2[$x] | % { Get-LineSegmentIntersection $LS1 $_ }
}
foreach ($y in $LS1.y_min .. $LS1.y_max) {
$HLS2[$y] | % { Get-LineSegmentIntersection $LS1 $_ }
}
}
} -ArgumentList ($buckets[$_], $VerticalLineSegments2, $HorizontalLineSegments2)
}
$Intersections = $IntersectionJobs | Receive-Job -Wait -AutoRemoveJob
($Intersections | % { manhattan $_.x $_.y } | Where { $_ -gt 0 } | Measure-Object -Minimum).Minimum
Jag tror nog att jag fÄr tÀnka om hÀr rejÀlt innan jag börjar med Steg 2. Mer anvÀnding av .NET:s collection-klasser kan eventuellt hjÀlpa en del.
Dag 3
Lösning 1&2
SprÄk C#
Svettigt i början men nÀr man vÀl fattat instruktionen var det inte sÄ svÄrt.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//https://adventofcode.com/
namespace AdventOfCode2019
{
public partial class frmAdventOfCode : Form
{
public frmAdventOfCode()
{
InitializeComponent();
}
private string[] GetStrArray(string input)
{
string[] strArr = input.Split(',');
return strArr;
}
private List<string> GetLines(string input)
{
return input.Split(new[] { "\r\n", "\r", "\n" },StringSplitOptions.None).ToList<string>();
}
public static int? ToInt(string val)
{
int test;
bool isint = int.TryParse(val, out test);
if (isint)
{
return test;
}
return null;
}
private void setCoord(int line, string coord, Dictionary<string,int[]> pathDict, int lineCount)
{
if (line<lineCount)
{
if (pathDict.ContainsKey(coord))
{
pathDict[coord][line] = 1;
}
else
{
int[] lines = new int[lineCount];
for (int i = 0; i < lineCount; i++)
{
lines[i] = 0;
}
lines[line] = 1;
pathDict.Add(coord, lines);
}
}
}
private bool getCord(string coord, Dictionary<string, int[]> pathDict, int lineCount)
{
bool test = true;
int[] linesCrossed = pathDict[coord];
for (int i = 0; i < lineCount; i++)
{
if (linesCrossed[i]!=1)
{
test = false;
}
}
return test;
}
private void button3_Click(object sender, EventArgs e)
{
string directions = "UDRL";
Dictionary<string, int[]> pathDict = new Dictionary<string, int[]>();
Dictionary<string, int[]> stepsTaken = new Dictionary<string, int[]>();
List<string> lines = GetLines(txtInput.Text);
int lineCount = lines.Count;
for (int runCount = 0; runCount < this.numSubTask.Value; runCount++)
{
int curLine = 0;
foreach (string line in lines)
{
string[] lineInstructions = GetStrArray(line);
Coord origo = new Coord(0, 0);
Coord curPos = origo;
int steppingCounter = 0;
for (int instructionIndex = 0; instructionIndex < lineInstructions.Length; instructionIndex++)
{
string dir = lineInstructions[instructionIndex].Substring(0, 1).ToUpper();
int? steps = ToInt(lineInstructions[instructionIndex].Substring(1));
if (steps != null && directions.Contains(dir))
{
int dirPos = directions.IndexOf(dir);
int axis = dirPos / 2;
int fbDir = (dirPos % 2) * -2 + 1;
for (int stepCounter = 0; stepCounter < (int)steps; stepCounter++)
{
steppingCounter++;
string newStrCoord = curPos.Step(axis, fbDir);
if (runCount==0)
{
setCoord(curLine, newStrCoord, pathDict, lineCount);
}
else
{
if (runCount==1)
{
bool test=getCord(newStrCoord,pathDict,lineCount);
if (test)
{
if (stepsTaken.ContainsKey(newStrCoord))
{
stepsTaken[newStrCoord][curLine] = steppingCounter;
}
else
{
int[] newData = new int[lineCount];
newData[curLine] = steppingCounter;
stepsTaken.Add(newStrCoord, newData);
}
}
}
}
}
}
}
curLine++;
}
}
if (this.numSubTask.Value==1)
{
Coord closestCord = new Coord(9999, 9999);
int shortestdist = closestCord.Distance;
foreach (KeyValuePair<string, int[]> kvp in pathDict)
{
bool test = true;
for (int i = 0; i < lineCount; i++)
{
if (kvp.Value[i] != 1)
{
test = false;
}
}
if (test)
{
Coord crossCord = new Coord(kvp.Key);
if (crossCord.Distance < shortestdist)
{
shortestdist = crossCord.Distance;
closestCord = crossCord;
}
}
}
txtInput.AppendText(Environment.NewLine + closestCord.ToString());
txtAnswer.Text = closestCord.Distance.ToString();
}
else
{
if (this.numSubTask.Value==2)
{
Coord closestCord = new Coord(9999, 9999);
int fewestSteps = 9999999;
foreach (KeyValuePair<string,int[]> kvp in stepsTaken)
{
int testValue = 0;
for (int i = 0; i < lineCount; i++)
{
testValue = testValue + kvp.Value[i];
}
if (testValue<fewestSteps)
{
fewestSteps = testValue;
closestCord = new Coord(kvp.Key);
}
}
txtInput.AppendText(Environment.NewLine + closestCord.ToString());
txtAnswer.Text = fewestSteps.ToString();
}
}
}
}
class Coord
{
private int _x=0;
private int _y=0;
public Coord(int x, int y)
{
_x = x;
_y = y;
}
public Coord(string coordString)
{
if (coordString.Split(',').Length==2)
{
int? lx = frmAdventOfCode.ToInt(coordString.Split(',')[0]);
int? ly = frmAdventOfCode.ToInt(coordString.Split(',')[1]);
if (lx!=null && ly!=null)
{
_x = (int)lx;
_y = (int)ly;
}
}
}
public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
public override string ToString()
{
return _x.ToString() + "," + _y.ToString();
}
public string Step(int axis, int dir)
{
if (axis==0)
{
x = x + dir;
}
else
{
if (axis==1)
{
y = y + dir;
}
}
return this.ToString();
}
public int Distance
{
get
{
return Math.Abs(_x) + Math.Abs(_y);
}
}
}
}
Ok jag vet att jag skriver ygigt och stort men herregud vilka nÀtta lösningar vissa publicerar. I alla fall nöjd med mina exekveringstider. 203 respektive 312 ms pÄ dagens uppgift.
@ZonYx: Kanon. Lycka till
OBS: Dag 2 Del2 (skam den som ger sig)
Dag:2 Del2
SprÄk: Python
Lösning:
import csv
import copy
register = []
saved = []
def readIn():
text = ""
nummer = 0
number1 = 0
with open('Day2_Part2.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
text = ",".join(row)
number1 = text.split(",")
for number in number1:
nummer = int(number)
register.append(nummer)
def operation(noun,verb):
index = 0
position1=1
position2=2
positionOutput=3
register[1] = noun
register[2] = verb
while register[index] == 1 or register[index] == 2:
if register[index] == 1:
register[register[positionOutput]] = register[register[position1]]+register[register[position2]] #Output
index = index + 4
position1 = position1 + 4
position2 = position2 + 4
positionOutput = positionOutput + 4
elif register[index] == 2:
register[register[positionOutput]] = register[register[position1]]*register[register[position2]] #Output
index = index + 4
position1 = position1 + 4
position2 = position2 + 4
positionOutput = positionOutput + 4
else:
print "Unavailable"
if register[index] == 99 and register[0] == 19690720:
print "Du lyckades hitta: ", register[0]
print "Med parametrarna:"
print "noun: ", register[1]
print "verb: ", register[2]
readIn()
saved = copy.deepcopy(register)
for x in range(0,100):
for y in range(0,100):
register = copy.deepcopy(saved)
operation(x,y)
Din förklaring gav utdelning!
Visste först inte att det inte gick att lÀsa in en CSV-fil flera gÄnger, sÄ satt fast pÄ att jag inte kunde ÄterstÀlla minnet ett bra tag.
Sedan googlade jag fram en lösning och gjorde en kopia av arrayen istÀllet. med "module copy"
@Daz: Haha det dÀr Àr elegant i jÀmförelse med mitt aber som undersöker om linjesegment korsar varandra.
Nu fÄr du ju posta
Min första tanke var att rita linjerna med turtle och returnera positionen nÀr den andra sköldpaddan passerar en linje men tydligen gÄr inte det Hade varit sjujÀkla elegant annars!
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 |
@ZonYx: Ok hÀr kommer lite mer handfasta tips.
Enklast Àr om du gör din lösning ifrÄn del1 som en funktion som tar emot tvÄ vÀrden. index1(noun) och index2(verb). Det Àr dessa som Àr 12 och 2 i första uppgiften. I del2 vill vi kunna testa olika parametrar.
Testa sedan alla kombination av noun och verb mellan 0 och 99 och se vilken kombination som ger index0 pÄ 19690720. Detta kan du tex göra med 2 nÀstlade loopar.
NÀr du vÀl har hittar korrekt vÀrden pÄ noun och verb sÄ Àr svaret de söker 100 * noun + verb.
Tackar för dessa tips. Satt nÀra 1h och förstog inte riktigt vad som skulle göras pÄ del 2.
Dag: 2
SprÄk: C++
Lösning:
Del 1:
#include <iostream>
using namespace std;
int main() {
int intCode[153] = /* Tog bort för enklare lÀsning*/
int pos = 0;
int sum = 0;
do
{
if (intCode[pos] == 99) {
break;
}
else if(intCode[pos] == 1)
{
sum = intCode[intCode[pos + 1]] + intCode[intCode[pos + 2]];
intCode[intCode[pos + 3]] = sum;
}
else if (intCode[pos] == 2)
{
sum = intCode[intCode[pos + 1]] * intCode[intCode[pos + 2]];
intCode[intCode[pos + 3]] = sum;
}
pos += 4;
} while (true);
cout << intCode[0] << endl;
cin.get();
}
Del 2:
#include <iostream>
using namespace std;
int getOPCode(int noun, int verb) {
int intCode[153] = /* Tog bort för enklare lÀsning*/
int pos = 0;
int sum = 0;
do
{
if (intCode[pos] == 99) {
break;
}
else if (intCode[pos] == 1)
{
sum = intCode[intCode[pos + 1]] + intCode[intCode[pos + 2]];
intCode[intCode[pos + 3]] = sum;
}
else if (intCode[pos] == 2)
{
sum = intCode[intCode[pos + 1]] * intCode[intCode[pos + 2]];
intCode[intCode[pos + 3]] = sum;
}
pos += 4;
} while (true);
return intCode[0];
}
int main() {
for (int verb = 0; verb <= 99; verb++) {
for (int noun = 0; noun <= 99; noun++) {
if (getOPCode(noun, verb) == 19690720) {
cout << ((100 * noun) + verb) << endl;
}
}
}
cin.get();
}
Node 304 White | Asus Strix X470-I | R5 2600 @ 3.85Ghz | 16GiB DDR4-3000Mhz CL15 | Sapphire Radeon RX 5700 PULSE | 512GiB 860 EVO M.2 | 1TiB 970 EVO Plus NVMe | Corsair SF450
Nu fÄr du ju posta
Min första tanke var att rita linjerna med turtle och returnera positionen nÀr den andra sköldpaddan passerar en linje men tydligen gÄr inte det Hade varit sjujÀkla elegant annars!
Det hade varit magiskt!
Det vackra i krÄksÄngen var följande (som jag lÄnat frÄn internet):
def line_intercept(L1, L2):
# Sample L1 or L2 : [(0, 0), (75, 0)]
s1x = L1[1][0] - L1[0][0]
s1y = L1[1][1] - L1[0][1]
s2x = L2[1][0] - L2[0][0]
s2y = L2[1][1] - L2[0][1]
if (-s2x * s1y + s1x * s2y) != 0:
s = (-s1y * (L1[0][0] - L2[1][0]) + s1x * (L1[0][1] - L2[0][1])) / (-s2x * s1y + s1x * s2y)
t = ( s2x * (L1[0][1] - L2[0][1]) - s2y * (L1[0][0] - L2[0][0])) / (-s2x * s1y + s1x * s2y)
# print(s, t)
if s >= 0 and s <= 1 and t >= 0 and t <=1:
x_intercept = L1[0][0] + (t * s1x)
y_intercept = L1[0][1] + (t * s1y)
return (x_intercept, y_intercept)
else:
return False
Men den misslyckas med att kÀnna av nÀrmsta korsningen i första exemplet. Det blev att stega genom koordinat-systemet istÀllet.
HÀnger med frÄn och med idag, fÄr se hur nÀra inpÄ jul det finns tid över.
Dag: 1
SprÄk: Python
Lösning: Del 1 & 2
with open('input01.txt') as file:
print(sum([int(i)//3 - 2 for i in file]))
def f(n):
if n//3-2 < 1:
return 0
return f(n//3-2) + n//3-2
with open('input01.txt') as file:
print(sum([f(int(i)) for i in file]))
Dag: 2
SprÄk: Python
Lösning: Del 1 & 2
with open('input02.txt') as file:
intcode = list(map(int, file.read().split(',')))
intcode[1] = 12
intcode[2] = 2
cursor = 0
opCode = intcode[cursor]
while opCode != 99:
if opCode == 1:
intcode[intcode[cursor+3]] = intcode[intcode[cursor+1]] + intcode[intcode[cursor+2]]
elif opCode == 2:
intcode[intcode[cursor+3]] = intcode[intcode[cursor+1]] * intcode[intcode[cursor+2]]
cursor += 4
opCode = intcode[cursor]
print(intcode[0])
def f(memory, n, v):
memory[1] = n
memory[2] = v
ip = 0 #instruction pointer
instruction = memory[ip]
while instruction != 99:
if instruction == 1:
memory[memory[ip+3]] = memory[memory[ip+1]] + memory[memory[ip+2]]
elif instruction == 2:
memory[memory[ip+3]] = memory[memory[ip+1]] * memory[memory[ip+2]]
ip += 4
instruction = memory[ip]
return memory[0]
with open('input02.txt') as file:
memory = list(map(int, file.read().split(',')))
for noun in range(100):
for verb in range(100):
if f(memory.copy(), noun, verb) == 19690720:
print(100*noun + verb)
break
else:
continue
break
Dag: 3
SprÄk: Python
Lösning: Del 1 & 2
def getWire(rawWire):
x = 0
y = 0
wire = []
for section in rawWire:
direction = section[0]
for _ in range(int(section[1:])):
if direction == 'U':
y += 1
if direction == 'D':
y -= 1
if direction == 'L':
x -= 1
if direction == 'R':
x += 1
wire.append((x,y))
return wire
with open("input03.txt") as file:
rawWires = [row.strip().split(',') for row in file.readlines()]
wire1 = getWire(rawWires[0])
wire2 = getWire(rawWires[1])
intersections = set(wire1).intersection(wire2)
intersectionDistances = list(map(lambda x: abs(x[0])+abs(x[1]), intersections))
print(min(intersectionDistances))
def getWire(rawWire):
x = 0
y = 0
wire = []
for section in rawWire:
direction = section[0]
for _ in range(int(section[1:])):
if direction == 'U':
y += 1
if direction == 'D':
y -= 1
if direction == 'L':
x -= 1
if direction == 'R':
x += 1
wire.append((x,y))
return wire
with open("input03.txt") as file:
rawWires = [row.strip().split(',') for row in file.readlines()]
wire1 = getWire(rawWires[0])
wire2 = getWire(rawWires[1])
intersections = set(wire1).intersection(wire2)
intersectionDistances = list(map(lambda x: wire1.index(x)+wire2.index(x)+2, intersections))
print(min(intersectionDistances))
Dag 4
SprÄk C#
Uppgift 1&2
exekveringstid 300 respektive 300 ms
private void button4_Click(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
int? _from = ToInt(txtInput.Text.Split('-')[0]);
int? _to = ToInt(txtInput.Text.Split('-')[1]);
bool remembered = (this.numSubTask.Value == 2);
if (_from == null || _to == null)
{
return;
}
int from = (int)_from;
int to = (int)_to;
int validPassords = 0;
for (int i = from; i < (to + 1); i++)
{
if (hasDblDigit(i.ToString(),remembered) && digitsInSequens(i.ToString()))
{
validPassords++;
}
}
txtAnswer.Text = validPassords.ToString();
watch.Stop();
Int64 elapsedMs = watch.ElapsedMilliseconds;
label1.Text = elapsedMs.ToString();
}
public static bool hasDblDigit(string pwdTest, bool remembered=false)
{
bool test = false;
for (int i = 0; i < (pwdTest.Length - 1); i++)
{
if (pwdTest.Substring(i, 1) == pwdTest.Substring(i + 1, 1))
{
if (remembered)
{
string befChar = String.Empty;
string aftChar = String.Empty;
if (i>0)
{
befChar = pwdTest.Substring(i - 1, 1);
}
if (i<(pwdTest.Length-2))
{
aftChar = pwdTest.Substring(i+2, 1);
}
if (pwdTest.Substring(i, 1)!=befChar && pwdTest.Substring(i, 1)!=aftChar)
{
test = true;
}
}
else
{
test = true;
}
}
}
return test;
}
public static bool digitsInSequens(string pwdTest)
{
bool test = true;
for (int i = 0; i < (pwdTest.Length - 1); i++)
{
if (int.Parse(pwdTest.Substring(i, 1)) > int.Parse(pwdTest.Substring(i + 1, 1)))
{
test = false;
}
}
return test;
}
Dag: 4
SprÄk: Dyalog APL
Det gÄr sÀkert att skriva kortare och snabbare kod men det hÀr var det bÀsta jag fick till efter bara ett par dagar APL.
h lâ595730 136760
{+/{{(â”âĄâ”â·âšâââ”)â§5â„âŽâȘâ”}ââ”}šâ”}1-âšlââłh
{+/{{(â”âĄâ”â·âšâââ”)â§2â{,âąâ”}âžâ”}ââ”}šâ”}1-âšlââłh
Samma men nÄgot lÀngre scala kod:
val (low, hi) = (136760, 595730)
def rule1(x: Int): Boolean =
x.toString.toSeq.sorted == x.toString.toSeq && x.toString.toSeq.distinct.size < 6
def rule2(x: Int): Boolean =
x.toString.toSeq.sorted == x.toString.toSeq && x.toString
.groupMapReduce(identity)(_ => 1)(_ + _)
.valuesIterator
.contains(2)
(low to hi).count(rule1).pipe(println)
(low to hi).count(rule2).pipe(println)
Dag 2 i scala
DAG 2, problem 1
def intCode(input: Array[Int]): Int = {
@tailrec
def intCodeHelper(arr: Array[Int],index: Int): Int = {
val instruction = arr(index)
if(instruction == 99){
return arr.head
}
val first = arr(arr(index+1))
val second = arr(arr(index+2))
val target = arr(index+3)
if(instruction == 1) arr(target) = first+second else arr(target) = first*second
intCodeHelper(arr, index+4)
}
val arrCopy = input.clone()
intCodeHelper(arrCopy, 0)
}
DAG 2, problem 2
def intCode2(input: Array[Int], intTarget: Int): Int = {
val result =
for(
i <- 0 to 100;
j <- 0 to 100 if {
val arrCopy = input.clone()
arrCopy(1) = i
arrCopy(2) = j
intCode(arrCopy)
} == intTarget) yield (i, j)
100 * result(0)._1 + result(0)._2
}
Del 1
const { p4 } = require('./puzzle_input');
const [start, end] = p4.split('-').map(o => parseInt(o, 10));
const isCandidate = pw => {
const pwSize = pw.length;
let prevC;
let haveTwoSameC = false;
for (let i = 0; i < pwSize; i++){
const c = parseInt(pw[i], 10);
if (prevC === c) {
haveTwoSameC = true;
}
if (c < prevC) {
return false;
}
prevC = c;
};
return haveTwoSameC;
}
let candidates = 0;
for (let intPw = start; intPw <= end; intPw++) {
const pw = intPw.toString();
if (isCandidate(pw)) {
candidates++;
}
}
console.log(candidates);
Del 2
const { p4 } = require('./puzzle_input');
const [start, end] = p4.split('-').map(o => parseInt(o, 10));
const isCandidate = pw => {
const pwLen = pw.length;
let counter = {};
let prevC = 0;
for (let i = 0; i < pwLen; i++) {
const c = pw[i];
if (c < prevC) {
return false;
}
if (!counter[c]) {
counter[c] = 0;
}
counter[c]++;
prevC = c;
}
for (const c in counter){
if (counter[c] === 2){
return true;
}
}
return false;
}
let candidates = 0;
for (let i = start; i < end; i++){
if (isCandidate(i.toString())){
candidates++;
}
}
console.log(candidates);
Dag 4 i Kotlin.
Reflektion / kommentar
Jag optimerade en del grejer frÄn början för jag tÀnkte att runtime skulle bli för lÄng annars, men sÄ verkar inte fallet ha varit
fun increment(value: Array<Int>, index: Int = value.size - 1): Array<Int> {
return if (value[index] == 9) {
if (index == 0) {
value
} else {
increment(value, index - 1)
}
} else {
val newValue = value[index] + 1
(index until value.size).forEach { value[it] = newValue }
value
}
}
fun validatePart1(value: Array<Int>): Boolean {
var doubleDigit = false
(1 until value.size).forEach {
if (value[it] == value[it - 1]) {
doubleDigit = true
}
if (value[it] < value[it - 1]) {
return false
}
}
return doubleDigit
}
fun validatePart2(value: Array<Int>): Boolean {
var doubleDigit = false
(1 until value.size).forEach {
val next = if (it == value.size - 1) -1 else value[it + 1]
val previous = if (it < 2) -1 else value[it - 2]
if (value[it] == value[it - 1] && next != value[it] && previous != value[it]) {
doubleDigit = true
}
if (value[it] < value[it - 1]) {
return false
}
}
return doubleDigit
}
fun solve(input: String, validate: (Array<Int>) -> Boolean): Int {
val parts = input.split("-")
val start = parts[0].map { it.toString().toInt() }.toTypedArray()
val end = parts[1].map { it.toString().toInt() }.toTypedArray()
var count = 0
while (true) {
if (validate(start)) {
count++
}
increment(start)
if (!start.indices.any { start[it] < end[it] }) {
return count
}
}
}
"Knowledge amplification. What he learns, we all learn. What he knows, we all benefit from."
Dag: 1
SprÄk: C++
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("input.txt");
int a, b;
while(file >> a){
while(a >= 9){
a = (int)((a/3)-2);
b += a;
}
}
std::cout << b;
return 0;
}
Dag: 2
SprÄk: C++
Satt och undrade lÀnge varför jag fick fel svar tills jag lÀste uppgiften igen och sÄg att man skulle Àndra nÄgra siffror innan man kör igÄng....
Del 1:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("input.txt");
char c;
int a = 0;
int arr[244] = {0};
while(file.get(c)){
if(c != ','){
arr[a] *= 10;
arr[a] += c -'0';
}
else{
a++;
}
}
arr[1] = 12;
arr[2] = 2;
a = 0;
while(1){
if(arr[a] == 1){
arr[arr[a+3]] = (arr[arr[a+1]] + arr[arr[a+2]]);
}
else if(arr[a] == 2){
arr[arr[a+3]] = (arr[arr[a+1]]) * (arr[arr[a+2]]);
}
else if(arr[a] == 99){
break;
}
else{
std::cout << "error, opcode not 1, 2, or 99" << std::endl;
}
a+=4;
}
std::cout << arr[0];
return 0;
Del 2:
#include <iostream>
#include <fstream>
#include <chrono>
using namespace std;
int main()
{
ifstream file("input.txt");
char c;
int a = 0;
int x = 0;
int y = 0;
int arr[244] = {0};
int arr2[244] = {0};
while(file.get(c)){
if(c != ','){
arr2[a] *= 10;
arr2[a] += c -'0';
}
else{
a++;
}
}
while(1){
copy(begin(arr2), end(arr2), begin(arr));
arr[1] = x;
arr[2] = y;
a = 0;
while(1){
if(arr[a] == 1){
arr[arr[a+3]] = (arr[arr[a+1]] + arr[arr[a+2]]);
}
else if(arr[a] == 2){
arr[arr[a+3]] = (arr[arr[a+1]]) * (arr[arr[a+2]]);
}
else if(arr[a] == 99){
break;
}
else{
cout << "error, opcode not 1, 2, or 99" << endl;
}
a+=4;
}
if(arr[0]== 19690720){
break;
}
if(y >= 99){
x++;
y=0;
}
else{
y++;
}
if(x >= 99){
break;
}
}
cout << "x= " << x << endl << "y= " << y << endl << 100 * x + y << endl;
cout << arr[0] << endl;
return 0;
}
Citera sÄ att jag hittar tillbaka! AMD Ryzen 7 5800X3D | MSI B450 Tomahawk Max | 32GB Ballistix @ 3733/16 | EVGA 2070 | Crucial MX500 2TB | EVGA G2 750W | Windows 10
- Idag Quiz: Har du koll pÄ det senaste inom processorkylare? 58
- Idag Cooler Master Ncore 100 Max â lĂ€ttbyggt minstingchassi 11
- IgÄr Nytt vetenskapligt genombrott kan lösa OLED-inbrÀnning 45
- IgÄr Microsoft vill göra handhÄllen Xbox 41
- 26 / 3 Microsoft patenterar teknik för bÀttre ray tracing-prestanda 27
- Idag Ny RAM-sparande funktion upptÀckt i Microsoft Edge 6
- Idag SĂ„ byter du till gamla Notepad i Windows 11 32
- Idag Microsoft Copilot kan snart köras direkt pÄ datorn 13
- IgÄr Stort steg för Windows pÄ ARM: Google slÀpper optimerat Chrome 26
- IgÄr Xbox-chef Àr öppen för fler spelbutiker pÄ konsol 23
- Idag Svenska Embracer sÀljer Gearbox för 4,9 miljarder kronor 12
- Idag Var femte anvÀndare har lÀmnat X sedan Musk tog över 106
- IgÄr Veckans frÄga: Hur gammalt Àr ditt Steam-konto? 162
- IgÄr Bluffkampanj sprider sig genom Googles AI-sökfunktion 11
- 26 / 3 82 studenter avstĂ€ngda för AI-fusk â Uppsala strĂ€ngast 55
- Google Drive sviker - Tips pÄ alternativa lösningar95
- Hur gör ni med jobbmobilen?149
- Dags att deklarera, vilka avdrag?5
- Benify-erbjudanden pÄ Samsung-TV [utbruten trÄd]1490
- Var femte anvÀndare har lÀmnat X sedan Musk tog över105
- Vad har ni i lön?12939
- Stutters och FPS besvÀr79
- Bilder pÄ ditt senaste inköp (2024) [inga produktbilder]419
- Ny RAM-sparande funktion upptÀckt i Microsoft Edge6
- Prisförslag/VÀrdering - Galaxy S22 Ultra SM-S908B/DS1
- SĂ€ljes Playstation 5 - Digital Edition
- SĂ€ljes Acer Nitro N50-600 (9400F, 1660 Ti, 32 GB RAM & 500 GB SSD)
- SÀljes UtförsÀljning: 3 stycken helt nya roomba robotdammsugare sÀljes till bra pris.
- SĂ€ljes Kingston 32GB (2x16GB) DDR5 6000MHz CL36 FURY Beast
- SĂ€ljes Gigabyte B650I Aorus Ultra AM5 - garanti
- SĂ€ljes apple macbook pro 16 m1 max 32gb ram 1tb ssd
- SĂ€ljes Apple iPad Pro 11'' 5G (gen 4)
- SĂ€ljes Xbox Series S
- SĂ€ljes B550-f/5900x/32gb
- SĂ€ljes Xbox Series X
- Ny RAM-sparande funktion upptÀckt i Microsoft Edge6
- Quiz: Har du koll pÄ det senaste inom processorkylare?58
- Svenska Embracer sÀljer Gearbox för 4,9 miljarder kronor12
- Cooler Master Ncore 100 Max â lĂ€ttbyggt minstingchassi11
- Var femte anvÀndare har lÀmnat X sedan Musk tog över105
- SĂ„ byter du till gamla Notepad i Windows 1132
- Microsoft Copilot kan snart köras direkt pÄ datorn13
- Stort steg för Windows pÄ ARM: Google slÀpper optimerat Chrome26
- Nytt vetenskapligt genombrott kan lösa OLED-inbrÀnning45
- Xbox-chef Àr öppen för fler spelbutiker pÄ konsol23