1 Commits

Author SHA1 Message Date
28597a3f26 Initial working commit 2022-12-11 12:44:35 +01:00
3 changed files with 101 additions and 70 deletions

View File

@@ -1,9 +1,8 @@
# Advent of Code 2022 - Assignment 4 - javascript
# Advent of Code 2022 - Assignment8 javascript
## Description
The problem for assignment4 deals with overlaps and string parsing. The provided solution for this argument uses substring to parse ranges from file. Furthermore it has a checkbox to trigger whether ranges should fully overlap.
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.
## References
- https://www.w3schools.com/jsref/jsref_indexof.asp
- https://www.geeksforgeeks.org/convert-a-string-to-an-integer-in-javascript/#:~:text=In%20JavaScript%20parseInt()%20function,argument%20of%20parseInt()%20function.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
- https://medium.com/@raihan_tazdid/overlapping-numbers-in-ranges-5d0f2efc294e
- 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

View File

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

156
script.js
View File

@@ -1,17 +1,14 @@
const ASSIGNMENT = 'assignment';
const ANSWER = 'answer';
const ALGORITHM_CHECKBOX = 'algorithm';
const ERROR_MESSAGE_INVALID_RANGE = "Invalid range, ";
const COMMA_CHARACTER = ',';
const NEWLINE_CHARACTER = '\n';
const RANGE_CHARACTER = '-';
/**
* 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);
document.getElementById(ALGORITHM_CHECKBOX).addEventListener("click", calculateAnswer);
}
/**
@@ -21,8 +18,8 @@ window.onload = function() {
function calculateAnswer(event) {
console.info("Calculating answer for input...");
let assignment = document.getElementById(ASSIGNMENT).value;
let fullOverlap = document.getElementById(ALGORITHM_CHECKBOX).checked;
let answer = algorithm(assignment, fullOverlap);
let getHighestScenicScore = document.getElementById(ALGORITHM_CHECKBOX).checked;
let answer = algorithm(assignment, getHighestScenicScore);
document.getElementById(ANSWER).innerText = answer;
}
@@ -30,73 +27,108 @@ function calculateAnswer(event) {
/**
* Calculate the answer to assignment.
* @param assignment the input from the assignment.
* @param fullOverlap if input needs to fully overlap.
* @return string the answer
*/
function algorithm(assignment, fullOverlap) {
let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length);
function algorithm(assignment, getHighestScenicScore) {
let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length);
let containedPairs = 0;
for(let i=0; i<lines.length; i++) {
let error = false;
let ranges = lines[i].trim();
// Search for separation charactes -,-
let range1CharacterIndex = ranges.indexOf(RANGE_CHARACTER);
let range1EndCharacterIndex = ranges.indexOf(COMMA_CHARACTER);
let range2CharacterIndex = ranges.indexOf(RANGE_CHARACTER, range1CharacterIndex+1);
let visibleTreeCount = 0;
let highestScenicScore = 0;
// Get range substrings
let range1LowerString = ranges.substring(0,range1CharacterIndex);
let range1HigherString = ranges.substring(range1CharacterIndex+1, range1EndCharacterIndex);
let range2LowerString = ranges.substring(range1EndCharacterIndex+1, range2CharacterIndex);
let range2HigherString = ranges.substring(range2CharacterIndex+1);
console.debug("Parsed values: " + range1LowerString + "-" + range1HigherString + "," + range2LowerString + "-" + range2HigherString);
for (let i = 0; i < lines.length; i++) {
let row = lines[i].trim();
// Parse to int
let range1Lower = parseInt(range1LowerString);
let range1Higher = parseInt(range1HigherString);
let range2Lower = parseInt(range2LowerString);
let range2Higher = parseInt(range2HigherString);
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;
}
// Validation
if(range1Lower > range1Higher) {
console.error(ERROR_MESSAGE_INVALID_RANGE + range1Lower + "-" + range1Higher + " on line:" + i + " for range1");
error = true;
}
if(range2Lower > range2Higher) {
console.error(ERROR_MESSAGE_INVALID_RANGE + range2Lower + "-" + range2Higher + " on line:" + i + " for range2");
error = true;
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--;
}
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(error) {
continue;
}
// Check for overlap
if(fullOverlap && doesRangeFullyOverlap(range1Lower, range1Higher, range2Lower, range2Higher)
|| !fullOverlap && doesRangeOverlap(range1Lower, range1Higher, range2Lower, range2Higher)) {
console.debug("Found overlapping range:" + range1Lower + "-" + range1Higher + "," + range2Lower + "-" + range2Higher);
containedPairs++;
}
// Tree is on edge.
visibleTreeCount++;
}
}
return "Fully overlapping timeslot counts: " + containedPairs;
if (getHighestScenicScore) {
return "Highest scenic score: " + highestScenicScore;
}
return "Amount of visible trees in the grid: " + visibleTreeCount;
}
function doesRangeFullyOverlap(lower, higher, lower2, higher2) {
console.debug("Compare range: " + lower + "-" + higher + " with " + lower2 + "-" + higher2);
if(lower > higher || lower2 > higher2) {
return false;
}
return ((lower <= lower2 && higher >= higher2) || (lower2 <= lower && higher2 >= higher));
function walkColumnCount(height, index, rowIndex, column) {
return walkCount(height, index, column, false, rowIndex);
}
function doesRangeOverlap(lower, higher, lower2, higher2) {
console.debug("Compare range: " + lower + "-" + higher + " with " + lower2 + "-" + higher2);
if(lower > higher || lower2 > higher2) {
return false;
}
function walkRowCount(height, index, row) {
return walkCount(height, index, row, true, -1);
}
return higher2 >= lower && lower2 <= higher;
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);
}