1 Commits

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

View File

@@ -1,17 +1,6 @@
# Advent of Code 2022 - assignment 1 # Advent of Code 2022 - Assignment7 javascript
This is the first assignment for Advent of Code 2022. The provided solution uses 3 variables: currentScore, highestCalorieScore, currentElf, highestElf. 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.
It is complexity O(n+m) since it loops through every line exactly once (n) and the iterates for recalculating highscore (m).
The GUI also provides a checkbox to toggle top3 or top1.
## Solution description ## References
Every iteration the score is added to the currentScore. If an empty line is detected we check if currentscore exceeds one of our highestCalorieScore, if yes we assign currentElf to highestElf. - 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
## references
- https://adventofcode.com/2022/day/1
- https://stackoverflow.com/questions/17595361/how-to-read-text-line-by-line-in-a-html-text-area
- https://bobbyhadz.com/blog/javascript-get-value-of-textarea
- https://stackoverflow.com/questions/154059/how-do-i-check-for-an-empty-undefined-null-string-in-javascript
- https://www.geeksforgeeks.org/convert-a-string-to-an-integer-in-javascript/#:~:text=In%20JavaScript%20parseInt()%20function,argument%20of%20parseInt()%20function.
- https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers
- https://www.w3schools.com/js/js_break.asp
- https://2ality.com/2018/12/creating-arrays.html

View File

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

147
script.js
View File

@@ -1,16 +1,85 @@
const ASSIGNMENT = 'assignment'; const ASSIGNMENT = 'assignment';
const ANSWER = 'answer'; const ANSWER = 'answer';
const ALGORITHM_CHECKBOX = 'algorithm';
const NEWLINE_CHARACTER = '\n'; const NEWLINE_CHARACTER = '\n';
const TOP_1 = 1; const MAX_SIZE = 100000;
const TOP_N = 3; const UPDATE_SIZE = 30000000;
const TOTAL_SPACE = 70000000;
/** /**
* Main function * Main function
*/ */
window.onload = function() { window.onload = function() {
document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer); document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer);
document.getElementById(ALGORITHM_CHECKBOX).addEventListener("click", 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;
}
} }
/** /**
@@ -19,52 +88,60 @@ window.onload = function() {
*/ */
function calculateAnswer(event) { function calculateAnswer(event) {
console.info("Calculating answer for input..."); console.info("Calculating answer for input...");
let assignment = document.getElementById(ASSIGNMENT).value; let answer = algorithm(event.target.value);
let top3 = document.getElementById(ALGORITHM_CHECKBOX).checked;
let answer = algorithm(assignment, (top3)? TOP_N: 1);
document.getElementById(ANSWER).innerText = answer; document.getElementById(ANSWER).innerText = answer;
} }
/** /**
* Calculate the answer to assignment1 with 2 variables, count and highest. * Calculate the answer to assignment.
* @param assignment the input from the assignment. * @param assignment the input from the assignment.
* @param topn the * @return string the answer
* @return string the elf with the highest calory count
*/ */
function algorithm(assignment, topn) { function algorithm(assignment) {
let currentCalorieScore = 0;
let highestCalorieScores = Array.from({length: topn}, () => (0));
let currentElf = 1;
let lines = assignment.trim().split(NEWLINE_CHARACTER); let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length); console.info("Linecount:" + lines.length);
for(var i = 0; i < lines.length; i++){ let root = new TreeNode('/');
let line = lines[i]; let currentdir = root;
if(!line && currentCalorieScore > 0) { // Check for empty line and skip subsequent emptylines for(let i=0; i<lines.length; i++) {
console.debug("Calculated score for elf " + currentElf + ": " + currentCalorieScore); let terminalLine = lines[i].trim();
for(let j=0; j < highestCalorieScores.length; j++) { if(terminalLine.substring(0, 4) == "$ cd") {
if(currentCalorieScore > highestCalorieScores[j]) { let changeDirectory = terminalLine.substring(5).trim();
console.debug("New highest #"+(j+1) + " elf found, with score:" + currentCalorieScore); if(changeDirectory == "..") {
let oldHighestCalorieScore = highestCalorieScores[j]; console.debug("One directory up from: " + currentdir.value);
highestCalorieScores[j] = currentCalorieScore; currentdir = currentdir.parent;
currentCalorieScore = oldHighestCalorieScore; console.debug("navigates to: " + currentdir.value);
}
}
// Reset values
currentCalorieScore = 0;
currentElf++;
continue; continue;
} }
let calorieScore = parseInt(line); if(changeDirectory == "/") {
currentCalorieScore += calorieScore; currentdir = root;
continue;
} }
console.debug(highestCalorieScores); if(!currentdir.contains(changeDirectory)) {
return "The highest of sum of calorie amount: " + highestCalorieScores.reduce(function(a, b) { return a + b; }, 0); currentdir.descendants.push(new TreeNode(changeDirectory, currentdir));
}
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);
}
}
let freeDiskSpace = TOTAL_SPACE - root.size;
console.debug("Free disk space: " + freeDiskSpace);
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);
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; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
} }
textarea {
display: block;
}
#answer { #answer {
color: purple color: purple
} }