🌟 Advent of Code (AoC) 2022 🌟

PermalÀnk
Medlem ♄ ★
●

Dag: 5
SprÄk: Go

type stacks [][]string func main() { lines, err := helpers.ReadLines(os.Args[1]) if err != nil { panic(err) } re := regexp.MustCompile("([A-Z]|\\s{4})") first := true stacks1 := make(stacks, 0) stacks2 := make(stacks, 0) for _, line := range lines { if strings.Contains(line, "[") { res := re.FindAllStringSubmatch(line, -1) if first { first = false for range res { stack := make([]string, 0) stacks1 = append(stacks1, stack) } } stacks1.getCrates(res) } if line == "" { for _, stack := range stacks1 { helpers.Reverse(stack) stack2 := make([]string, len(stack)) copy(stack2, stack) fmt.Println(stack2) stacks2 = append(stacks2, stack2) } } if strings.Contains(line, "move") { stacks1.moveStacks(line, false) stacks2.moveStacks(line, true) } } for _, stack := range stacks1 { if len(stack) > 0 { fmt.Print(stack[len(stack)-1]) } } fmt.Println() for _, stack := range stacks2 { if len(stack) > 0 { fmt.Print(stack[len(stack)-1]) } } } func (s *stacks) getCrates(res [][]string) { for i, val := range res { str := val[1] char, _ := utf8.DecodeRuneInString(str) if unicode.IsLetter(char) { (*s)[i] = append((*s)[i], str) } } } func (s *stacks) moveStacks(instruction string, newRobot bool) { re := regexp.MustCompile("\\d+") res := re.FindAllStringSubmatch(instruction, -1) crates, from, to := helpers.GetInt(res[0][0]), helpers.GetInt(res[1][0])-1, helpers.GetInt(res[2][0])-1 if !newRobot { for i := 0; i < crates; i++ { (*s)[to] = append((*s)[to], (*s)[from][len((*s)[from])-i-1]) } } else { (*s)[to] = append((*s)[to], (*s)[from][len((*s)[from])-crates:]...) } (*s)[from] = (*s)[from][:len((*s)[from])-crates] }

Dold text
PermalÀnk
Medlem ♄ ★
●

Dag: 5
SprÄk: Elixir
Lösning: Github

Visa signatur

AMD Ryzen 7 1700X 3.8 GHz 20MB | ASUS PRIME X370-PRO | MSI GeForce GTX 1080 Gaming X 8GB | G.Skill 16GB DDR4 3200 MHz CL14 Flare X | Corsair RM650x 650W

PermalÀnk
Medlem ♄
●

Dag: 6
SprÄk: C#

Överraskande enkelt idag!

using System.Diagnostics; Console.WriteLine("Mickur's Advent of Code 2022 - Day 6!"); // Setup var input = File.ReadAllLines("input.txt"); const int partOneUniquesNeeded = 4; const int partTwoUniquesNeeded = 14; const int maxUniquesNeeded = partTwoUniquesNeeded > partOneUniquesNeeded ? partTwoUniquesNeeded : partOneUniquesNeeded; var sw = new Stopwatch(); sw.Start(); var uniqueCheckHashSet = new HashSet<char>(); var partOneAllUniqueFound = false; var partTwoAllUniqueFound = false; for (var i = 0; i < input[0].Length; i++) { uniqueCheckHashSet.Clear(); for (var j = 0; j < maxUniquesNeeded; j++) { if (i + j >= input[0].Length || uniqueCheckHashSet.Add(input[0][i + j]) == false) break; if (!partOneAllUniqueFound && j == partOneUniquesNeeded - 1) { Console.WriteLine($"Answer to part one: {i + partOneUniquesNeeded}"); partOneAllUniqueFound = true; } if (!partTwoAllUniqueFound && j == partTwoUniquesNeeded - 1) { Console.WriteLine($"Answer to part two: {i + partTwoUniquesNeeded}"); partTwoAllUniqueFound = true; } } if(partOneAllUniqueFound && partTwoAllUniqueFound) break; } sw.Stop(); Console.WriteLine($"{sw.ElapsedMilliseconds} ms ({sw.ElapsedTicks} ticks)");

Dold text

Körde lite BenchmarkDotNet pÄ lösningen, not bad, not bad at all!

| Method | Job | Runtime | neededUniquesInARow | Mean | Error | StdDev | Median | Ratio | RatioSD | Allocated | Alloc Ratio | |--------- |--------- |--------- |-------------------- |---------:|---------:|---------:|---------:|------:|--------:|----------:|------------:| | Solution | .NET 6.0 | .NET 6.0 | 4 | 31.72 us | 0.623 us | 0.970 us | 31.74 us | 1.00 | 0.00 | 232 B | 1.00 | | Solution | .NET 7.0 | .NET 7.0 | 4 | 31.03 us | 0.618 us | 1.702 us | 31.75 us | 0.94 | 0.07 | 232 B | 1.00 | | | | | | | | | | | | | | | Solution | .NET 6.0 | .NET 6.0 | 14 | 65.35 us | 1.272 us | 2.054 us | 65.71 us | 1.00 | 0.00 | 392 B | 1.00 | | Solution | .NET 7.0 | .NET 7.0 | 14 | 70.35 us | 1.397 us | 3.037 us | 70.90 us | 1.08 | 0.06 | 392 B | 1.00 |

Dold text
Visa signatur

CPU: 7950X 5GHz@1.1v | RAM: 32GB 6000MHz CL36 | GPU: KFAÂČ 3090 SG w/ AlphaCool Eisblock Aurora
Ljudkort: Modius + Magnius | Lurar: GoldPlanar GL2000 / Sennheiser HD 650 / Philips Fidelio X3 / Supreme CD-99

PermalÀnk
Medlem ♄ ★
●
Skrivet av GLaDER:

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

Mitt hjÀrta blöder.

Jag har ett script som lÀser in datan frÄn AoC och sparar i en fil <dag>.input. Av nÄgon outgrundlig anledning fungerade inte scriptet för att lÀsa dagens input, men det tog lÄÄÄng tid att förstÄ varför. "Problemet" var att min parsningsfunktion fortfarande returnerade en helt rimlig parsning (och eftersom jag gjorde copy-paste pÄ test-input sÄ fick jag rÀtt pÄ test-input).

Det tog nog 20 minuter för mig att lösa uppgiften; sen tog det vÀldigt lÄng tid att fatta varför jag fick fel svar.

Dold text

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
Visa signatur

:(){ :|:& };:

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

PermalÀnk
Medlem ♄ ★
●

Dag: 6
SprÄk: Python (oneliner)

print([(lambda n, s: [i + n for i in range(len(s)) if len(set(s[i:i+n ])) == n][0]) (n, open("input06").read()) for n in [4, 14]])

Dold text
PermalÀnk
Datavetare ♄ ★
●

Dag: 6
SprÄk: Go

package main import "fmt" const ( START_OF_PACKET_MARKER_LEN = 4 START_OF_MESSAGE_MARKER_LEN = 14 ) func isMarker(subSignal string) bool { for i, chA := range subSignal { for _, chB := range subSignal[i+1:] { if chA == chB { return false } } } return true } func markerOffset(signal string, markerLen int) int { for offset := 0; offset < len(signal)-markerLen-1; offset++ { maybeMarker := signal[offset : offset+markerLen] if isMarker(maybeMarker) { return offset + markerLen } } panic("No marker found") } func startOfPacketMarker(signal string) int { return markerOffset(signal, START_OF_PACKET_MARKER_LEN) } func startOfMessageMarker(signal string) int { return markerOffset(signal, START_OF_MESSAGE_MARKER_LEN) } func day6(input []string) { signal := input[0] fmt.Println(startOfPacketMarker(signal)) fmt.Println(startOfMessageMarker(signal)) } func init() { Solutions[6] = day6 }

Dold text

Implementerade först isMarker() genom att stoppa in tecknen i ett set och kolla att dess storlek blev lika stor som lÀngden pÄ indata, men tÀnkte att det faktiskt Àr enklare och lÄngt effektivare med tvÄ for-loopar (Go's motto verkar vara att föredra "trÄkiga" men enkla konstruktioner...)

Första Àr for-loopar, andra Àr set-manövern

BenchmarkDay6_startOfPacketMarker-8 165830 7206 ns/op 0 B/op 0 allocs/op BenchmarkDay6_startOfMessageMarker-8 26545 45001 ns/op 0 B/op 0 allocs/op BenchmarkDay6_startOfPacketMarker-8 28279 40486 ns/op 0 B/op 0 allocs/op BenchmarkDay6_startOfMessageMarker-8 1383 859868 ns/op 220101 B/op 2142 allocs/op

Dold text
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: 6
SprÄk: Node(js)

import { data } from '../input/day6.js'; const testData = 'bvwbjplbgvbhsrlpgdmjqwftvncz'; function foundDuplicates(substr) { const hash = {}; for (const c of substr) { if (hash[c]) return true; hash[c] = 'snus'; } return false; } function solve(input, n) { for (let i = 0; i+n < input.length; i++) { const str = input.substr(i, n); if (!foundDuplicates(str)) return i+n; } } const solutionA = () => { console.log(solve(data, 4)); } const solutionB = () => { console.log(solve(data, 14)); } export { solutionA, solutionB }

Dold text
PermalÀnk
Medlem ♄ ★
●

Dag: 6
SprÄk: F#, idag endast 5 rader - inkl I/O och en blankrad

let findFirstUnique cnt row = (row |> Seq.windowed cnt |> (Seq.findIndex (fun c-> (Set.ofSeq c |> Set.count) = cnt))) + cnt let input = System.IO.File.ReadAllText "input.txt" printfn "Task 1: %i" (findFirstUnique 4 input) printfn "Task 2: %i" (findFirstUnique 14 input)

Dold text
Visa signatur

Jag Àr en optimist; det Àr aldrig sÄ dÄligt sÄ att det inte kan bli sÀmre.

PermalÀnk
Medlem ♄
●

Dag: 6
SprÄk: Go

Jag var tvungen

go test -bench=. . goos: darwin goarch: amd64 pkg: aoc2022/06/a cpu: Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz BenchmarkPartOne-8 600711 1823 ns/op BenchmarkPartTwo-8 56715 21502 ns/op PASS ok aoc2022/06/a 2.719s

package main import ( "bufio" "fmt" "os" ) func getPartOne(row []rune) int { for i := 0; i < len(row)-3; i++ { r0 := row[i] r1 := row[i+1] r2 := row[i+2] r3 := row[i+3] if r0 != r1 && r0 != r2 && r0 != r3 && r1 != r2 && r1 != r3 && r2 != r3 { return i + 4 } } return 0 } func getPartTwo(row []rune) int { for i := 0; i < len(row)-13; i++ { r0 := row[i] r1 := row[i+1] r2 := row[i+2] r3 := row[i+3] r4 := row[i+4] r5 := row[i+5] r6 := row[i+6] r7 := row[i+7] r8 := row[i+8] r9 := row[i+9] r10 := row[i+10] r11 := row[i+11] r12 := row[i+12] r13 := row[i+13] if r0 != r1 && r0 != r2 && r0 != r3 && r0 != r4 && r0 != r5 && r0 != r6 && r0 != r7 && r0 != r8 && r0 != r9 && r0 != r10 && r0 != r11 && r0 != r12 && r0 != r13 && r1 != r2 && r1 != r3 && r1 != r4 && r1 != r5 && r1 != r6 && r1 != r7 && r1 != r8 && r1 != r9 && r1 != r10 && r1 != r11 && r1 != r12 && r1 != r13 && r2 != r3 && r2 != r4 && r2 != r5 && r2 != r6 && r2 != r7 && r2 != r8 && r2 != r9 && r2 != r10 && r2 != r11 && r2 != r12 && r2 != r13 && r3 != r4 && r3 != r5 && r3 != r6 && r3 != r7 && r3 != r8 && r3 != r9 && r3 != r10 && r3 != r11 && r3 != r12 && r3 != r13 && r4 != r5 && r4 != r6 && r4 != r7 && r4 != r8 && r4 != r9 && r4 != r10 && r4 != r11 && r4 != r12 && r4 != r13 && r5 != r6 && r5 != r7 && r5 != r8 && r5 != r9 && r5 != r10 && r5 != r11 && r5 != r12 && r5 != r13 && r6 != r7 && r6 != r8 && r6 != r9 && r6 != r10 && r6 != r11 && r6 != r12 && r6 != r13 && r7 != r8 && r7 != r9 && r7 != r10 && r7 != r11 && r7 != r12 && r7 != r13 && r8 != r9 && r8 != r10 && r8 != r11 && r8 != r12 && r8 != r13 && r9 != r10 && r9 != r11 && r9 != r12 && r9 != r13 && r10 != r11 && r10 != r12 && r10 != r13 && r11 != r12 && r11 != r13 && r12 != r13 { return i + 14 } } return 0 } func getRows(filename string) []rune { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) rows := make([][]rune, 0) for scanner.Scan() { row := scanner.Text() rows = append(rows, []rune(row)) } return rows[0] } func main() { fmt.Println("Part one:", getPartOne(getRows("../input.txt"))) fmt.Println("Part two:", getPartTwo(getRows("../input.txt"))) }

Dold text
PermalÀnk
Medlem ♄
●

Dag: 6
SprÄk: Haskell

Idag var mer min grej, dvs lite enklare! OcksÄ första gÄngen jag gör det innan jobbet (fast nu blir det brÄttom).

-- The program expects the input on stdin, ie -- $ ./solve < input import Data.Set main = interact solve solve :: String -> String solve input = "Problem 1: " ++ show (findUniq input 4) ++ "\n" ++ "Problem 2: " ++ show (findUniq input 14) ++ "\n" -- Find the index of the first unique substring -- of a particular length n. findUniq :: String -> Int -> Int findUniq s n = n + findHelper s n 0 -- Helper function to keep track of index while searching. findHelper :: String -> Int -> Int -> Int findHelper s len i | i > length s = 0 -- Base case, failed to find. | size (fromList (take len (drop i s))) == len = i | otherwise = findHelper s len (i+1)

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

Dold text
PermalÀnk
Medlem ♄
●

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

Idag lyckades jag Àntligen förutse del tvÄ sÄ inga kodÀndringar behövdes mellan delarna

include prelude, strformat proc part(input: string, windowSize: int, part: int) = for i in 0 .. input.high - windowSize - 1: block innerLoop: var cs: seq[char] for j in i ..< i + windowSize: let c = input[j] if c in cs: break innerLoop cs.add c echo &"Part {part}: {i + windowSize}" return when isMainModule: let input = readFile "input.txt" part(input, 4, 1) part(input, 14, 2)

Dold text
PermalÀnk
Medlem ♄ ★
●

Dag: 6
SprÄk: Elixir
Lösning: Github

Visa signatur

AMD Ryzen 7 1700X 3.8 GHz 20MB | ASUS PRIME X370-PRO | MSI GeForce GTX 1080 Gaming X 8GB | G.Skill 16GB DDR4 3200 MHz CL14 Flare X | Corsair RM650x 650W

PermalÀnk
Medlem ♄ ★
●

Dag: 6
SprÄk: C#

Man kunde ju definitivt ana vad del 2 skulle vara nÀr man satt och fnulade pÄ del 1 denna gÄng.

var input = "mjqjpqmgbljsphdztnvjfqwrcgsmlb"; int pt1 = 0; int pt2 = 0; for (int i = 3; i < input.Length; i++) { if (all_different(i - 3, i)) { if (pt1 == 0) { pt1 = i + 1; } } if (i >= 13 && all_different(i - 13, i)) { pt2 = i + 1; break; } } Console.WriteLine("Part 1: " + pt1); Console.WriteLine("Part 2: " + pt2); bool all_different(int beg, int end) { if (beg == end) { return true; } for (int i = beg + 1; i <= end; i++) { if (input[beg] == input[i]) return false; } return all_different(beg + 1, end); }

Dold text
lite optimeringar
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:6
SprÄk: Python

for n in range(len(signal_str)): if(len(set(signal_str[n:n+4]))) == 4: print(n+4) break

Dold text
PermalÀnk
Medlem ♄
●
Skrivet av Flexbert:

Dag: 6
SprÄk: Go

Jag var tvungen

go test -bench=. . goos: darwin goarch: amd64 pkg: aoc2022/06/a cpu: Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz BenchmarkPartOne-8 600711 1823 ns/op BenchmarkPartTwo-8 56715 21502 ns/op PASS ok aoc2022/06/a 2.719s

package main import ( "bufio" "fmt" "os" ) func getPartOne(row []rune) int { for i := 0; i < len(row)-3; i++ { r0 := row[i] r1 := row[i+1] r2 := row[i+2] r3 := row[i+3] if r0 != r1 && r0 != r2 && r0 != r3 && r1 != r2 && r1 != r3 && r2 != r3 { return i + 4 } } return 0 } func getPartTwo(row []rune) int { for i := 0; i < len(row)-13; i++ { r0 := row[i] r1 := row[i+1] r2 := row[i+2] r3 := row[i+3] r4 := row[i+4] r5 := row[i+5] r6 := row[i+6] r7 := row[i+7] r8 := row[i+8] r9 := row[i+9] r10 := row[i+10] r11 := row[i+11] r12 := row[i+12] r13 := row[i+13] if r0 != r1 && r0 != r2 && r0 != r3 && r0 != r4 && r0 != r5 && r0 != r6 && r0 != r7 && r0 != r8 && r0 != r9 && r0 != r10 && r0 != r11 && r0 != r12 && r0 != r13 && r1 != r2 && r1 != r3 && r1 != r4 && r1 != r5 && r1 != r6 && r1 != r7 && r1 != r8 && r1 != r9 && r1 != r10 && r1 != r11 && r1 != r12 && r1 != r13 && r2 != r3 && r2 != r4 && r2 != r5 && r2 != r6 && r2 != r7 && r2 != r8 && r2 != r9 && r2 != r10 && r2 != r11 && r2 != r12 && r2 != r13 && r3 != r4 && r3 != r5 && r3 != r6 && r3 != r7 && r3 != r8 && r3 != r9 && r3 != r10 && r3 != r11 && r3 != r12 && r3 != r13 && r4 != r5 && r4 != r6 && r4 != r7 && r4 != r8 && r4 != r9 && r4 != r10 && r4 != r11 && r4 != r12 && r4 != r13 && r5 != r6 && r5 != r7 && r5 != r8 && r5 != r9 && r5 != r10 && r5 != r11 && r5 != r12 && r5 != r13 && r6 != r7 && r6 != r8 && r6 != r9 && r6 != r10 && r6 != r11 && r6 != r12 && r6 != r13 && r7 != r8 && r7 != r9 && r7 != r10 && r7 != r11 && r7 != r12 && r7 != r13 && r8 != r9 && r8 != r10 && r8 != r11 && r8 != r12 && r8 != r13 && r9 != r10 && r9 != r11 && r9 != r12 && r9 != r13 && r10 != r11 && r10 != r12 && r10 != r13 && r11 != r12 && r11 != r13 && r12 != r13 { return i + 14 } } return 0 } func getRows(filename string) []rune { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) rows := make([][]rune, 0) for scanner.Scan() { row := scanner.Text() rows = append(rows, []rune(row)) } return rows[0] } func main() { fmt.Println("Part one:", getPartOne(getRows("../input.txt"))) fmt.Println("Part two:", getPartTwo(getRows("../input.txt"))) }

Dold text

Vilket Àr 30 gÄnger snabbare Àn varianten med tvÄ for loops och en map.

go test -bench=. . goos: darwin goarch: amd64 pkg: aoc2022/06/b cpu: Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz BenchmarkPartOne-8 19353 61947 ns/op BenchmarkPartTwo-8 1900 602046 ns/op PASS

package main import ( "bufio" "fmt" "os" ) func getFirstMarkerPosition(row []rune, size int) int { for i := 0; i < len(row)-size-1; i++ { set := make(map[int32]bool, size) set[row[i]] = true duplicateFound := false for j := i + 1; j < i+size; j++ { if _, ok := set[row[j]]; ok { duplicateFound = true break } else { set[row[j]] = true } } if !duplicateFound { return i + size } } return 0 } func getPartOne(row []rune) int { return getFirstMarkerPosition(row, 4) } func getPartTwo(row []rune) int { return getFirstMarkerPosition(row, 14) } func getRows(filename string) []rune { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) rows := make([][]rune, 0) for scanner.Scan() { row := scanner.Text() rows = append(rows, []rune(row)) } return rows[0] } func main() { fmt.Println("Part one:", getPartOne(getRows("../input.txt"))) fmt.Println("Part two:", getPartTwo(getRows("../input.txt"))) }

Dold text
PermalÀnk
Medlem ♄
●

Dag: 6
SprÄk: C#

Idag blev det inte mycket kod. Skapade iofs en hjÀlpmetod för att skapa ett "sliding window" frÄn en IEnumerable.

using AOC.Helpers.Extensions; namespace AOC2022.Puzzles; internal partial class Puzzle6 : Puzzle<int> { protected override void Solve(string[] lines) { One = FindMarker(lines[0], 4); Two = FindMarker(lines[0], 14); } private static int FindMarker(string message, int windowLength) => message .SlidingWindow(windowLength) .Select((windowStr, idx) => windowStr .GroupBy(x => x) .Count() == windowLength ? (idx + windowLength) : -1) .First(x => x > 0); }

Dold text
PermalÀnk
Datavetare ♄ ★
●
Skrivet av Flexbert:

Vilket Àr 30 gÄnger snabbare Àn varianten med tvÄ for loops och en map.

go test -bench=. . goos: darwin goarch: amd64 pkg: aoc2022/06/b cpu: Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz BenchmarkPartOne-8 19353 61947 ns/op BenchmarkPartTwo-8 1900 602046 ns/op PASS

package main import ( "bufio" "fmt" "os" ) func getFirstMarkerPosition(row []rune, size int) int { for i := 0; i < len(row)-size-1; i++ { set := make(map[int32]bool, size) set[row[i]] = true duplicateFound := false for j := i + 1; j < i+size; j++ { if _, ok := set[row[j]]; ok { duplicateFound = true break } else { set[row[j]] = true } } if !duplicateFound { return i + size } } return 0 } func getPartOne(row []rune) int { return getFirstMarkerPosition(row, 4) } func getPartTwo(row []rune) int { return getFirstMarkerPosition(row, 14) } func getRows(filename string) []rune { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) rows := make([][]rune, 0) for scanner.Scan() { row := scanner.Text() rows = append(rows, []rune(row)) } return rows[0] } func main() { fmt.Println("Part one:", getPartOne(getRows("../input.txt"))) fmt.Println("Part two:", getPartTwo(getRows("../input.txt"))) }

Dold text

Intressant att explicit unrolling ger sÄdan utvÀxling! KÀnns som det fortfarande finns förbÀttringspotential i Go-kompilatorn...

GĂ„r att snabba upp en lite mer generell variant m.h.a. bit-operationer

func isMarker(subSignal string) bool { seen := 0 for _, ch := range subSignal { chBit := 1 << (ch - 'a') if seen&chBit != 0 { return false } seen |= chBit } return true }

men fortfarande mÀrkbart snabbare med din hand-unrolled version (BenchmarkDayX_xxx)

BenchmarkDay6_startOfPacketMarker-8 198682 6132 ns/op 0 B/op 0 allocs/op BenchmarkDay6_startOfMessageMarker-8 52242 22553 ns/op 0 B/op 0 allocs/op BenchmarkDayX_part1-8 829896 1408 ns/op 0 B/op 0 allocs/op BenchmarkDayX_part2-8 70647 15078 ns/op 0 B/op 0 allocs/op

Dold text
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: 6
SprÄk: Kotlin

fun day6(word: String, number: Int) = word.windowed(number).indexOfFirst { it.toSet().size == number } + number println("Part 1: ${day6(input, 4)}. Part 2: ${day6(input, 14)}.")

Dold text
Visa signatur

i5-7600k . GTX 1080 . 16 GB

Quest 2

PermalÀnk
Medlem ♄
●

Dag: 6
SprÄk: Java
Lösning: Github

public class DaySix { public static void main(String[] args) { //String input -> buffered reader read in Queue<Character> que = new LinkedList<>(); int counter = 0; for(int i = 0; i < input.length(); i++) { if(que.size() != 4) { if(!que.contains(input.charAt(i))) { counter++; que.add(input.charAt(i)); } else { while(que.contains(input.charAt(i))) { que.poll(); } que.add(input.charAt(i)); counter++; } } } System.out.println("Part one: " + counter + " queue: " + que); Queue<Character> queTwo = new LinkedList<>(); int counterTwo = 0; for(int i = 0; i < input.length(); i++) { if(queTwo.size() != 14) { if(!queTwo.contains(input.charAt(i))) { counterTwo++; queTwo.add(input.charAt(i)); } else { while(queTwo.contains(input.charAt(i))) { queTwo.poll(); } queTwo.add(input.charAt(i)); counterTwo++; } } } System.out.println("Part two: " + counterTwo + " queue: " + queTwo); }

Dold text
PermalÀnk
Medlem ♄ ★
●

Dag: 6
SprÄk: C#

Inte jÀttenöjd med lösningen, men har velat leka lite mer med Span<T>. Var 2-3 gÄnger snabbare att köra pÄ span + slice Àn strings + substring. Att allokera Hashset med en initiell storlek i del 2 gav lite mer ocksÄ.

| Method | Job | Runtime | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Allocated | Alloc Ratio | |------- |--------- |--------- |----------:|---------:|---------:|-------------:|--------:|---------:|----------:|------------:| | Run_A | .NET 6.0 | .NET 6.0 | 87.90 us | 0.978 us | 0.867 us | baseline | | 85.0830 | 347.77 KB | | | Run_A | .NET 7.0 | .NET 7.0 | 84.99 us | 0.616 us | 0.576 us | 1.03x faster | 0.01x | 85.0830 | 347.77 KB | 1.00x more | | | | | | | | | | | | | | Run_B | .NET 6.0 | .NET 6.0 | 408.53 us | 8.062 us | 9.284 us | baseline | | 215.3320 | 881.23 KB | | | Run_B | .NET 7.0 | .NET 7.0 | 377.20 us | 3.299 us | 3.086 us | 1.08x faster | 0.03x | 215.3320 | 881.23 KB | 1.00x more |

public sealed class TuningTrouble : Puzzle<int> { public override int A(string data) { const int targetLength = 4; return FindPosition(data, targetLength); } public override int B(string data) { const int targetLength = 14; return FindPosition(data, targetLength); } private static int FindPosition(string data, int targetLength) { var span = data.AsSpan(); int tail = 0; for (int i = targetLength - 1; i < data.Length; i++) { var window = span.Slice(tail, targetLength); HashSet<char> seen = new HashSet<char>(targetLength); foreach (var t in window) { seen.Add(t); } if (seen.Count == targetLength) return i + 1; tail++; } return -1; } }

Dold text
Kodfix, benchmark fix
PermalÀnk
Medlem ♄ ★
●

Dag 6, uppgift 1 men 2:an Àr ju likadan. Utan list comprehension

with open("6.txt") as f: stream, i = f.read(), 0 while len({*stream[(i:=i+1)-4:i]}) != 4: pass print(i)

Dold text

Edit: Oj, glömde visst att lÀsa in datan ocksÄ sÄ det blev ingen two-liner

Visa signatur

1

PermalÀnk
Medlem ♄ ★
●

Dag: 6
SprÄk: js

insÄg nÀr jag var klar att den skulle kunna rÀkna fel om det finns en unik marker i slutet pÄ strÀngen eftersom index - length blir negativ i början men jag klarade mig

Edit: gick ju att skriva om som one-liner, yay.

console.log("htsslsmstsrrhlrrllqppfnpnzzqtqtjqttslttmvmsmbbnpbbznzjjmrmsrrnjjzczcfcqchcnnhrnrzrnrzzddtrrpjrprbpbwbswsqswqswsqsqffgngtgwtwbtbbhhslsrsmrmffgcgtcgcppnbpnpbnpptcptpltthjhwwlttrrlldzldzzzlssccrfrqfrfdfldfldfdzfdzzcnznwznzqqzpqzqdzzbbslbljlqjjvzjzgzqgqqqvsvffzjfzfmzzrjrhjhrhcrhhtgtmggchggcsggvtttwmmsspmpffzpfpjjnwwnpwwdttcfcmmlblwlvvqrqddcdwcwnnfqnqdnnncggflfdftddtftqthqhrrmsrmsrsffbccjnnjjgddppjmmldllhttqvqzvzrvrsslnlplrprtprtttnvnsvsvzzdndrnnnlznzcnnzwwzjjsnjnwjwqqczqcqwqppqnqqllgblbhhbbzbjzzwjzzrqzqggdppgcgwcclglhhwwgcccgcvvpbbrzzwszsqqjqrrczzvmvpprllsgstsnnnrvvsszgzddzttbccmjccwtccrbccnssdqsdsqqfgqfqbfqfjqqzqqmhmwhwffsjjcjffqmmwjwhjjqttpvvgddzjdddwndwdjdldgdsdmdzmdzmzqqszzcwwwjbbvvlplnpndnddjcjcttrgrggjvjsjvjssnsmshmhrmhhfvvdqqppmbbjnbnzzzwlzzfmmlttvptvpphlhwhzzwffcsfsppdssvsvgsgcscmmdwwpggtcgttmlmglgmmcsccmmgffnvvvvsscstctptzzcmcsclcffnwwndnwddmgmfmvffntfnndgdrrbmrrvprrjnjcnjjsgjgmmjjjqwqhhlfljfljlclttrgttmdmhhcncwncnmccnmnqqmhmwmdwdmdfdttnggcscfsftttcjchhqghhtdthtwtgwgttlffphfhtftpfttlgtltblljmljjsmsszgsghhnnmvnmnvmvmhvvtmmdqdppclplqljllzppwgpgvpvjpvvlwldlcdcmvfrbcqfdrgqjdmpvczgmtrbhtfgbctjghwfmpqtprlnvzvbmhnmgsnbcqpdqhtstncmtrvwmjzzmsbprfvmszgvdwjwchzcvmzncfblffwvwwrdqpfnvrtlftnvhcqpwfgzdnmpqthblmqzhbdbdhmqvscfrpbjbgjgdndhlnnpcrrmrlghcwvmmmhbvdsrztbpdvhwhsphmgblzfpflhnbrvjsgsbvgcfwdlbmbsmbqfwczhhbbwntsczhljgvdwpsfmjppmdwcfchhvtrwlfgqrzbtzndqwbwqflpthhgtzrfmspfnlrrvrjttwnzzfsbzlvfwlntvcqhfntllsrdgqjdbrbvnmjgfsqshmcgtsmlrzjmmqbpfdfhlghqjnjrcnzvvmbwhwfwpbbsmpdmvvznstqpjwmthncjsvfmbhwtbfqgfmvhhwrwzrzccbmmrngfbcqgsdjlfwrlzqwrbhvhmjzqqtgqvjwgllhhgphjthwnscndjfhrdzjctthwfszztvtzcnvsnfdwnvrrbjzplgnghfsvnflhctjntrpzfgjnfzlmwzrvqcfdqqscrffjshhgmvlgdtqpbllfdspdhcccqbmpqcgctljwzdszbfzsltfmdrcvmjqmpvzzhnczlfdbrmsvfffmfzjvnthghqgtnvjtflzrrnrhqshtzslbmbghvtqcmbdgzcmmrpbtqlzbzjhhgfcbrbcztlhdcfqccqsgdqdfrvlsprbhwhtmjfbzlzfpcslcddzdhbhstvqjgdfwdwzfhrzpthnzgmzrrbrszvcwhbdczzcnqsqrwdpmgdmcdmccmfdwdfmzpbbsdtjlmlvcnvhhgcltwmpzqmjlpbsbfrrntrbmrrmgqrdsbfcgnqvnmwwgnmvvpjzpwbvwfzzfcfrbgdshrvbpdlbpzdsvjnrsmfttqgbngjbqcnhhhmrnlgwjnlfcsdwccqqlzcdrcqnjlmsfqldgdmwlctstcvqbvvwvhvrnhvtgpcnsstnhvlttdnstlndnpdglqlbgggqlwqpfztgzvhqqwbctvgtrmrbpmvwlztsfbrmhhpfdtnsjcjmngsqtzvhqjnwmgcrjbhvghpnrjlrhjfrfrmbzvprpzlcshbqtlnlmqmfhsmbznjmpzwljccngbsvqqmghqsqwwmtqhgddnpcmmlfvmplgptzmfsmpntprnwlpjmsdsntpmpnhwlqgfwslrnjlmvhvqsnlcssvrqvtvfhhghbhnvmpngtdmrcmftjmwgnptbmjcwvrqqbczmtdprlltcjcggvffvjwdthbhvjvhbsmfnstqvczmvsgsqfjmddszzrwnbrbvlhgltjddczwpzpsgfgbtmgmssbszhjfbprpbgsqpvgwfnmpcdwfzwbfbtfwhjbjgrctcwqgfhpvjpjssmcpppwpbnlfsrmbzqdpmpmqjtzqmqswpfhfvfltwnfbltvdmfgmpbhzzdrbtnmmjfqgtrgmrbsgplfrmlnjrggtslngnphcvcwvqsdftlhddhpsdwlhzcrfwgwbndplwjmtrltmswwdqjpgmmcdchllzdgpfpfrvqrmvppvzcrvbswzdclnqnqvmfvjtpzpvzlmbngtrrjwpgqjgrrqbqwcvjlgqzddtcfmmrqtnjppqvztfpdrdmjpsqqvzrhwjgvdwwdtmrzrvhwgsqvjjrtsdtwfwhrbcsqdblhgwzghrqrqtfbzszrmjqbhrtsrcfjlzbcjmdnpthrtbhtzmhgpfcqndwpmtlvzschzzcqdnzdrfhczsrscvttlpslrzgvwprwppmpfjqwhtnhzcdjjwmsnvqzmtlzsdpbdtdtsmbmjszsglrldcsgtnmbgsjfmnrftnmvnjtswrmdthvstmdlsnsmrbqhdlpnmnhjhcccgnzrrsljvwswmhjqrrfbwwhgrcttsdcjsdtlgmgblfnvwmgztbbzlbrdnspfnvwvhzlztdhlzhwwppgwwvrhfbjvrmjpjflqzbdnlvptmrsggqmzgmzlsdzbfqnqzzdnzfgmhncvwmgrcfrmlnwzcwdsvtwbvcqpmgcczbnnfdrlsgnfgnpbdstdmwhlprnzvhjpznsgwhfhzfwmjsvcbwccpsnfgbzrltcbwczcmzwljcswgwjnhwtjrjvgrggsrqszscrjcghnwdzpzhttrjcgwvmtcwmrhvwptlgfjpdjpnhphmzdgfdvsncswbdvjdtsgdtlsgjljlczgrwbswtbwrcfpmhgfjfnhpsmfrrtcjmpvvscmgftpprdmbjwcvhzbrmpbvhgzwftwtvvhrjmljgjhbpnbnfntmjhvjrzwlqbtqlrfbblgmfsbgzhhscgwgzrwvflnfctngtwbvdbbgspntclnbwgpppjgbrlqvtfznpdttrsplvjfsgbjwjprbvdfvjtffbhsjwgbsfschfnmlqdfzmdwzvfctjjvzncdvrdttlpvpgvsssflpfnrzgfznzlldrbgnnztngtlbbrmrmlfnnspsvvsfzfbmsblmzdwqcrftvnbvdlhgdqjtglclpzrchtlffrfwslqjvbfpvnhmdgqrcjtbhmjqwqzpfndqbwldbzmwqsptdccczmhwmdqqzcqvmbbnmqndtspmbtggcghdhsfgrjgvwjdbwmltbhdvdtgqnpqhwmhzpzbqjtnlftqrjbsvtwtgpmvpnfwdtsjgdtfnlntpgrmwphphrrzhbdrbzhtqddwvptdllntjzldzrndhfjwdfnmtjmjtfmndbvlwgmlcmwwlpfdjwbfznbllbmqrlmvljngvpmdlqmvdvwvpqwlbqssqcbnrmhdvrzwljstghmhntwsbqmnlpgthbwmrznbbggthtjhnndnqbzmcrtftcbnpctqjzghdfcvmmvpqwtnntstlspfsgwfdbrlsbwgbhhbfcvwrjclsgmmbqmmjwtdjqppjvcbnbvfwczlqzbtnlhzhssglgnlm".split('').findIndex((_, index) => new Set(input.slice(index - 14, index)).size === 14))

Dold text
Visa signatur

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

PermalÀnk
Medlem ♄
●
Skrivet av Yoshman:

Intressant att explicit unrolling ger sÄdan utvÀxling! KÀnns som det fortfarande finns förbÀttringspotential i Go-kompilatorn...

GĂ„r att snabba upp en lite mer generell variant m.h.a. bit-operationer

func isMarker(subSignal string) bool { seen := 0 for _, ch := range subSignal { chBit := 1 << (ch - 'a') if seen&chBit != 0 { return false } seen |= chBit } return true }

men fortfarande mÀrkbart snabbare med din hand-unrolled version (BenchmarkDayX_xxx)

BenchmarkDay6_startOfPacketMarker-8 198682 6132 ns/op 0 B/op 0 allocs/op BenchmarkDay6_startOfMessageMarker-8 52242 22553 ns/op 0 B/op 0 allocs/op BenchmarkDayX_part1-8 829896 1408 ns/op 0 B/op 0 allocs/op BenchmarkDayX_part2-8 70647 15078 ns/op 0 B/op 0 allocs/op

Dold text

Intressant, mÄste lÀra mig bit operations.

https://github.com/johanneslarsson/aoc-2022/tree/main/06

Dold text
PermalÀnk
Medlem ♄ ★
●
Skrivet av Yoshman:

Intressant att explicit unrolling ger sÄdan utvÀxling! KÀnns som det fortfarande finns förbÀttringspotential i Go-kompilatorn...

GĂ„r att snabba upp en lite mer generell variant m.h.a. bit-operationer

Dold text

Maskningen testar mot alla tidigare lÀsta tecken i en operation, men nÀr man fÄr en trÀff sÄ undviker man att lÀsa de kvarvarande av de 14 tecknen frÄn minne vilka @Flexbert redan hade lÀst in före testerna. Din loop gör sannolikt livet lÀttre för branch prediction ocksÄ.

Dold text
PermalÀnk
Medlem ♄
●

Sent input

Postar mina lösningar hÀr lite sent dÄ jag sÄg denna utmaning igÄr och har pillat med som sedan dess, mycket kul och lÀrorikt för nÄgon som precis börjat programmera (2 mÄnader) och letat efter saker att göra för att lÀra sig lite. Alla svar blir i C# dÄ det Àr den enda jag kan lite halvt

Dag 1 följer hÀr, inte sÄ mycket att orda om utan rÀtt sÄ lÀtt.

string readText = File.ReadAllText("Day1.txt"); String[] backpacks = readText.Split("\n"); List<int> elvesTotal = new List<int>(); elvesTotal.Add(0); int k = 0; for (int i = 0; i < backpacks.Length; i++) { if (backpacks[i].Length == 1) { k++; elvesTotal.Add(0); } else { elvesTotal[k] = elvesTotal[k] + Convert.ToInt32(backpacks[i]); } } elvesTotal.Sort(); elvesTotal.Reverse(); Console.WriteLine("Day1:"); Console.WriteLine($"Step1: {elvesTotal.Max()} pounds Step2 {elvesTotal[0]+ elvesTotal[1]+ elvesTotal[2]} pounds");

Dold text
PermalÀnk
Medlem ♄
●

Dag 2
C#
Inte sÄ mycket spÀnnande hÀr, lite pill med if satserna dag 2 bara

string readText = File.ReadAllText("Day2.txt"); String[] choices = readText.Split("\n"); int scoreMe=0; for(int i = 0; i < choices.Length; i++) { if (choices[i][2] == 'Y') scoreMe = scoreMe + 2; if (choices[i][2] == 'X') scoreMe = scoreMe + 1; if (choices[i][2] == 'Z') scoreMe = scoreMe + 3; if (choices[i][0] == 'A' && choices[i][2]=='Y') scoreMe = scoreMe + 6; if (choices[i][0] == 'B' && choices[i][2] == 'Z') scoreMe = scoreMe + 6; if (choices[i][0] == 'C' && choices[i][2] == 'X') scoreMe = scoreMe + 6; if (choices[i][0] == 'A' && choices[i][2] == 'X') scoreMe = scoreMe + 3; if (choices[i][0] == 'B' && choices[i][2] == 'Y') scoreMe = scoreMe + 3; if (choices[i][0] == 'C' && choices[i][2] == 'Z') scoreMe = scoreMe + 3; } int scoreMe2 = scoreMe; scoreMe =0; for(int i = 0; i < choices.Length; i++) { if (choices[i][0] == 'A' && choices[i][2] == 'Y') scoreMe = scoreMe + 4; if (choices[i][0] == 'B' && choices[i][2] == 'Y') scoreMe = scoreMe + 5; if (choices[i][0] == 'C' && choices[i][2] == 'Y') scoreMe = scoreMe + 6; if (choices[i][0] == 'A' && choices[i][2] == 'X') scoreMe = scoreMe + 3; if (choices[i][0] == 'B' && choices[i][2] == 'X') scoreMe = scoreMe + 1; if (choices[i][0] == 'C' && choices[i][2] == 'X') scoreMe = scoreMe + 2; if (choices[i][0] == 'A' && choices[i][2] == 'Z') scoreMe = scoreMe + 8; if (choices[i][0] == 'B' && choices[i][2] == 'Z') scoreMe = scoreMe + 9; if (choices[i][0] == 'C' && choices[i][2] == 'Z') scoreMe = scoreMe + 7; } Console.WriteLine(); Console.WriteLine("Day2:"); Console.WriteLine("My Score step 1 " + scoreMe2+" step 2: "+scoreMe);

Dold text
PermalÀnk
Medlem ♄
●

Dag 3
C#

Tog lite tid dÄ jag dels missuppfattade att man bara skulle rÀkna en uppsÀttnings poÀng och inte fler om det fanns fler par och sedan gjorde jag en miss i inlÀsningen med att lÀsa in allt i en strÀng och sedan dela upp i en array vilket gjorde att \n stannade kvar och gjorde pÄsarna olika stora. Mycket huvudbry innan jag kom pÄ det. C#

String[] rucksacks = File.ReadAllLines("Day3.txt"); int sum = 0; for (int i = 0; i < rucksacks.Length; i++) { char[] chars = rucksacks[i].ToCharArray(); bool[] checkDouble = new bool[100]; bool[] checkDouble2 = new bool[100]; for (int j = 0; j < (chars.Length / 2); j++) { for (int k = chars.Length-1; k > (chars.Length/2)-1; k--) { if (chars[j] == chars[k] && checkDouble[j] != true && checkDouble2[k] != true) { checkDouble[j] = true; checkDouble2[k] = true; if (Char.IsUpper(chars[j]) == true) { sum = sum + chars[j] - 38; } else { sum = sum + chars[j] - 96; } } else if (chars[j] == chars[k] && checkDouble[j] == true) checkDouble2[k] = true; } } } int sum1=sum; sum = 0; for (int i = 0; i < rucksacks.Length; i=i+3) { char[] chars = rucksacks[i].ToCharArray(); char[] chars2 = rucksacks[i+1].ToCharArray(); char[] chars3 = rucksacks[i+2].ToCharArray(); bool[] checkDouble = new bool[300]; bool[] checkTripple = new bool[300]; string contains = ""; char result=' '; for (int j = 0; j < chars.Length; j++) { for(int k = 0; k < chars2.Length; k++) { if (chars[j] == chars2[k]) contains = contains + chars[j]; } for (int k = 0; k < chars3.Length; k++) { if (chars[j] == chars3[k] && contains.Contains(chars[j])) result = chars[j]; } } if (Char.IsUpper(result) == true) { sum = sum + result - 38; } else { sum = sum + result - 96; } } Console.WriteLine(); Console.WriteLine("Day3:"); Console.WriteLine("My Score step1 "+sum1+" step2: "+sum);

Dold text
PermalÀnk
Medlem ♄
●

Dag 4
C#

Kul uppgift som var hyfsat enkel att lösa

String[] pairs = File.ReadAllLines("Day4.txt"); int result = 0; for(int i = 0; i < pairs.Length; i++) { string[] split = pairs[i].Split(new char[] {'-', ',' }); if (int.Parse(split[0]) <= int.Parse(split[2]) && int.Parse(split[1]) >= int.Parse(split[3])) result++; else if (int.Parse(split[0]) >= int.Parse(split[2]) && int.Parse(split[1]) <= int.Parse(split[3])) result++; } int result1 = result; result = 0; for (int i = 0; i < pairs.Length; i++) { string[] split = pairs[i].Split(new char[] { '-', ',' }); int[] overlap= new int[100]; int[] overlap2 = new int[100]; for (int j = 0; j < overlap.Length; j++) { if (int.Parse(split[1]) >= int.Parse(split[0])+j) overlap[j] = int.Parse(split[0]) + j; if (int.Parse(split[3]) >= int.Parse(split[2]) + j) overlap2[j] = int.Parse(split[2]) + j; } for(int j = 0; j < overlap.Length; j++) { if (overlap[j] == int.Parse(split[2]) || overlap[j] == int.Parse(split[3])) { result++; break; } else if (overlap2[j] == int.Parse(split[0]) || overlap2[j] == int.Parse(split[1])) { result++; break; } } } Console.WriteLine(); Console.WriteLine("Day4:"); Console.WriteLine("Step1 result " + result1 + " step2: "+result);

Dold text
PermalÀnk
Medlem ♄
●

Dag 5
C#

Denna uppgift tyckte jag var riktigt kul, snurrade in mig pÄ tok för mycket i hur jag skulle lÀsa in och hÄlla lÄdorna och vilken arraystruktur jag skulle ha. Höll pÄ för lÀnge med det och nÀr det vÀl var löst med lÄdorna pÄ rÀtt plats var logiken relativt enkel Àven om jag Àr lite tjatig och bara löser alla uppgifter med for loopar :).

del 1

String[] data = File.ReadAllLines("Day5.txt"); char[,] stacks =new char[9,100]; for (int i = 0; i < stacks.GetLength(0); i++) { for (int j = 0; j < stacks.GetLength(1); j++) { stacks[i, j] = ' '; } } int koll = 0; for(int j = 7; j > -1; j--) { if (data[j][1] != ' ') stacks[0, koll] = data[j][1]; else stacks[0, koll] = ' '; if (data[j][5] != ' ') stacks[1, koll] = data[j][5]; else stacks[1, koll] = ' '; if (data[j][9] != ' ') stacks[2, koll] = data[j][9]; else stacks[2, koll] = ' '; if (data[j][13] != ' ') stacks[3, koll] = data[j][13]; else stacks[3, koll] = ' '; if (data[j][17] != ' ') stacks[4, koll] = data[j][17]; else stacks[4, koll] = ' '; if (data[j][21] != ' ') stacks[5, koll] = data[j][21]; else stacks[5, koll] = ' '; if (data[j][25] != ' ') stacks[6, koll] = data[j][25]; else stacks[6, koll] = ' '; if (data[j][29] != ' ') stacks[7, koll] = data[j][29]; else stacks[7, koll] = ' '; if (data[j][33] != ' ') stacks[8, koll] = data[j][33]; else stacks[8, koll] = ' '; koll++; } for (int i = 10; i < data.Length; i++) { string[] commands = data[i].Split(' '); char save=' '; for(int j = 0; j < int.Parse(commands[1]); j++) { for (int k = stacks.GetLength(1)-1; k > -1; k--) { if (stacks[int.Parse(commands[3])-1, k]!=' ') { save = stacks[int.Parse(commands[3]) - 1, k]; stacks[int.Parse(commands[3])-1, k] = ' '; break; } } for (int k = stacks.GetLength(1) - 1; k > -1; k--) { if (stacks[int.Parse(commands[5])-1, k] != ' ') { stacks[int.Parse(commands[5]) - 1, k+1] = save; break; } else if(k==0) stacks[int.Parse(commands[5]) - 1, k + 1] = save; } } } string answer = ""; for (int i = 0; i < stacks.GetLength(0); i++) { for (int j = 1; j < stacks.GetLength(1); j++) { if(stacks[i,j] == ' ') { answer = answer + stacks[i, j - 1]; break; } } } Console.WriteLine(); Console.WriteLine("Day5:"); Console.Write("Step1 result "+answer);

Dold text

del 2

String[] data = File.ReadAllLines("Day5.txt"); char[,] stacks = new char[9, 100]; char[] save = new char[50]; for (int i = 0; i < stacks.GetLength(0); i++) { for (int j = 0; j < stacks.GetLength(1); j++) { stacks[i, j] = ' '; } } int koll = 0; for (int j = 7; j > -1; j--) { if (data[j][1] != ' ') stacks[0, koll] = data[j][1]; else stacks[0, koll] = ' '; if (data[j][5] != ' ') stacks[1, koll] = data[j][5]; else stacks[1, koll] = ' '; if (data[j][9] != ' ') stacks[2, koll] = data[j][9]; else stacks[2, koll] = ' '; if (data[j][13] != ' ') stacks[3, koll] = data[j][13]; else stacks[3, koll] = ' '; if (data[j][17] != ' ') stacks[4, koll] = data[j][17]; else stacks[4, koll] = ' '; if (data[j][21] != ' ') stacks[5, koll] = data[j][21]; else stacks[5, koll] = ' '; if (data[j][25] != ' ') stacks[6, koll] = data[j][25]; else stacks[6, koll] = ' '; if (data[j][29] != ' ') stacks[7, koll] = data[j][29]; else stacks[7, koll] = ' '; if (data[j][33] != ' ') stacks[8, koll] = data[j][33]; else stacks[8, koll] = ' '; koll++; } for (int i = 10; i < data.Length; i++) { string[] commands = data[i].Split(' '); for (int k = stacks.GetLength(1) - 1; k > -1; k--) { if (stacks[int.Parse(commands[3]) - 1, k] != ' ') { for (int j = 0; j < int.Parse(commands[1]); j++) { save[j] = stacks[int.Parse(commands[3]) - 1, k-j]; stacks[int.Parse(commands[3]) - 1, k-j] = ' '; } break; } } for (int k = stacks.GetLength(1) - 1; k > -1; k--) { if (stacks[int.Parse(commands[5]) - 1, k] != ' ') { int counter = 1; for (int j = int.Parse(commands[1]) - 1; j > -1; j--) { stacks[int.Parse(commands[5]) - 1, k + counter] = save[j]; counter++; save[j] = ' '; } break; } else if (k == 0) { int counter = 1; for (int j = int.Parse(commands[1]) - 1; j > -1; j--) { stacks[int.Parse(commands[5]) - 1, k + counter] = save[j]; counter++; save[j] = ' '; } } } } string answer = ""; for (int i = 0; i < stacks.GetLength(0); i++) { for (int j = 1; j < stacks.GetLength(1); j++) { if (stacks[i, j] == ' ') { answer = answer + stacks[i, j - 1]; break; } } } Console.Write(" Step2 result " + answer);

Dold text
PermalÀnk
Medlem ♄
●

Dag 6
C#

Efter att ha strulat med dag 5 var det ju skönt att dag 6 var enkel, kul uppgift ÀndÄ

string readText = File.ReadAllText("Day6.txt"); int step1 = 0;int step2 = 0; for(int i = 3; i < readText.Length; i++) { if (readText[i] != readText[i - 1] && readText[i] != readText[i - 2] && readText[i] != readText[i - 3]) if (readText[i - 1] != readText[i] && readText[i - 1] != readText[i - 2] && readText[i - 1] != readText[i - 3]) if (readText[i - 2] != readText[i - 1] && readText[i - 2] != readText[i] && readText[i - 2] != readText[i - 3]) if (readText[i - 3] != readText[i - 1] && readText[i-3] != readText[i - 2] && readText[i-3] != readText[i]) { step1 = i + 1; break; } } for (int i = 0; i < readText.Length; i++) { if (step2 > 0) break; int check = 0; for(int j=0; j < 14; j++) { check = 0; for (int k = 0; k < 14; k++) { if(readText[i+j] == readText[i+k] && i+j!=i+k) { check = 1; break; } } if (check == 1) { break; } else if (j == 13) step2 = i + 14; } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Step1 result "+step1+" step2 result "+step2);

Dold text