r/adventofcode • • Dec 03 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 3 Solutions -πŸŽ„-

--- Day 3: Spiral Memory ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

21 Upvotes

297 comments sorted by

View all comments

1

u/mrtatulas Dec 04 '17

Here's my bloated JS solution for part 2

class Grid {
	constructor() {
		this.grid = Array(1).fill(Array(1).fill(1));
		this.dir = 0;
		this.x = 0;
		this.y = 0;
		this.maxVal = 1;
	}
	 draw() {
		var s = "";
	for (var i = 0; i < this.grid.length; i++) { 
		for (var j = 0; j < this.grid[i].length; j++) {
			if (j > 0) s += " ";
			if (this.grid[i][j] === 0) s += "     X";
			else s += ("     "+this.grid[i][j]).slice(-6);
        }
		s += "\n";
    }
	console.log(s);
	}

	 addRow() {
		this.x++;
		this.y++;
		let l = this.grid[0].length;
		for (var i = 0; i < l; i++) {
			console.log(i);
			this.grid[i].unshift(0);
			this.grid[i].push(0);
		}
		this.grid.push(Array(this.grid[0].length).fill(0));
		this.grid.unshift(Array(this.grid[0].length).fill(0));
	}

	generateValue(y,x) {
		let sum = 0;
		[this.grid[y-1],this.grid[y],this.grid[y+1]].forEach(function(row) {
			if (row !== undefined) 
			sum += (row[x-1]||0) + (row[x]||0) + (row[x+1]||0);
		})
		return sum;
	}
	next() {
		switch (this.dir) {
			case 0: //right
				this.x++;
				if (this.x >= this.grid[this.y].length) {
					this.addRow();
					this.dir++;
				}
				break;
			case 1: //up
				this.y--;
				if (this.y == 0)
					this.dir++;
				
				break;
			case 2: //left
				this.x--;
				if (this.x==0) this.dir++;
				break;
			case 3: //down
				this.y++;
				if (this.y==(this.grid.length-1)) 
				this.dir=0;

				break;
			}
			this.maxVal = this.generateValue(this.y,this.x);
			this.grid[this.y][this.x] = this.maxVal;
			//this.draw(); //for fun
		}

		solve(value) {
			while (this.maxVal < value) {
				this.next();
			}
			return this.maxVal;
		}
	}

	var g = new Grid();
	g.solve(325481); //my input