Browse Source

Solved part2

Piotr Czajkowski 1 year ago
parent
commit
796f2fe5ca
1 changed files with 59 additions and 0 deletions
  1. 59 0
      10/code.go

+ 59 - 0
10/code.go

@@ -74,6 +74,63 @@ func part1(commands []command) int {
 	return result
 }
 
+func inSprite(pixel int, sprite int) bool {
+	return pixel >= sprite-1 && pixel <= sprite+1
+}
+
+func putMark(pixel int, sprite int) byte {
+	if inSprite(pixel, sprite) {
+		return '#'
+	}
+
+	return '.'
+}
+
+func part2(commands []command) [][]byte {
+	sprite := 1
+	currentLimit := 40
+	period := 40
+	absoluteLimit := 220
+	cycles := 0
+	totalCycles := 0
+	var result [][]byte
+	currentRow := make([]byte, period)
+
+	for i := range commands {
+		if cycles > absoluteLimit {
+			break
+		}
+
+		end := 1
+		if commands[i].instruction == addx {
+			end++
+		}
+
+		for j := 0; j < end; j++ {
+			cycles++
+			currentRow[cycles-1] = putMark(cycles-1, sprite)
+			if cycles == currentLimit {
+				result = append(result, currentRow)
+				totalCycles += cycles
+				currentRow = make([]byte, period)
+				cycles = 0
+			}
+		}
+
+		if commands[i].instruction == addx {
+			sprite += commands[i].value
+		}
+	}
+
+	return result
+}
+
+func printScreen(screen [][]byte) {
+	for i := range screen {
+		fmt.Println(string(screen[i]))
+	}
+}
+
 func main() {
 	if len(os.Args) < 2 {
 		log.Fatal("You need to specify a file!")
@@ -88,4 +145,6 @@ func main() {
 
 	commands := readInput(file)
 	fmt.Println("Part1:", part1(commands))
+	fmt.Println("Part2:")
+	printScreen(part2(commands))
 }