Advent of Code 2022 - Day 6: Tuning Trouble Solution
Use a Set to check if all is differentPart 1
To check a substring has all different characters:
- put all characters to a set
- if the size of the set is the same as the length of the substring, then no duplication characters are existed
Implementation
1const fs = require("fs")23const readData = () => {4 const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)56 return data[0]7}89const main = () => {10 const data = readData()11 let res12 const SIZE = 41314 for (let i = 0; i < data.length - SIZE + 1; i++) {15 const marker = data.substring(i, i + SIZE)16 const isAllDifferent = new Set(marker.split("")).size === SIZE1718 if (isAllDifferent) {19 res = i + SIZE20 break21 }22 }2324 console.log(res)25}2627main()
Part 2
Like Part 1, just change the
SIZE
to 14
Implementation
1const fs = require("fs")23const readData = () => {4 const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)56 return data[0]7}89const main = () => {10 const data = readData()11 let res12 const SIZE = 141314 for (let i = 0; i < data.length - SIZE + 1; i++) {15 const marker = data.substring(i, i + SIZE)16 const isAllDifferent = new Set(marker.split("")).size === SIZE1718 if (isAllDifferent) {19 res = i + SIZE20 break21 }22 }2324 console.log(res)25}2627main()
References
Comments
Loading comments...
Tags
adventofcode
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.