Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Advent2018;
- import util.AdventOfCode;
- import util.Direction;
- import util.Node;
- import java.util.*;
- public class Day13 extends AdventOfCode {
- static final int GRID_SIZE = 150;
- static final String CART_DIR = "^>v<";
- String[][] grid;
- List<Cart> carts;
- String first = "";
- String lastCart = "";
- enum Turn {
- LEFT, STRAIGHT, RIGHT
- }
- class Cart {
- int num;
- Node position;
- Direction dir;
- Turn last = Turn.RIGHT;
- boolean collided;
- int getY() { return position.getY(); }
- int getX() { return position.getX(); }
- void move() {
- position = dir.move(position);
- for (Cart each :carts) {
- if (!each.equals(this)) {
- if (!each.collided) {
- if (each.position.equals(this.position)) {
- if (first.length() == 0) first = getX() + "," + getY();
- System.out.println("Collision at " + getX() + "," + getY());
- System.out.println("Between " + this.num + " and " + each.num);
- this.collided = true;
- each.collided = true;
- return;
- }
- }
- }
- }
- String next = grid[position.getY()][position.getX()];
- switch (next) {
- case "/":
- switch (dir) {
- case NORTH:
- case SOUTH:
- dir = dir.getRight();
- break;
- case EAST:
- case WEST:
- dir = dir.getLeft();
- break;
- }
- break;
- case "\\":
- switch (dir) {
- case NORTH:
- case SOUTH:
- dir = dir.getLeft();
- break;
- case EAST:
- case WEST:
- dir = dir.getRight();
- break;
- }
- break;
- case "+":
- switch (last) {
- case RIGHT:
- last = Turn.LEFT;
- dir = dir.getLeft();
- break;
- case STRAIGHT:
- last = Turn.RIGHT;
- dir = dir.getRight();
- break;
- case LEFT:
- last = Turn.STRAIGHT;
- break;
- }
- }
- }
- }
- public Day13(List<String> input) {
- super(input);
- }
- @Override
- public Object part1() {
- int count = carts.size();
- while (count > 1) {
- carts.sort(Comparator.comparing(Cart::getY).thenComparing(Cart::getX));
- count = (int) carts.stream().filter(x -> !x.collided).count();
- for (Cart each : carts) {
- if (!each.collided) each.move();
- }
- }
- Cart last = carts.stream().filter(x -> !x.collided).findFirst().get();
- lastCart = last.position.getX() + "," + last.position.getY();
- return first;
- }
- @Override
- public Object part2() {
- return lastCart;
- }
- @Override
- public void parse() {
- carts = new ArrayList<>();
- grid = new String[GRID_SIZE][GRID_SIZE];
- int count = 0;
- for (int i = 0; i < input.size(); i++) {
- String line = input.get(i);
- for (int j = 0; j < line.length(); j++) {
- String cell = Character.toString(line.charAt(j));
- grid [i][j] = cell;
- if (CART_DIR.contains(cell)) {
- Cart c = new Cart();
- c.num = count++;
- c.position = new Node(j, i);
- c.dir = Direction.getByNum(CART_DIR.indexOf(cell));
- carts.add(c);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement