Advent of Code 2022 - Day 6: Tuning Trouble Solution

Use a Set to check if all is different

Part 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")
2
3const readData = () => {
4 const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)
5
6 return data[0]
7}
8
9const main = () => {
10 const data = readData()
11 let res
12 const SIZE = 4
13
14 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 === SIZE
17
18 if (isAllDifferent) {
19 res = i + SIZE
20 break
21 }
22 }
23
24 console.log(res)
25}
26
27main()

Part 2

Like Part 1, just change the SIZE to 14

Implementation

1const fs = require("fs")
2
3const readData = () => {
4 const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)
5
6 return data[0]
7}
8
9const main = () => {
10 const data = readData()
11 let res
12 const SIZE = 14
13
14 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 === SIZE
17
18 if (isAllDifferent) {
19 res = i + SIZE
20 break
21 }
22 }
23
24 console.log(res)
25}
26
27main()

References

Original problem

Comments

Loading comments...

Tags

adventofcode

hash table

Next Post

Advent of Code 2022 - Day 7: No Space Left On Device

Recursive traversal

Previous Post

Advent of Code 2022 - Day 5: Supply Stacks

Transform (the hard part) and mutate

HoningJS

Search Posts