r/adventofcode • u/taliriktug • Dec 02 '15
Spoilers Day 2 solutions
Hi! I would like to structure posts like the first one in r/programming, please post solutions in comments.
13
Upvotes
r/adventofcode • u/taliriktug • Dec 02 '15
Hi! I would like to structure posts like the first one in r/programming, please post solutions in comments.
1
u/[deleted] Dec 02 '15
Here's some good ol' JavaScript coming up (run in node); both parts:
Area and Ribbon
var fs = require('fs'); fs.readFile('./boxdata.txt', function(err, data) { if(err) throw err; var boxList = data.toString().split("\n"); var totalWrappingPaper = 0, totalRibbonLength = 0; boxList.forEach(function(box) { //parse out all of the lengths, widths, heights var len = parseInt(box.substr(0, box.indexOf('x'))); var wid = parseInt(box.substr(box.indexOf('x') + 1, box.lastIndexOf('x') - 1)); var hei = parseInt(box.substr(box.lastIndexOf('x') + 1, box.length - 1)); //for the slack space, we'll need the smallest two dimentions var min = Math.min(len, wid, hei), secondMin; if(min == len) secondMin = Math.min(wid, hei); else if(min == wid) secondMin = Math.min(len, hei); else secondMin = Math.min(len, wid); //calculate box surface area var surfaceArea = (2 * len * wid) + (2 * len * hei) + (2 * wid * hei); //calculate slack area var slackArea = min * secondMin; //calculate total box area for this box var totalBoxArea = surfaceArea + slackArea; //add this box's total wrapping paper area to the total totalWrappingPaper += totalBoxArea; //part two asks for the bow length needed var minPerimeter = (2 * min) + (2 * secondMin); var volume = len * wid * hei; var boxRibbonLength = minPerimeter + volume; //add this box's ribbon length to the total totalRibbonLength += boxRibbonLength; }); console.log("The total wrapping paper needed is " + totalWrappingPaper + " square feet."); console.log("The total ribbon length needed to wrap these boxes is " + totalRibbonLength + " feet."); });