Advent of Code — Day 6 — Javascript

Vincent Yang
3 min readJan 25, 2021

For Day 6, you are given a string of characters that represent the answer “Yes” to a question labeled with a single character. There are 26 possible possible questions as there are the same number of letters in the alphabet.

In the input data, each person is represented on a new line and each group is represented with an extra space in between the input data. For example, if we were to look at the sample data:

abc

a
b
c

ab
ac

a
a
a
a

b

As there are letters on eleven lines, there are eleven people split within five different groups. The goal is to find the total number of “Yes”s for each group without counting duplicate “Yes”s. If that sounds confusing, I apologize and I’ll explain below.

abc
Group 1 has 1 person saying yes to 3 unique questions
Total = 3
a
b
c
Group 2 has 3 people saying to yes 3 unique questions
Total = 3
ab
ac
Group 3 has 2 people saying yes to 3 unique questions
Total = 3
a
a
a
a
Group 4 has 4 people saying yes to 1 unique question
Total = 1
b
Group 5 has 1 person saying yes to 1 unique question
Total = 1

After getting the total for each group, return the sum of all of the totals within the input data. Given the sample data, the number that I am looking for is 3+3+3+1+1=11.

The first thing we want to do is parse the data and separate it into groups.

function day6(input){
let groups = input.split('\n\n')
}
//groups[0] = "abc"
//groups[1] = "a,
b,
c"
//...

If we look at the sample data, you can see that the question is asking for the uniqueness count on a group’s letters.

Group 1:
abc
"abc" => Check if each character is unique and then return the length
Group 2:
a
b
c
"abc" => Check if each character is unique and then return the length
Group 3:
ab
ac
"abac" => "abc" => 3
Group 4:
a
a
a
a
"aaaa" => "a" => 1
Group 5:
b
"b" => 1

What we can use here is a Set as adding duplicate letters will not work as it already checks for uniqueness.

function day6(input){
let groups = input.split('\n\n')
let set = new Set()
for(let group of groups){
for(let i = 0; i < group.length; i++){
set.add(group[i])
}
}
}

Going through this line by line, for each individual group, we are parsing through each letter and adding it to the set that we created. For example, if we were to add a wall of letters, the longest the set would be is a length of 26 characters.

Now that we have uniqueness, we need a variable to contain all of the totals for each group. After parsing through each group and adding to the set, we can get the size of the set and add that number to the total.

function day6(input){
let groups = input.split('\n\n')
let set = new Set()
let total = 0
for(let group of groups){
for(let i = 0; i < group.length; i++){
set.add(group[i])
}
total += set.size
}
return total
}

--

--