109 lines
3.0 KiB
Python
109 lines
3.0 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
#file = "./ex.txt"
|
|
#f_rows = 3
|
|
#f_columns = 7
|
|
|
|
file = "./input.txt"
|
|
f_rows = 6
|
|
f_columns = 50
|
|
|
|
from time import time
|
|
from copy import deepcopy
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
start_time = time()
|
|
|
|
def create_field(columns:int, rows:int) -> list[list[str]]:
|
|
result = []
|
|
for r in range(rows):
|
|
row = []
|
|
for col in range(columns):
|
|
row.append(".")
|
|
result.append(row)
|
|
return result
|
|
|
|
def print_field(f):
|
|
for r in f:
|
|
for s in r:
|
|
print(s, end="")
|
|
print()
|
|
|
|
def read_file(filename:str)->list[list[str]]:
|
|
result = []
|
|
input_file = open(filename, "r")
|
|
for line in input_file:
|
|
line = line.strip()
|
|
if line == "":
|
|
continue
|
|
else:
|
|
result.append(line.split())
|
|
input_file.close()
|
|
return result
|
|
|
|
def do_command(c:list[str], f:list[list[str]])->list[list[str]]:
|
|
result = deepcopy(f)
|
|
if c[0] == "rect":
|
|
co, ro = command[1].split("x")
|
|
for i in range(int(ro)):
|
|
for j in range(int(co)):
|
|
result[i][j] = "#"
|
|
|
|
elif c[0] == "rotate" and c[1] == "row":
|
|
selected_row = int(c[2].split("=")[1])
|
|
row_shift_by = int(c[4])
|
|
for _ in range(row_shift_by):
|
|
r_tmp = result[selected_row][f_columns-1]
|
|
for i in range(f_columns-1):
|
|
result[selected_row][f_columns-i-1] = result[selected_row][f_columns-i-2]
|
|
result[selected_row][0] = r_tmp
|
|
|
|
elif c[0] == "rotate" and c[1] == "column":
|
|
selected_column = int(c[2].split("=")[1])
|
|
column_shift_by = int(c[4])
|
|
for _ in range(column_shift_by):
|
|
r_tmp = result[f_rows-1][selected_column]
|
|
for i in range(f_rows-1):
|
|
result[f_rows-i-1][selected_column] = result[f_rows-i-2][selected_column]
|
|
result[0][selected_column] = r_tmp
|
|
return result
|
|
|
|
def count_pixel(f:list[list[str]])->int:
|
|
result = 0
|
|
for r in f:
|
|
for c in r:
|
|
if c == "#":
|
|
result += 1
|
|
return result
|
|
|
|
def array_to_image(ar):
|
|
# Konvertiere das Array in ein NumPy-Array
|
|
np_array = np.array(ar)
|
|
# Erstelle ein leeres RGB-Bild
|
|
height, width = np_array.shape
|
|
image = Image.new('RGB', (width, height))
|
|
# Fülle das Bild mit Pixeln basierend auf den Array-Werten
|
|
for y in range(height):
|
|
for x in range(width):
|
|
if np_array[y, x] == "#":
|
|
image.putpixel((x, y), (0, 0, 0)) # Schwarz
|
|
else:
|
|
image.putpixel((x, y), (0, 255, 0)) # Grün
|
|
return image
|
|
|
|
if __name__ == "__main__":
|
|
field = create_field(int(f_columns), int(f_rows))
|
|
commands = read_file(file)
|
|
for command in commands:
|
|
field = do_command(command, field)
|
|
print(f"Solution Part1: {count_pixel(field)}")
|
|
|
|
print(f"Solution Part2:")
|
|
print_field(field)
|
|
img = array_to_image(field)
|
|
img.save("./solution-part2.png")
|
|
|
|
print(f'Runtime: {time()-start_time:.4f} s') |