Browse Source

Day 15 - hashmap package needed to speed things up, but not in cran

Petra Lamborn 3 years ago
parent
commit
43b5a01be9
1 changed files with 47 additions and 0 deletions
  1. 47
    0
      15.R

+ 47
- 0
15.R View File

@@ -0,0 +1,47 @@
1
+library(hashmap)
2
+
3
+input <- as.integer(c(2,0,1,7,4,14,18))
4
+
5
+vals <- numeric(0)
6
+sapply(1:2020, function(x) {
7
+           if (x <= length(input)) {
8
+               vals <<- c(vals, input[x])
9
+               return(input[x])
10
+           } else {
11
+               can <- vals[x - 1]
12
+               pos <- which(can == vals[1:(x - 2)])
13
+               if (length(pos) == 0) {
14
+                   vals <<- c(vals, 0)
15
+                   return(0)
16
+               } else {
17
+                   le <- max(pos)
18
+                   vals <<- c(vals, x - 1 - le)
19
+                   return(x - 1 - le)
20
+               }
21
+           }
22
+})
23
+
24
+
25
+# Part 2
26
+
27
+hasha <- hashmap(as.integer(input[1:(length(input) - 1)]), as.integer(1:(length(input) - 1)))
28
+# hashb <- hashmap(numeric(0), numeric(0))
29
+
30
+last <- tail(input, 1)
31
+lb1 <- input[length(input) - 1]
32
+
33
+for (x in (length(input)):30000000) {
34
+    if ((x %% 10000) == 0) {
35
+        print(x)
36
+    }
37
+    hl <- hasha[[last]]
38
+    lb1 <- last
39
+    if (is.na(hl)) {
40
+        last <- 0
41
+    } else {
42
+        last <- (x) - hl
43
+    }
44
+    hasha[[lb1]] <- x
45
+    # print(lb1)
46
+}
47
+print(lb1)