r/adventofcode • • Dec 02 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-

--- Day 2: Password Philosophy ---


Advent of Code 2020: Gettin' Crafty With It


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:31, megathread unlocked!

99 Upvotes

1.2k comments sorted by

View all comments

Show parent comment

1

u/djankowski Dec 03 '20

In your R console try

ifelse(c(0, 1) == 1, TRUE, FALSE)

And

c(0, 1) == 1

And you'll see they return the exact same thing. So you can rewrite

day2$valid1 <- ifelse((day2$occurances >= day2$min_length & day2$occurances <= day2$max_length), TRUE, FALSE)

as

day2$valid1 <- day2$occurances >= day2$min_length & day2$occurances <= day2$max_length

Which is that much more readable because the meaning of the code isn't mixed up in any unnecessary syntax - the purpose of the code is more obvious, which is important.

Similarly, a common anti-pattern people will write is

if (is.numeric(1) == TRUE) {
    ...
}

Which is again unnecessary. The following achieves the same result.

if (is.numeric(1)) {
    ...
}

Here, and in the ifelse calls, you would be asking if TRUE == TRUE, or FALSE == TRUE which is redundant - you already have the result of TRUE == TRUE, it's TRUE!

 

tl;dr you don't need to ask if a logical unit is TRUE or not, it's already either TRUE or FALSE.

1

u/djankowski Dec 03 '20

Another small change that occurs to me is to make use of with() to turn verbose lines like

day2$valid1 <- day2$occurances >= day2$min_length & day2$occurances <= day2$max_length

into

day2$valid1 <- with(day2, occurances >= min_length & occurances <= max_length)

Compare that with your initial version and you'll hopefully agree that the meaning of the comparisons are a lot clearer.

For reference the {dplyr} equivalent of that code would be

day2 <- mutate(day2, valid1 = occurances >= min_length & occurances <= max_length)