DEV Community

Cover image for How About a Nice Game of Chess?
Robert Mion
Robert Mion

Posted on

How About a Nice Game of Chess?

Advent of Code 2016 Day 5

Part 1

  1. Going backwards helped
  2. Playing the waiting game...again

Going backwards helped

I'm quite familiar with MD5 hashing by now:

Playing the waiting game...again

  • Generate a hash
  • Check for a match of 00000 as the first five characters in the hash
  • Repeat until eight matches are found

My algorithm in JavaScript:

let index = 0, password = "", doorID = 'abc'
while (password.length < 8) {
  let hash = MD5(doorID + index).toString()
  if (hash.slice(0,5) == '00000') {
    password += hash[5]
  }
  index++
}
return password
Enter fullscreen mode Exit fullscreen mode

This may take a while...especially since the match is five 0s in a row!

...

It didn't take as long as Day 14 - where I had to generate 2017 hashes each iteration!

But it still took several minutes to run.

Thankfully, it generated the correct answer for my door ID!

Part 2

A cool twist and a longer waiting game

  • I updated my algorithm to account for an array, a position and a value

But I initially neglected to account for this portion of the instructions:

Use only the first result for each position

  • I wasn't quite sure what that meant
  • Until I ran my algorithm on the example input
  • And I generated an answer different from the expected one
  • Because I had modified some of the values already set

After updating my code to account for this:

password[hash[5]] = password[hash[5]] || hash[6]
Enter fullscreen mode Exit fullscreen mode

My algorithm generated the correct answer for the example door ID and my door ID!

My updated algorithm in JavaScript:

let index = 0, doorID = 'abc'
let password = new Array(8).fill(null)
while (password.includes(null)) {
  let hash = MD5(doorID + index).toString()
  if (hash.slice(0,5) == '00000' && hash[5] < 8) {
    password[hash[5]] = password[hash[5]] || hash[6]
  }
  index++
}
return password.join('')
Enter fullscreen mode Exit fullscreen mode

I did it!!

  • I solved both parts!
  • After a short time writing and a lot of time waiting!
  • And accommodating one important use case in my algorithm!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay