1 Commits

Author SHA1 Message Date
312a514472 Solution for part 1. 2022-12-22 23:07:39 +01:00
4 changed files with 157 additions and 112 deletions

View File

@@ -1,8 +1,14 @@
# Advent of Code 2022 - Assignment8 javascript
## Description
This problem is all about walking through a grid. In this solution, we look through an entire column and row until we find a node with height <= height.
# Advent of Code - assignment 9 javascript
This repository contains answers to the assignments of Advent of Coding 2022
## References
- https://www.w3schools.com/jsref/jsref_charat.asp
- https://stackabuse.com/javascript-check-if-variable-is-a-number/
- https://www.w3schools.com/jsref/jsref_abs.asp
- https://betterprogramming.pub/tuples-in-javascript-57ede9b1c9d2
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
- https://www.javascripttutorial.net/javascript-multidimensional-array/
- https://flaviocopes.com/how-to-replace-whitespace-javascript/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
- https://www.sohamkamani.com/javascript/enums/
- https://www.w3schools.com/js/js_switch.asp
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
- https://stackoverflow.com/questions/4564414/delete-first-character-of-string-if-it-is-0
- https://stackoverflow.com/questions/1959040/is-it-possible-to-send-a-variable-number-of-arguments-to-a-javascript-function

View File

@@ -8,8 +8,6 @@
<body>
<p>Assignment:</p>
<textarea rows="15" cols="50" id="assignment"></textarea>
<input type="checkbox" id="algorithm" />
<label for="algorithm">Highest scenic score?</label>
<p>Answer:</p>
<div id="answer">Provide input first</div>

245
script.js
View File

@@ -1,25 +1,142 @@
const ASSIGNMENT = 'assignment';
const ANSWER = 'answer';
const ALGORITHM_CHECKBOX = 'algorithm';
const NEWLINE_CHARACTER = '\n';
/**
* Main function
*/
window.onload = function () {
document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer);
document.getElementById(ALGORITHM_CHECKBOX).addEventListener("click", calculateAnswer);
window.onload = function() {
document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer);
}
const DIRECTIONS = {
UP: 'U',
DOWN: 'D',
LEFT: 'L',
RIGHT: 'R'
};
class Knot {
constructor(x, y) {
this.x=x;
this.y=y;
}
}
/*class Rope {
constructor(headX, headY, tailX, tailY) {
this.headX = headX;
this.headY = headY;
this.tailX = tailX;
this.tailY = tailY;
console.info("Created Rope with head:" + headX + "," + headY + " and tail: " + tailX + "," + tailY);
}
step = function (direction) {
let oldHeadX = this.headX;
let oldHeadY = this.headY;
switch (direction) {
case DIRECTIONS.UP:
this.headY++;
break;
case DIRECTIONS.DOWN:
this.headY--;
break;
case DIRECTIONS.LEFT:
this.headX--;
break;
case DIRECTIONS.RIGHT:
this.headX++;
break;
default:
console.error("Invalid direction given: " + direction);
}
this.__correctTail(oldHeadX, oldHeadY);
}
getTailPosition = function () {
return "" + this.tailX + "," + this.tailY;
}
__correctTail = function (oldHeadX, oldHeadY) {
let absoluteDifferenceX = Math.abs(this.headX - this.tailX);
let absoluteDifferenceY = Math.abs(this.headY - this.tailY);
if (absoluteDifferenceX > 1 || absoluteDifferenceY > 1) {
this.tailX = oldHeadX;
this.tailY = oldHeadY;
console.debug("Corrected tail Position: (" + this.tailX + ", " + this.tailY + "), head position: (" + this.headX + ", " + this.headY + ")");
}
}
};*/
class Rope {
constructor(count) {
if(count < 2) {
console.error("Rope needs at least 2 knots.");
return;
}
let knots = [];
while(count > 0) {
knots.push(new Knot(0,0));
count--;
}
this.head = knots[0];
this.knots = Array.from(knots).slice(1);
this.tail = this.knots[this.knots.length-1];
console.info("Created Rope with " + knots.length + " knots.");
}
step = function(direction) {
let oldHeadX = this.head.x;
let oldHeadY = this.head.y;
switch(direction) {
case DIRECTIONS.UP:
this.head.y++;
break;
case DIRECTIONS.DOWN:
this.head.y--;
break;
case DIRECTIONS.LEFT:
this.head.x--;
break;
case DIRECTIONS.RIGHT:
this.head.x++;
break;
default:
console.error("Invalid direction given: " + direction);
}
this.__correctTails(oldHeadX, oldHeadY, this.head, this.knots[0], this.knots.slice(1));
}
getTailPosition = function() {
return "" + this.tail.x + "," + this.tail.y;
}
__correctTails = function(oldHeadX, oldHeadY, head, tail, tails) {
let absoluteDifferenceX = Math.abs(head.x - tail.x);
let absoluteDifferenceY = Math.abs(head.y - tail.y);
let oldTailX = tail.x;
let oldTailY = tail.y;
if(absoluteDifferenceX > 1 || absoluteDifferenceY > 1) {
tail.x = oldHeadX;
tail.y = oldHeadY;
console.debug("Corrected tail Position: (" + this.tail.x + ", " + this.tail.y + "), head position: (" + this.head.x + ", " + this.head.y + ")");
}
if(tails.length > 0)
this.__correctTails(oldTailX, oldTailY, tail, tails[0], tails.slice(1));
}
};
/**
* Listener function for input in assignment field.
* @param event the onInput event
*/
function calculateAnswer(event) {
console.info("Calculating answer for input...");
let assignment = document.getElementById(ASSIGNMENT).value;
let getHighestScenicScore = document.getElementById(ALGORITHM_CHECKBOX).checked;
let answer = algorithm(assignment, getHighestScenicScore);
let answer = algorithm(event.target.value);
document.getElementById(ANSWER).innerText = answer;
}
@@ -29,106 +146,34 @@ function calculateAnswer(event) {
* @param assignment the input from the assignment.
* @return string the answer
*/
function algorithm(assignment, getHighestScenicScore) {
let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length);
function algorithm(assignment) {
let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length);
let visibleTreeCount = 0;
let highestScenicScore = 0;
let rope = new Rope(10);
let visitedPositions = [rope.getTailPosition()];
for (let i = 0; i < lines.length; i++) {
let row = lines[i].trim();
for (let j = 0; j < row.length; j++) {
if (i <= 0 || i >= lines.length - 1 || j <= 0 || j >= row.length - 1) { // Edge node
//console.debug("Edge node found.");
visibleTreeCount++;
continue;
for(let i=0; i<lines.length; i++) {
let line = lines[i].replace(/\s/g, ''); // Remove all whitespace
let direction = line[0];
let count = parseInt(line.substring(1));
if(isNaN(count)) { // Validate count
console.error("Invalid number in line: " + lines[i]);
}
let height = parseInt(lines[i].charAt(j));
if (!walkRowVisible(height, j, row) && !walkColumnVisible(height, i, j, lines)) {
console.log("Found invisible tree, height:" + height + ", i:" + i + ", j:" + j);
visibleTreeCount--;
}
while(count > 0) {
rope.step(direction);
let tailPosition = rope.getTailPosition();
if (getHighestScenicScore) {
let scenicScore = walkRowCount(height, j, row) * walkColumnCount(height, i, j, lines);
if (scenicScore > highestScenicScore) {
console.debug("Found new highest scenic score: " + scenicScore);
highestScenicScore = scenicScore;
if(!visitedPositions.includes(tailPosition) ) { // Add only unique tailpositions
visitedPositions.push(tailPosition);
}
count--;
}
// Tree is on edge.
visibleTreeCount++;
}
}
if (getHighestScenicScore) {
return "Highest scenic score: " + highestScenicScore;
}
return "Amount of visible trees in the grid: " + visibleTreeCount;
}
function walkColumnCount(height, index, rowIndex, column) {
return walkCount(height, index, column, false, rowIndex);
}
function walkRowCount(height, index, row) {
return walkCount(height, index, row, true, -1);
}
function walkColumnVisible(height, index, rowIndex, column) {
return walkVisible(height, index, column, false, rowIndex);
}
function walkRowVisible(height, index, row) {
return walkVisible(height, index, row, true, -1);
}
function walkCount(height, index, line, isRow, rowIndex) {
let visibleLeftCount = __walkHelper(height, index, line, isRow, -1, rowIndex, 0);
let visibleRightCount = __walkHelper(height, index, line, isRow, 1, rowIndex, 0);
return visibleLeftCount * visibleRightCount;
}
function walkVisible(height, index, line, isRow, rowIndex) {
let visibleLeft = __walkHelper(height, index, line, isRow, -1, rowIndex);
let visibleRight = __walkHelper(height, index, line, isRow, 1, rowIndex);
return visibleLeft || visibleRight;
}
function __walkHelper(height, index, line, isRow, direction, rowIndex, count) {
if (direction == 0) {
console.error("Invalid direction 0 in __walkhelper");
return -1;
}
direction = direction / Math.abs(direction);
// Edge reached
if ((direction < 0 && index <= 0) || (direction > 0 && index >= line.length - 1)) {
return (count == undefined) ? true : count;
}
let nextIndex = index + direction;
let nextHeightCharacter = (isRow) ? line.charAt(nextIndex) : line[nextIndex].trim().charAt(rowIndex);
let nextHeight = parseInt(nextHeightCharacter);
if (isNaN(height) || isNaN(nextHeightCharacter)) {
console.error("Invalid height found, height:" + height + ", nextHeight: " + nextHeightCharacter);
return -1;
}
if (height <= nextHeight) {
if (count == undefined)
return false;
return count + 1;
}
return __walkHelper(height, nextIndex, line, isRow, direction, rowIndex, (count !=undefined)? count + 1 : undefined);
console.log(visitedPositions);
return "Amount of positions for tail: " + visitedPositions.length;
}

View File

@@ -6,10 +6,6 @@ body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
textarea {
display: block;
}
#answer {
color: purple
}