xxxxxxxxxx
121
let inputData;
let DataGrid1 = [];
let DataGrid2 = [];
function preload() {
inputData = loadStrings("input.txt");
}
function setup() {
createCanvas(1000, 1000);
inputData = parseData(inputData);
for (let x = 0; x < width; x++) {
DataGrid1[x] = [];
DataGrid2[x] = [];
for (let y = 0; y < height; y++) {
let numLines1 = 0;
let numLines2 = 0;
for (let ln of inputData) {
if (ln.contains(x, y, false)) numLines1++;
if (ln.contains(x, y, true)) numLines2++;
}
DataGrid1[x][y] = numLines1;
DataGrid2[x][y] = numLines2;
}
}
let puzzle1 = 0;
let puzzle2 = 0;
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
if (DataGrid1[x][y] >= 2) puzzle1++;
if (DataGrid2[x][y] >= 2) puzzle2++;
}
}
console.log("Puzzle 1: ", puzzle1);
console.log("Puzzle 2: ", puzzle2);
}
function draw() {
background(255);
for (const entry of inputData) {
entry.draw();
}
// for (let x = 0; x < width; x++) {
// for (let y = 0; y < height; y++) {
// if (DataGrid[x][y]) point(x, y);
// }
// }
noLoop();
}
class StraightLine {
constructor(from, to) {
this.from = from;
this.to = to;
if (this.from.x === this.to.x || this.from.y === this.to.y) {
this.diagonal = false;
} else {
this.diagonal = true;
}
}
static parse(str) {
const [from, to] = str
.split(" -> ")
.map((vec) => createVector(vec.split(",").map((x) => +x)));
return new StraightLine(from, to);
}
contains(x, y, checkDiagonals = false) {
const x1 = this.from.x;
const y1 = this.from.y;
const x2 = this.to.x;
const y2 = this.to.y;
if (x1 === x2) {
// vertical line
if (x === x1 && inBetween(y1, y2, y)) {
return true;
}
} else if (y1 === y2) {
// horizontal line
if (y === y1 && inBetween(x1, x2, x)) {
return true;
}
} else {
// diagonal line
if (checkDiagonals) {
if ((y - y1) * (x2 - x1) === (y2 - y1) * (x - x1)) {
if ((y - y1) * (y2 - y) >= 0) return true;
}
}
}
return false;
}
draw() {
line(this.from.x, this.from.y, this.to.x, this.to.y);
}
toString() {
const x1 = this.from.x;
const y1 = this.from.y;
const x2 = this.to.x;
const y2 = this.to.y;
return `${x1},${y1} -> ${x2},${y2}`;
}
}
function inBetween(a, b, num) {
if (a > b) [b, a] = [a, b];
return a <= num && num <= b;
}
function parseData(data) {
return data.map((row) => StraightLine.parse(row));
}