Created
December 20, 2021 14:27
-
-
Save almendar/290b873f1ac5ccac45b7fb2a24f0bad8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"math" | |
"strings" | |
) | |
// Image enhancing algorithms | |
type IEA []rune | |
type Image [][]rune | |
func (iea IEA) String() string { | |
return string(iea) | |
} | |
func (iea Image) String() string { | |
sb := strings.Builder{} | |
sb.WriteString("\n") | |
for _, v := range iea { | |
sb.WriteString(string(v)) | |
sb.WriteString("\n") | |
} | |
return sb.String() | |
} | |
func (img Image) Lits() int { | |
counter := 0 | |
for _, row := range img { | |
for _, rune := range row { | |
if rune == '#' { | |
counter += 1 | |
} | |
} | |
} | |
return counter | |
} | |
func readInput(file string) (IEA, Image) { | |
bytes, err := ioutil.ReadFile(file) | |
if err != nil { | |
log.Fatal(err) | |
} | |
S := strings.Split(string(bytes), "\n\n") | |
IEA := make(IEA, 0) | |
for _, rune := range S[0] { | |
IEA = append(IEA, rune) | |
} | |
image := make(Image, 0) | |
for _, line := range strings.Split(S[1], "\n") { | |
image = append(image, []rune(line)) | |
} | |
return IEA, image | |
} | |
func tranform(in string) int { | |
l := len(in) - 1 | |
counter := 0 | |
for i, v := range in { | |
if v == '#' { | |
counter += int(math.Pow(2, float64((l - i)))) | |
} | |
} | |
return counter | |
} | |
func task(input string, iteration int) { | |
iea, image := readInput(input) | |
background := '.' | |
for it := 0; it < iteration; it++ { | |
lenY := len(image) | |
lenX := len(image[0]) | |
getPoint := func(x, y int, bgk rune) rune { | |
if x < 0 || x >= lenX { | |
return bgk | |
} | |
if y < 0 || y >= lenY { | |
return bgk | |
} | |
return image[y][x] | |
} | |
nextImage := make(Image, lenY+2) | |
for yi := -1; yi < lenY+1; yi++ { | |
for xi := -1; xi < lenX+1; xi++ { | |
s := "" | |
for i := -1 + yi; i <= 1+yi; i++ { | |
for j := -1 + xi; j <= 1+xi; j++ { | |
s += string(getPoint(j, i, background)) | |
} | |
} | |
index := tranform(s) | |
nextImage[yi+1] = append(nextImage[yi+1], iea[index]) | |
} | |
} | |
image = nextImage | |
switch background { | |
case '.': | |
background = iea[tranform(".........")] | |
case '#': | |
background = iea[tranform("#########")] | |
} | |
} | |
fmt.Printf("Day20 nr of iteration %d %s - %v\n", iteration, input, image.Lits()) | |
} | |
func main() { | |
// 35 | |
task("example.txt", 2) | |
// 4964 | |
task("input.txt", 2) | |
// 3351 | |
task("example.txt", 50) | |
// 13202 | |
task("input.txt", 50) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment