Advent of code 2017 - Day 1

今天阅读RSS订阅的时候,注意到有一篇文章,里面有一个有趣的网址。
Advent of code 2017
网站是英文的,网站的大概意思是:
圣诞老人小精灵找到你,说圣诞老人的打印机坏啦,离午夜还有15millisecond了。让你帮忙修好,说完你就变小了,进入到了计算机的世界。
网站提供了15天的题目,每天的题目都分为两部分,解出来一部分以后可以拿到一颗🌟,第一天的题目是:

The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.

大概意思就是,有一串连续的数字,然后让我们找出和后面一个数字相同的的数字的和。串是环形的,所以最后一个数字的后一个数字是数字串的第一个数字。
题目很简单啊,当时就三下五除二,写出了解:

1
2
3
4
5
6
7
8
9
10
11
12
13
let s = "1122" // answer should be 3.
var sum = 0
for c in s.enumerated() {
if c.offset == s.count - 1 {
if c.element == s[s.startIndex] {
sum += Int(String(c.element))!
}
} else {
if (c.element == s[s.index(s.startIndex, offsetBy: c.offset + 1)]) {
sum += Int(String(c.element))!
}
}
}

看起来没什么毛病,测试样例也能过。
然后得到了Part 2,题目变成了:

Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. That is, if your list contains 10items, only include a digit in your sum if the digit 10/2 = 5 steps forward match it. Fortunately, your list has an even number of elements.

emmmmmmm…
总的来说题目没怎么变化,但是现在不是求后面一个数字,而是求数字串一般长度的距离的那个数字。
其实也很简单,按照上面的思路,改一改就能过了。
但是这让我开始思考,第二部分和第一部分明明是同一个题目对应了不同的距离而已,而当时在写第一部分代码的时候,我却没有考虑过代码的扩展性。看到第二部分之后,想到我们可以把距离提成一个单独的变量,作为代码中一个可配置的点,这样无论距离怎么变,我们只需要修改距离变量,而不用改动其他代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let s = "1122"
var sum = 0
let step = s.count / 2
for c in s.enumerated() {
if c.offset + step > s.count - 1 {
if (c.element == s[s.index(s.startIndex, offsetBy: c.offset + step - s.count)]) {
sum += Int(String(c.element))!
}
} else {
if (c.element == s[s.index(s.startIndex, offsetBy: c.offset + step)]) {
sum += Int(String(c.element))!
}
}
}

Proudly powered by Hexo and Theme by Hacker
© 2021 KK