2020 Advent of Code–Day 2

This series looks at the Advent of Code challenges.

As one of my goals, I’m working through challenges. This post looks at day 2.

Part 1

This problem is really a string processing issue. We get a long string that needs splitting into different parts. We have two numbers, a digit to check, and a password. In this part, we are looking to see if our check digit appears x number of times.

For T-SQL, we can use Substring and charindex to split things. I had code like this:

SELECT
             SUBSTRING(datavalue, 1, CHARINDEX('-', datavalue) - 1) AS lowerbound
           , SUBSTRING(datavalue, CHARINDEX('-', datavalue) + 1, CHARINDEX(' ', datavalue) - CHARINDEX('-', datavalue) - 1) AS upperbound
           , SUBSTRING(datavalue, CHARINDEX(' ', datavalue) + 1, 1)
           , SUBSTRING(datavalue, CHARINDEX(':', datavalue) + 2, 50)
        FROM dbo.Day2 AS d

From here, I can do some counting to determine if we have the correct number of check digits.

For Python and PowerShell, I used split functions. The PowerShell one I did in two routines, one to break the numbers off into $counters, after everything is split.

$values = $line.Split(' ')
$counters = $values.split('-')

From here, I could then break everything up into the 4 parts.

$min = $counters[0]
$max = $counters[1]
$checkvalue = $values[1].Substring(0, $values[1].Length - 1)
$pwd = $values[2]

Now I get a count, and then an IF statement that can clean this up.

if (($count -ge $min) -and ($count -le $max)) { $part1 += 1}
if (($checkvalue -eq $pwd[$min-1]) -ne ($checkvalue -eq $pwd[$max-1])) { $part2 += 1}

This worked right away.

Part 2

In Part 2, rather than counting, we are deciding if the check digit is in the positions specified by the numbers.  The trick here is to check if that substring is equal to the digit. Again, in PoSh, the trick is to see if we have one or the other, which is the requirement.

if (($checkvalue -eq $pwd[$min-1]) -ne ($checkvalue -eq $pwd[$max-1])) { $part2 += 1}

This code looks if the digit matches first, then the second digit matches, and if these are both a 0 or 1, it’s not valid. If only one is valid, we increment the counter.

The python code is very similar.

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.