View Single Post
Advent of Code dag 8, del 1 og 2. Fortsatt i sliten java..
SPOILER ALERT! Vis spoiler


Kode

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Day8 {
    private static char[][] grid = new char[50][6];

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                grid[i][j] = '░';
            }
        }

        for (String line : Files.readAllLines(Paths.get("C:/Users/xxx/IdeaProjects/AdventOfCode/src/A8"))) {
            if (line.startsWith("r_"))
                rect(line.substring(2));
            else if (line.startsWith("y_"))
                row(line.substring(2));
            else if (line.startsWith("x_"))
                column(line.substring(2));
        }

        printResult();
    }

    private static void column (String col) {
        int colNum = Integer.parseInt(col.split("_")[0]);
        int shifts = Integer.parseInt(col.split("_")[1]);
        String old = "", newResult;

        for (int i = 0; i < grid[colNum].length; i++) {
            old += String.valueOf(grid[colNum][i]);
        }
        int subStart = old.length()-shifts;
        newResult = old.substring(subStart) + old.substring(0, subStart);

        for (int i = 0; i < grid[colNum].length; i++) {
            grid[colNum][i] = newResult.charAt(i);
        }
    }

    private static void row (String row) {
        int rowNum = Integer.parseInt(row.split("_")[0]);
        int shifts = Integer.parseInt(row.split("_")[1]);
        String old = "", newResult;

        for (int i = 0; i < grid.length; i++) {
            old += String.valueOf(grid[i][rowNum]);
        }
        int subStart = old.length()-shifts;
        newResult = old.substring(subStart) + old.substring(0, subStart);

        for (int i = 0; i < grid.length; i++) {
            grid[i][rowNum] = newResult.charAt(i);
        }
    }

    private static void rect (String rect) {
        int xLen = Integer.parseInt(rect.split("x")[0]);
        int yLen = Integer.parseInt(rect.split("x")[1]);
        for (int i = 0; i < xLen; i++) {
            for (int j = 0; j < yLen; j++) {
                grid[i][j] = '▓';
            }
        }
    }

    private static void printResult () {
        int count = 0;
        for (int j = 0; j < grid[0].length; j++) {
            for (int i = 0; i < grid.length; i++) {
                if (grid[i][j] == '▓')
                    count++;
                System.out.print(grid[i][j]);
                if (i == grid.length - 1)
                    System.out.println();
            }
        }
        System.out.println(count + " pixels is lit.");
    }
}
Sist endret av Dyret; 9. desember 2016 kl. 03:08.