r/adventofcode • (AoC creator) • Dec 12 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 12 Solutions -๐ŸŽ„-

--- Day 12: Digital Plumber ---


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!

14 Upvotes

233 comments sorted by

View all comments

2

u/songkeys Dec 12 '17 edited Dec 12 '17

JavaScript (ES6) with HTML :)

<html>
<body>
	<textarea id="text"></textarea>
	<button onclick="part1()">Part 1</button>
	<button onclick="part2()">Part 2</button>

	<script type="text/javascript">
		let programIdArr

		const init = () => {
			programIdArr = []
			const lines = document.getElementById("text").value.split("\n")
			lines.forEach(line => {
				const programId = line.split(" <-> ")[0]
				const connectedId = line.split(" <-> ")[1].split(", ")
				const obj = {
					programId : programId,
					connectedId: connectedId,
					isConnected : false
				}

				programIdArr.push(obj)
			})
		}

		const connectGroup = groupId => {
			if (!programIdArr) { init() }

			programIdArr[0].isConnected = true

			let prev = 0, cur, counter
			while(prev != cur){
				programIdArr.forEach(obj => {
					if (obj.isConnected == true) {
						obj.connectedId.forEach(cid => {
							programIdArr.forEach(obj2 => {
								if (cid == obj2.programId) {
									obj2.isConnected = true
								}
							})
						})
					}
				})

				prev = counter
				counter = 0
				programIdArr.forEach(obj => {
					if (obj.isConnected == true) { counter++ }
				})
				cur = counter
			}

			console.log("Group " + groupId + " has " + cur + (cur == 1 ? " element." : " elements."))
		}

		const part1 = () => { connectGroup(1) }

		const part2 = () => {
			let group = 0
			if (!programIdArr) { init() }
			while(programIdArr.length != 0) {
				connectGroup(group + 1)
				let tempArr = []
				programIdArr.forEach(obj => {
					if (obj.isConnected != true) {
						tempArr.push(obj)
					}
				})
				programIdArr = tempArr
				group++
			}

			console.log("There are " + group + " groups in total.")
		}
	</script>
</body>
</html>