Browse Source

Nim day 2

master
Chris Smith 5 years ago
parent
commit
09ad330e31
1 changed files with 40 additions and 0 deletions
  1. 40
    0
      day02.nim

+ 40
- 0
day02.nim View File

@@ -0,0 +1,40 @@
1
+import sequtils, strutils
2
+
3
+proc checksum(ids: seq[string]): int =
4
+    var pairCount, tripCount: int
5
+    for id in ids:
6
+        var pairs, trips: bool
7
+        for c in id:
8
+            var count = id.count(c)
9
+            if count == 2 and not pairs:
10
+                pairs = true
11
+                pairCount.inc
12
+            if count == 3 and not trips:
13
+                trips = true
14
+                tripCount.inc
15
+            if pairs and trips:
16
+                break
17
+    pairCount * tripCount
18
+
19
+proc difference(pairs: seq[tuple[a: char, b: char]]): string =
20
+    var difference: bool
21
+    for pair in pairs:
22
+        if pair.a != pair.b:
23
+            if difference:
24
+                return ""
25
+            else:
26
+                difference = true
27
+        else:
28
+            result &= pair.a
29
+
30
+proc max_common(ids: seq[string]): string =
31
+    for i, id1 in ids:
32
+        for id2 in ids[i+1 .. ids.high]:
33
+            let difference = zip(id1, id2).difference
34
+            if difference != "":
35
+                return difference
36
+    
37
+
38
+let ids = readFile("data/02.txt").strip.splitlines
39
+echo ids.checksum
40
+echo ids.max_common