-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_7_while_loop.R
More file actions
82 lines (66 loc) · 1.84 KB
/
day_7_while_loop.R
File metadata and controls
82 lines (66 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
library(tidyverse)
input <- as_tibble((readLines("./inputs/input7.txt")))
##Part 1
`add` <- function(x, y) {as.numeric(x+y)}
`mult` <- function(x, y) {as.numeric(x*y)}
df <-
input %>%
separate(value, into = c("answer", "inputs"), sep = ": ") %>%
separate_rows(inputs, sep = " ") %>%
group_by(answer) %>%
summarize(
values = list(inputs),
.groups = "drop"
)
count <- 0
for(i in 1:nrow(df)){
# i <- 1
# print(i)
inputs <- as.numeric(df$values[[i]])
answer <- as.numeric(df$answer[[i]])
current_values <- inputs[1]
inputs <- inputs[-1]
while(length(inputs)>0){
current_values_add <- add(current_values, inputs[1])
current_values_mult <- mult(current_values, inputs[1])
current_values <- c(current_values_add, current_values_mult)
inputs <- inputs[-1]
}
if(answer %in% current_values){
count = count+answer
}
}
print(count %>% as.character)
##Part 2
`conc` <- function(x, y) {as.numeric(paste0(x,y))}
`add` <- function(x, y) {as.numeric(x+y)}
`mult` <- function(x, y) {as.numeric(x*y)}
df <-
input %>%
separate(value, into = c("answer", "inputs"), sep = ": ") %>%
separate_rows(inputs, sep = " ") %>%
group_by(answer) %>%
summarize(
values = list(inputs),
.groups = "drop"
)
count <- 0
for(i in 1:nrow(df)){
# i <- 1
# print(i)
inputs <- as.numeric(df$values[[i]])
answer <- as.numeric(df$answer[[i]])
current_values <- inputs[1]
inputs <- inputs[-1]
while(length(inputs)>0){
current_values_add <- add(current_values, inputs[1])
current_values_mult <- mult(current_values, inputs[1])
current_values_conc <- conc(current_values, inputs[1])
current_values <- c(current_values_add, current_values_mult, current_values_conc)
inputs <- inputs[-1]
}
if(answer %in% current_values){
count = count+answer
}
}
print(count %>% as.character)