1 Commits

Author SHA1 Message Date
0af89a72ba Messy solution. 2022-12-08 01:31:18 +01:00
4 changed files with 110 additions and 105 deletions

View File

@@ -1,8 +1,6 @@
# 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 2022 - Assignment7 javascript
Assignment 7 involves parsing linux directory commands/results into a tree. The solution defines a root TreeNode first and sets it as currentdirectory. Whenever a cd command is found a new node is created if it does not exist and set to currentdir. Whenever a cd .. is found currentdirectory is set to parent. Whenever a file is found size is recursively increased for current node and parent nodes.
## 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://adrianmejia.com/data-structures-for-beginners-trees-binary-search-tree-tutorial/
- https://stackoverflow.com/questions/8376525/get-value-of-a-string-after-last-slash-in-javascript

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>

199
script.js
View File

@@ -1,14 +1,85 @@
const ASSIGNMENT = 'assignment';
const ANSWER = 'answer';
const ALGORITHM_CHECKBOX = 'algorithm';
const NEWLINE_CHARACTER = '\n';
const MAX_SIZE = 100000;
const UPDATE_SIZE = 30000000;
const TOTAL_SPACE = 70000000;
/**
* 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);
}
class TreeNode {
constructor(value, parent) {
console.debug(((!parent)?"Root ":"") + "node created: " + value);
this.parent = parent;
this.value = value;
this.size = 0;
this.descendants = [];
}
getDir = function(path) {
for(let descendant of this.descendants) {
if(descendant.value == path) {
return descendant;
}
}
}
contains = function(path) {
// Recursive case
let subPathIndex = path.indexOf('/');
let subPath = path.substring(0, subPathIndex-1);
let leftOverPath = path.substring(subPathIndex);
// Base case
if(subPath == '') {
return false;
}
for(let descendant of this.descendants) {
if(descendant.value == subPath) {
return descendant.contains(subPath);
}
}
}
findClosestNodeToSize = function(minSize) {
let closest = this;
for(let descendant of this.descendants) {
let closestDescendant = descendant.findClosestNodeToSize(minSize);
if (closestDescendant.size > minSize && closestDescendant.size < closest.size) {
console.debug("New closest:" + closestDescendant.size);
closest = closestDescendant;
}
}
return closest;
}
increaseSize = function(size) {
// TODO: Wat doen we met duplicate files?
this.size += size;
if(this.parent) {
this.parent.increaseSize(size);
}
}
getSum = function(maxSize) {
let result = (this.size < maxSize) ? this.size: 0;
for(let descendant of this.descendants) {
result += descendant.getSum(maxSize);
}
return result;
}
}
/**
@@ -17,9 +88,7 @@ window.onload = function () {
*/
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 +98,50 @@ function calculateAnswer(event) {
* @param assignment the input from the assignment.
* @return string the answer
*/
function algorithm(assignment, getHighestScenicScore) {
function algorithm(assignment) {
let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length);
let visibleTreeCount = 0;
let highestScenicScore = 0;
let root = new TreeNode('/');
let currentdir = root;
for (let i = 0; i < lines.length; i++) {
let row = lines[i].trim();
for(let i=0; i<lines.length; i++) {
let terminalLine = 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++;
if(terminalLine.substring(0, 4) == "$ cd") {
let changeDirectory = terminalLine.substring(5).trim();
if(changeDirectory == "..") {
console.debug("One directory up from: " + currentdir.value);
currentdir = currentdir.parent;
console.debug("navigates to: " + currentdir.value);
continue;
}
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(changeDirectory == "/") {
currentdir = root;
continue;
}
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(!currentdir.contains(changeDirectory)) {
currentdir.descendants.push(new TreeNode(changeDirectory, currentdir));
}
// Tree is on edge.
visibleTreeCount++;
currentdir = currentdir.getDir(changeDirectory);
} else if(terminalLine.substring(0, 3) != 'dir' && !terminalLine.includes('$')) {
console.debug(terminalLine);
spaceIndex = terminalLine.indexOf(' ');
size = parseInt(terminalLine.substring(0, spaceIndex));
currentdir.increaseSize(size);
}
}
if (getHighestScenicScore) {
return "Highest scenic score: " + highestScenicScore;
}
let freeDiskSpace = TOTAL_SPACE - root.size;
console.debug("Free disk space: " + freeDiskSpace);
return "Amount of visible trees in the grid: " + visibleTreeCount;
}
console.debug("Root size:" + root.size);
console.debug("Value to find: " + (UPDATE_SIZE - freeDiskSpace));
let closestNode = root.findClosestNodeToSize(UPDATE_SIZE - freeDiskSpace);
console.debug("Closest value: " + closestNode.size);
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);
return "Sum below maxSize " + MAX_SIZE + ": " + root.getSum(MAX_SIZE);
}

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
}