Skip to content

Instantly share code, notes, and snippets.

@namarkus
Last active April 7, 2021 07:41
Show Gist options
  • Save namarkus/17ca3a048f4ea56fbc74106c770542ae to your computer and use it in GitHub Desktop.
Save namarkus/17ca3a048f4ea56fbc74106c770542ae to your computer and use it in GitHub Desktop.
Advent of Code 2020
# Day 22 ------------------------------------------------------------------
squares = [1, 4, 9, 16, 25]
squares
squares[4] = 26
squares[0:2]
squares[1:]
deckA = [9, 2, 6, 3, 1]
deckB = [5, 8, 4, 7, 10]
deckA = [14, 29, 25, 17, 13, 50, 33, 32, 7, 37, 26, 34, 46, 24, 3, 28, 18, 20, 11, 1, 21, 8, 44, 10, 22]
deckB = [5, 38, 27, 15, 45, 40, 43, 30, 35, 9, 48, 12, 16, 47, 42, 4, 2, 31, 41, 39, 23, 19, 36, 49, 6]
counter = 0
while len(deckA) > 0 and len(deckB) > 0:
dealA = deckA.pop(0)
dealB = deckB.pop(0)
if dealA > dealB:
deckA = deckA + [dealA, dealB]
else:
deckB = deckB + [dealB, dealA]
counter = counter + 1
counter
deckA
deckB
res = 0
for i in range(len(deckB)):
res = res + deckB[i] * (len(deckB)-i)
print(i)
res
x = 'A' + ''.join(str(deckA)) + 'B' + ''.join(str(deckB))
constellation = constellation + [x]
''.join(str(e) for e in deckB)
deckA = [9, 2, 6, 3, 1]
deckB = [5, 8, 4, 7, 10]
deckA = [14, 29, 25, 17, 13, 50, 33, 32, 7, 37, 26, 34, 46, 24, 3, 28, 18, 20, 11, 1, 21, 8, 44, 10, 22]
deckB = [5, 38, 27, 15, 45, 40, 43, 30, 35, 9, 48, 12, 16, 47, 42, 4, 2, 31, 41, 39, 23, 19, 36, 49, 6]
configurations = []
counter = 0
while len(deckA) > 0 and len(deckB) > 0:
dealA = deckA.pop(0)
dealB = deckB.pop(0)
if len(deckA) >= dealA and len(deckB) >= dealB:
elif dealA > dealB:
deckA = deckA + [dealA, dealB]
else:
deckB = deckB + [dealB, dealA]
counter = counter + 1
new_conf = 'A' + ''.join(str(deckA)) + 'B' + ''.join(str(deckB))
if new_conf in configurations:
print('configuration appeared before')
break
configurations = configurations + [new_conf]
counter
len(configurations)
configurations
deckA
deckB
# Day 23 ------------------------------------------------------------------
input1 = list('389125467')
cups = input1
nc = len(input1) # number of cups
curr_idx = 0
curr = cups[curr_idx]
for i in range(10):
cups_out_idx = [x % nc for x in range(curr_idx + 1, curr_idx + 4)]
cups_out = [cups[i] for i in cups_out_idx]
cups_in = [cups[i] for i in range(0, nc) if i not in cups_out_idx]
cups_in_s = cups_in.copy()
cups_in_s.sort()
cups_in_s.reverse()
dest = cups_in_s[(cups_in_s.index(curr) + 1) % (nc-3)]
dest_idx = cups_in.index(dest)
cups = cups_in[0:(dest_idx+1)] + cups_out + cups_in[(dest_idx + 1):nc]
curr_idx = (curr_idx + 1) % nc
curr = cups[curr_idx]
print(i, cups)
# Day 24 ------------------------------------------------------------------
def cryptographic_handshake(subject_nr, loop_size):
value = 1
for i in range(loop_size):
value = value * subject_nr
value = value % 20201227
return value
cryptographic_handshake(7, 8)
def get_loop_size(subject_nr, public_key):
value = 1
i = 0
while value != public_key and i < 1000000000:
value = (value * subject_nr) % 20201227
i = i + 1
if i % 10000000 == 0: print(str(i) + ': ' + str(value))
if value == public_key: return i
return 0
get_loop_size(7, 5764801)
pk_card = 19241437
ls_card = get_loop_size(7, pk_card)
cryptographic_handshake(7, ls_card)
pk_door = 17346587
ls_door = get_loop_size(7, pk_door)
cryptographic_handshake(7, ls_door)
cryptographic_handshake(pk_door, ls_card)
cryptographic_handshake(pk_card, ls_door)
# Advent of Code 2020
# 1 ----------------------------------------------------------------
library(tidyr)
library(dplyr)
input1 = readClipboard()
input1 = as.integer(input1)
df = crossing(var1=input1, var2=input1)
df %>%
mutate(sumVar = var1 + var2,
prodVar = var1 * var2) %>%
filter(sumVar == 2020L)
df = crossing(var1=input1, var2=input1, var3=input1)
df %>%
mutate(sumVar = var1 + var2 + var3,
prodVar = var1 * var2 * var3) %>%
filter(sumVar == 2020L)
# 2 ----------------------------------------------------------------
library(stringr)
library(tidyr)
library(dplyr)
input1 = readClipboard()
input1 %>%
as_tibble() %>%
extract(value, into=c('min', 'max', 'letter', 'pw'),
regex='^(\\d{1,2})-(\\d{1,2}) ([a-z]): (.*)$') %>%
mutate(across(c(min, max), as.integer)) %>%
mutate(n = str_count(pw, letter)) %>%
filter(n>=min & n<=max) %>%
nrow()
input1 %>%
as_tibble() %>%
mutate(id = row_number()) %>%
extract(value, into=c('pos1', 'pos2', 'letter', 'pw'),
regex='^(\\d{1,2})-(\\d{1,2}) ([a-z]): (.*)$') %>%
mutate(across(c(pos1, pos2), as.integer)) %>%
pivot_longer(cols=c(pos1, pos2), values_to='pos') %>%
mutate(pos_letter = str_sub(pw, pos, pos)) %>%
filter(pos_letter == letter) %>%
count(id) %>%
filter(n==1) %>%
nrow()
# 3 ----------------------------------------------------------------
library(purrr)
library(tidyr)
library(dplyr)
input1 = readClipboard()
count_trees <- function(df, shiftx=0L, shifty=1L) {
df %>%
mutate(maxx = nchar(input),
posy = row_number() - 1L,
keeprow = (posy %% shifty) == 0,
posy = posy %/% shifty) %>%
filter(keeprow) %>%
mutate(posx = posy * shiftx + 1L,
posx = posx %% maxx, # nach Pos maxx wieder bei 1 beginnen
posx = if_else((posx %% maxx) == 0, maxx, posx),
chrx = str_sub(input, posx, posx)) %>%
summarise(nTrees = sum(chrx == '#'), .groups='drop') %>%
pull(nTrees)
}
df = tibble(input = input1)
tibble(input = input1) %>%
nest(df=input) %>%
bind_cols(tibble(shiftx = as.integer(c(1,3,5,7,1)), shifty = as.integer(c(1,1,1,1,2)))) %>%
pmap_int(count_trees) %>%
prod()
# 4 ----------------------------------------------------------------
library(purrr)
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
passports =
tibble(input = input1) %>%
mutate(passport = cumsum(input=='')) %>%
filter(input!='') %>%
group_by(passport) %>%
summarise(keyvalues = paste(input, collapse =' '), .groups = 'drop') %>%
mutate(keyvalues = strsplit(keyvalues, split = ' ')) %>%
unnest(keyvalues) %>%
separate(keyvalues, into=c('key', 'value'), sep=':') %>%
filter(key != 'cid') # cid muss nicht überprüft werden
passports %>%
count(passport) %>%
count(n==7)
check_pp <- function(key, data) {
value = data$value
res = rep(FALSE, length(value))
if(key == 'byr') res = between(as.integer(value), 1920L, 2002L)
if(key == 'iyr') res = between(as.integer(value), 2010L, 2020L)
if(key == 'eyr') res = between(as.integer(value), 2020L, 2030L)
if(key == 'hgt') {
hgt_val = sub('^(\\d+)([a-z]{2})$', '\\1', value)
hgt_val = as.integer(hgt_val)
hgt_unit = sub('^(\\d+)([a-z]{2})$', '\\2', value)
res = (hgt_unit == 'cm' & between(hgt_val, 150L, 193L)) | (hgt_unit == 'in' & between(hgt_val, 59L, 76L))
}
if(key == 'hcl') res = grepl('^#[a-f0-9]{6}$', value)
if(key == 'ecl') res = value %in% c('amb','blu','brn','gry','grn','hzl','oth')
if(key == 'pid') res = grepl('^[0-9]{9}$', value)
data$res = res
return(data)
}
passports %>%
nest(data=c(passport, value)) %>%
mutate(data = pmap(., check_pp)) %>%
unnest(data) %>%
group_by(passport) %>%
summarise(is_valid = sum(res)==7L) %>%
count(is_valid)
# 5 ----------------------------------------------------------------
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
i = 2^(0:6)
rows =
map2(64L/i, i, ~rep(rep(c('F','B'), each=.x), .y)) %>%
bind_cols() %>%
unite(col='row_c', everything(), sep='') %>%
mutate(row_nr = row_number()-1)
j = 2^(0:2)
seats =
map2(4L/j, j, ~rep(rep(c('L','R'), each=.x), .y)) %>%
bind_cols() %>%
unite(col='seat_c', everything(), sep='') %>%
mutate(seat_nr = row_number()-1)
seatid =
tibble(input = input1) %>%
mutate(row_c = substr(input,1,7),
seat_c = substr(input,8,10)) %>%
left_join(rows, by='row_c') %>%
left_join(seats, by='seat_c') %>%
mutate(ID = row_nr * 8 + seat_nr)
max(seatid$ID) # answ 1: 989
seatid %>%
arrange(ID) %>%
mutate(ID_before = lag(ID),
gap = ID - ID_before - 1L) %>%
filter(gap == 1L)
# 6 ----------------------------------------------------------------
library(purrr)
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
answers =
tibble(input = input1) %>%
mutate(grp_id = cumsum(input=='')) %>%
filter(input!='')
answers %>%
group_by(grp_id) %>%
summarise(yes_answers = paste(input, collapse='')) %>%
mutate(n_answ = map_int(yes_answers, ~length(unique(strsplit(., '')[[1]])))) %>%
summarise(code = sum(n_answ)) # answ 1: 6735
answers %>%
group_by(grp_id) %>%
mutate(anz_psng = n()) %>%
mutate(inp = map(input, ~unique(strsplit(., '')[[1]]))) %>%
unchop(inp) %>%
count(grp_id, anz_psng, inp) %>%
filter(n == anz_psng) %>%
nrow()
# 7 ----------------------------------------------------------------
library(magrittr)
library(purrr)
library(data.tree)
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
input1 = sub('\\.$', '', input1)
input1 = gsub(' bags', '', input1)
input1 = gsub(' bag', '', input1)
bag_data =
tibble(input=input1) %>%
# head(8) %>%
separate(input, into=c('root', 'child'), sep=' contain ') %>%
mutate(child = strsplit(child, split=', ')) %>%
unchop(child) %>%
group_by(root) %>%
mutate(child_nr = row_number(),
n_children = n()) %>%
ungroup() %>%
tidyr::extract(child, into=c('nob', 'child'), regex='^(\\d+) (.*)$')
root_bags = anti_join(bag_data, bag_data, by=c('root'='child'))
child_bags = anti_join(bag_data, root_bags, by='root')
add_children <- function(root_bags, child_bags, hierarchie=0) {
last_child = names(root_bags)[ncol(root_bags)]
level_nr = as.character(as.integer(sub('.*_(\\d*)$', '\\1', last_child)) + 1L)
child_bags %<>% rename_with(~paste0(., '_', level_nr), .cols=c(nob, child))
root_bags %<>% left_join(child_bags, by=setNames('root', last_child))
n_leafs = root_bags %>% mutate(is_leaf = across(last_col(), is.na)) %>% count(is_leaf) %>% pull(n)
print(paste0(round(n_leafs[2] / sum(n_leafs) * 100, 0), '%'))
return(root_bags)
}
root_bags =
anti_join(bag_data, bag_data, by=c('root'='child')) %>%
distinct(child_0 = root) %>%
mutate(root = 'all', .before='child_0') %>%
group_by(root) %>%
mutate(path = row_number()) %>%
ungroup()
child_bags = bag_data %>% select(root, child, nob, child_nr)
add_children <- function(root_bags, child_bags, hierarchie=0) {
last_child = names(root_bags)[ncol(root_bags)-1]
level_nr = as.character(as.integer(sub('.*_(\\d*)$', '\\1', last_child)) + 1L)
child_bags %<>% rename_with(~paste0(., '_', level_nr), .cols=c(nob, child))
root_bags %<>%
left_join(child_bags, by=setNames('root', last_child)) %>%
mutate(path = path * 10 + coalesce(child_nr, 0)) %>%
select(-child_nr)
n_leafs = root_bags %>% mutate(is_leaf = across(last_col(), is.na)) %>% count(is_leaf) %>% pull(n)
print(paste0(round(n_leafs[2] / sum(n_leafs) * 100, 2), '%'))
return(root_bags)
}
bag_tree = root_bags %>% add_children(child_bags)
while(any(!is.na(bag_tree[ncol(bag_tree)-1]))) bag_tree %<>% add_children(child_bags)
gold_root_bags =
bag_data %>% filter(root == 'shiny gold') %>%
mutate(path = row_number()) %>%
select(root, path, child_0 = child, nob_0=nob)
gold_bag_tree = gold_root_bags %>% add_children(child_bags)
while(any(!is.na(gold_bag_tree[ncol(gold_bag_tree)-1]))) gold_bag_tree %<>% add_children(child_bags)
bgsbags =
gold_bag_tree %>%
pivot_longer(-c(root, path), names_to=c('.value', 'level'), names_sep='_') %>%
filter(!is.na(child)) %>%
group_by(path) %>%
mutate(n_bag = cumprod(nob)) %>%
ungroup
bags7 = bgsbags %>% filter(level==7) %>% distinct(root, child, n_bag)
bags6 = bgsbags %>% filter(level==6) %>% mutate(path = path %/% 10) %>% distinct(root, child, n_bag)
bags5 = bgsbags %>% filter(level==5) %>% mutate(path = path %/% 100) %>% distinct(root, child, n_bag)
bags4 = bgsbags %>% filter(level==4) %>% mutate(path = path %/% 1000) %>% distinct(root, child, n_bag)
bags3 = bgsbags %>% filter(level==3) %>% mutate(path = path %/% 10000) %>% distinct(root, child, n_bag)
bags2 = bgsbags %>% filter(level==2) %>% mutate(path = path %/% 100000) %>% distinct(root, child, n_bag)
bags1 = bgsbags %>% filter(level==1) %>% mutate(path = path %/% 1000000) %>% distinct(root, child, n_bag)
bags0 = bgsbags %>% filter(level==0) %>% mutate(path = path %/% 10000000) %>% distinct(root, child, n_bag)
bind_rows(bags0, bags1, bags2, bags3, bags4, bags5, bags6, bags7) %>%
summarise(total = sum(n_bag))
# 8 ----------------------------------------------------------------
input1 = c('nop +0', 'acc +1', 'jmp +4', 'acc +3', 'jmp -3', 'acc -99', 'acc +1', 'jmp -4', 'acc +6')
input1 = readClipboard()
op = sub('^([a-z]{3}).*', '\\1', input1)
arg = as.integer(sub('^[a-z]{3} (.*)$', '\\1', input1))
j = 0L
i = 1L
acc0 = 0L
step = logical(length = length(op))
while(!step[i] & j < 10000) {
if(op[i] == 'acc') acc0 = acc0 + arg[i]
step[i] = TRUE
j = j + 1
print(paste0('j=',j,' / i=',i,' / acc0=',acc0))
if(op[i] == 'jmp') {
i = i + arg[i]
} else {
i = i + 1L
}
}
for (k in (which(op %in% c('nop', 'jmp')))) {
op2 = op
if(op2[k] == 'nop') {
op2[k] = 'jmp'
} else if (op2[k] == 'jmp') {
op2[k] = 'nop'
}
j = 0L
i = 1L
acc0 = 0L
step = logical(length = length(op2))
while(!step[i] & i <= length(op2) & j < 10000) {
if(op2[i] == 'acc') acc0 = acc0 + arg[i]
step[i] = TRUE
j = j + 1
# print(paste0('j=',j,' / i=',i,' / acc0=',acc0))
if(op2[i] == 'jmp') {
i = i + arg[i]
} else {
i = i + 1L
}
}
if(i > length(op2)) break
}
j
i
k
acc0
# 9 ----------------------------------------------------------------
library(magrittr)
library(purrr)
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = c('35' ,'20' ,'15' ,'25' ,'47' ,'40' ,'62' ,'55' ,'65' ,'95' ,'102' ,'117' ,'150' ,'182' ,'127' ,'219' ,'299' ,'277' ,'309' ,'576')
input1 = readClipboard()
input1 = as.numeric(input1)
NR = length(input1)
PREAM = 25L
pairsums = expand.grid(in1 = input1, in2 =input1)
pairsums %<>%
mutate(i = rep(1:NR, each=NR),
j = rep(1:NR, NR),
.before=in1) %>%
filter(i != j & abs(i - j < PREAM)) %>%
mutate(pairsum = in1 + in2)
for(k in (PREAM+1L):NR) {
presums =
pairsums %>%
filter(between(i, k-PREAM, k - 1L)) %>%
filter(between(j, k-PREAM, k - 1L)) %>%
pull(pairsum)
if(!input1[k] %in% presums) break
}
k
input1[k] # answ 1: 1212510616
consums = map(1:NR, ~cumsum(input1[.:NR]))
for(i in 1:NR) {
consum = consums[[i]]
j = which(consum == 1212510616)
if(length(j) > 0) break
}
i
j
input1[i:(i+j-1)]
sum(range(input1[i:(i+j-1)])) # answ 2: 171265123
# 10 ----------------------------------------------------------------
input1 = c(16,10,15,5,1,11,7,19,6,12,4)
input1 = c(28,33,18,42,31,14,46,20,48,47,24,23,49,45,19,38,39,11,1,32,25,35,8,17,7,9,4,2,34,10,3)
input1 = readClipboard()
adapters = c(0L, sort(as.integer(input1)), max(as.integer(input1)) + 3L)
diffs = adapters[-1] - adapters[-length(adapters)]
table(diffs)
sum(diffs==1L) * sum(diffs==3L) # answer 1: 2738
x2 = gregexpr('(?<!1)1{2}(?!1)', paste(diffs, collapse=''), perl=TRUE)[[1]]
x3 = gregexpr('(?<!1)1{3}(?!1)', paste(diffs, collapse=''), perl=TRUE)[[1]]
x4 = gregexpr('(?<!1)1{4}(?!1)', paste(diffs, collapse=''), perl=TRUE)[[1]]
x5 = gregexpr('(?<!1)1{5}(?!1)', paste(diffs, collapse=''), perl=TRUE)[[1]]
options(scipen=7)
2^length(x2) * 4^length(x3) * 7^length(x4)
# 10 ----------------------------------------------------------------
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = c(0L,3L,6L)
input1 = c(1L,3L,2L)
input1 = c(2L,1L,3L)
input1 = c(1L,2L,3L)
input1 = c(3L,1L,2L)
input1 = as.integer(c(0,20,7,16,1,18,15))
nmbrs = tibble(nmbr = 0:999999,
n_spoken = 0L,
last_pos = NA_integer_,
pre_pos = NA_integer_)
for(i in 1:length(input1)) {
nmbrs$last_pos[nmbrs$nmbr==input1[i]] = i
nmbrs$n_spoken[nmbrs$nmbr==input1[i]] = 1L
}
last_nmbr = input1[i]
curr = last_nmbr
play = nmbrs
for(i in (length(input1)+1):2020) {
if(play$n_spoken[play$nmbr == curr] == 1) {
curr = 0L
} else {
curr = play$last_pos[play$nmbr == curr] - play$pre_pos[play$nmbr == curr]
}
play$pre_pos[play$nmbr == curr] = play$last_pos[play$nmbr == curr]
play$last_pos[play$nmbr == curr] = i
play$n_spoken[play$nmbr == curr] = play$n_spoken[play$nmbr == curr] + 1
if(i %% 100 == 0L) print(paste(round(i / 2020 * 100, 1), '%'))
}
play
curr
# answer 1: 1025
n_spoken = integer()
last_pos = integer()
pre_pos = integer()
n_spoken[input1 + 1] = 1L
last_pos[input1 + 1] = 1:length(input1)
curr = input1[length(input1)]
for(i in (length(input1)+1):30000000) {
if(n_spoken[curr + 1] == 1) {
curr = 0L
} else {
curr = last_pos[curr+1] - pre_pos[curr+1]
}
pre_pos[curr + 1] = last_pos[curr + 1]
last_pos[curr + 1] = i
n_spoken[curr + 1] = ifelse(is.na(n_spoken[curr + 1]), 1L, n_spoken[curr + 1] + 1)
if(i %% 1000000 == 0L) print(paste(round(i / 30000000 * 100, 1), '%'))
}
i
curr
# 16 ----------------------------------------------------------------
library(magrittr)
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
input2 = readClipboard()
input3 = readClipboard()
df1 =
tibble(input = input1) %>%
extract(input, into=c('field', 'range1', 'range2'), regex = '^(.*?): (.*?) or (.*)$') %>%
pivot_longer(cols=c(range1:range2), names_to='range_nr', values_to='range') %>%
separate(range, into=c('lo', 'hi'), sep='-') %>%
mutate(across(c(lo:hi), as.integer)) %>%
rowwise() %>%
mutate(valid_nrs = list(seq(lo, hi))) %>%
ungroup() %>%
unchop(valid_nrs)
df3 =
tibble(input = input3) %>%
mutate(id = row_number()) %>%
mutate(field_val = strsplit(input, split=',')) %>%
unchop(field_val) %>%
mutate(field_val = as.integer(field_val)) %>%
group_by(id) %>%
mutate(field_nr = row_number()) %>%
ungroup() %>%
select(id, field_nr, field_val)
df3 %>%
anti_join(df1, by=c('field_val' = 'valid_nrs')) %>%
summarise(answ1 = sum(field_val))
# answer1: 26988
valid_tix =
df3 %>%
mutate(valid_nr = field_val %in% unique(df1$valid_nrs)) %>%
group_by(id) %>%
filter(all(valid_nr)) %>%
ungroup()
df =
inner_join(df1, valid_tix, by=c('valid_nrs' = 'field_val')) %>%
distinct(field, id, field_nr) %>%
count(field, field_nr) %>%
filter(n==190) %>%
group_by(field) %>%
mutate(n_field_nrs = n_distinct(field_nr)) %>%
ungroup()
field_nr_multi = df %>% select(field_name = field, field_nr, n_field_nrs)
field_nr_match = tibble(field_name = character(), field_nr = integer())
i = 1L
while(sum(field_nr_multi$n_field_nrs==1L)==1L) {
field_nr_match %<>%
bind_rows(field_nr_multi %>% filter(n_field_nrs==1L) %>% select(field_name, field_nr))
field_nr_multi %<>%
anti_join(field_nr_match, by='field_nr') %>%
group_by(field_name) %>%
mutate(n_field_nrs = n_distinct(field_nr)) %>%
ungroup()
i=i+1
}
prod(as.integer(strsplit(input2, split=',')[[1]])[field_nr_match$field_nr[grepl('^departure', field_nr_match$field_name)]])
# 17 ----------------------------------------------------------------
library(magrittr)
library(ggplot2)
library(tidyr)
library(dplyr)
input1 = c('.#.', '..#', '###')
input1 = readClipboard()
initial_active = gregexpr('\\#', input1)
cube_dim = 25
mid_cell = 12
df =
crossing(x=1:cube_dim, y=1:cube_dim, z=1:cube_dim) %>%
mutate(id = row_number(),
state = FALSE,
nb_state = FALSE) %>%
rowwise() %>%
mutate(across(c(x,y,z), ~list(c(.-1L, . ,.+1L)), .names='nb_{.col}')) %>%
unchop(nb_x) %>% unchop(nb_y) %>% unchop(nb_z) %>%
mutate(id_fg = x==nb_x & y==nb_y & z==nb_z) %>%
group_by(nb_x, nb_y, nb_z) %>%
mutate(nb_id = median(id[id_fg])) %>%
ungroup() %>%
filter(!is.na(nb_id)) %>%
select(id, x, y, z, state, id_fg, nb_id, nb_state)
df2 = df
for(i in 1:length(initial_active)) {
y = c((mid_cell-4):(mid_cell+3))[i]
x = initial_active[[i]] + mid_cell - 4
df2$state[df2$x %in% x & df2$y == y & df2$z==mid_cell] = TRUE
}
df2 %>%
filter(z == mid_cell) %>%
ggplot(aes(x,y, fill=state)) +
geom_tile() +
scale_y_continuous(trans = "reverse")
activate <- function(df) {
df %>%
group_by(nb_id) %>%
mutate(nb_state = all(state[id_fg], na.rm=TRUE)) %>%
ungroup() %>%
group_by(id) %>%
mutate(active_nb = sum(nb_state[!id_fg])) %>%
mutate(state = case_when(state & (active_nb < 2L | active_nb > 3L) ~ FALSE,
!state & active_nb == 3L ~ TRUE,
TRUE ~ state)) %>%
ungroup()
}
df3 = df2 %>% activate() %>% activate() %>% activate() %>% activate() %>% activate() %>% activate()
df3 %>%
filter(z %in% c(6:10) & id==id_nb) %>%
ggplot(aes(x, y, fill=state)) +
geom_tile() +
scale_y_continuous(trans = "reverse") +
facet_wrap(vars(z))
df3 %>%
filter(id==id_nb) %>%
ggplot(aes(x, y, fill=state)) +
geom_tile() +
scale_y_continuous(trans = "reverse") +
facet_wrap(vars(z))
df3 %>% filter(id_fg) %>% count(state) # answer 1: 424
df4 =
df =
crossing(x=1:cube_dim, y=1:cube_dim, z=1:cube_dim, w=1:cube_dim) %>%
mutate(id = row_number(),
state = FALSE,
nb_state = FALSE) %>%
rowwise() %>%
mutate(across(c(x,y,z,w), ~list(c(.-1L, . ,.+1L)), .names='nb_{.col}')) %>%
unchop(nb_x) %>% unchop(nb_y) %>% unchop(nb_z) %>% unchop(nb_w) %>%
mutate(id_fg = x==nb_x & y==nb_y & z==nb_z & w==nb_w) %>%
group_by(nb_x, nb_y, nb_z, nb_w) %>%
mutate(nb_id = median(id[id_fg])) %>%
ungroup() %>%
filter(!is.na(nb_id)) %>%
select(id, x, y, z, w, state, id_fg, nb_id, nb_state)
df5 = df4
for(i in 1:length(initial_active)) {
y = c((mid_cell-4):(mid_cell+3))[i]
x = initial_active[[i]] + mid_cell - 4
df5$state[df5$x %in% x & df5$y == y & df5$z==mid_cell & df5$w==mid_cell] = TRUE
}
df5 %>%
activate() %>%
filter(id_fg & z==mid_cell & w==mid_cell) %>%
ggplot(aes(x, y, fill=state)) +
geom_tile() +
scale_y_continuous(trans = "reverse")
df6 = df5 %>% activate() %>% activate() %>% activate() %>% activate() %>% activate() %>% activate()
df6 %>%
filter(id_fg & w==mid_cell) %>%
ggplot(aes(x, y, fill=state)) +
geom_tile() +
scale_y_continuous(trans = "reverse") +
facet_wrap(vars(z))
df6 %>% filter(id_fg) %>% count(state) # answer 2: 2460
# 18 ------------------------------------------------------------
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
input2 = readClipboard()
df =
tibble(input = input1) %>%
mutate(input = gsub('"', '', input)) %>%
separate(input, into=c('rule_nr', 'rule'), sep=': ') %>%
mutate(rule = if_else(grepl('\\|', rule), paste('(', rule, ')'), rule)) %>%
mutate(rule2 = strsplit(rule, split=' '))
rule0 = as.list(df$rule2[df$rule_nr=='0'][[1]])
nrules = length(rule0)
j=0
while (!all(grepl('[a-z|()]', rule0))) {
j=j+1
for(i in 1:length(rule0)) {
curr_rule_nr = rule0[[i]]
if(grepl('[|\\(\\)]', curr_rule_nr)) next
curr_rule_nr = rule0[[i]]
if(grepl('^[a-z]$', curr_rule_nr)) next
rule0[i] = df$rule2[df$rule_nr==curr_rule_nr]
}
rule0 = as.list(unlist(rule0))
nrules = length(rule0)
}
i
j
regex0 = paste0('^', paste(rule0, collapse=''), '$')
sum(grepl(regex0, input2))
# 21 ----------------------------------------------------------------
library(magrittr)
library(tidyr)
library(dplyr)
input1 = readClipboard()
foods =
tibble(input = input1) %>%
mutate(food_nr = row_number(), .before=input) %>%
separate(input, into=c('ingredients', 'allergenes'), sep=' \\(contains ') %>%
mutate(allergenes = sub('\\)$', '', allergenes)) %>%
mutate(allergenes = strsplit(allergenes, split=', ')) %>%
unchop(allergenes) %>%
group_by(food_nr) %>%
mutate(allerg_nr = row_number()) %>%
mutate(ingredients = strsplit(ingredients, split=' ')) %>%
unchop(ingredients) %>%
mutate(fg = 1L) %>%
select(food_nr, allergenes, allerg_nr, ingredients, fg)
allergenes = unique(foods$allergenes)
ingredients = unique(foods$ingredients)
# all combinations of allergenes and ingredients
combs = as_tibble(t(combn(ingredients, length(allergenes))))
names(combs) = allergenes
combs %<>%
mutate(comb_id = row_number()) %>%
pivot_longer(-c(comb_id), names_to='allerg_comb', values_to='ingredients')
combn(1:15, m=8)
200 * 199 * 198 * 197 * 196 * 195 * 194 * 193
foods %>%
inner_join(combs, by='ingredients') %>%
mutate(allg_match = if_else(allergenes == allerg_comb, 1L, 0L)) %>%
group_by(comb_id, food_nr, allerg_nr) %>%
summarise(x = sum(allg_match)) %>%
group_by(comb_id) %>%
summarise(comb_ok = all(x==1L))
combs %>% filter(comb_id == 8L)
foods %>%
anti_join(filter(combs, comb_id==8L), by='ingredients') %>%
distinct(food_nr, ingredients) %>%
nrow()
# 24 ------------------------------------------------------------
library(purrr)
library(tidyr, warn.conflicts=FALSE)
library(dplyr, warn.conflicts=FALSE)
input1 = readClipboard()
tibble(input = input1) %>%
mutate(id = row_number()) %>%
rowwise() %>%
mutate(input = gsub('([ew])', '\\1|', input),
direction = strsplit(input, split='\\|')) %>%
ungroup() %>%
mutate(dir_x = map(direction, ~recode(., e = 1, w = -1, ne = 0.5, nw = -0.5, se = 0.5, sw = -0.5)),
dir_y = map(direction, ~recode(., e = 0, w = 0, ne = 1, nw = 1, se = -1, sw = -1))) %>%
mutate(dir_x2 = map_dbl(dir_x, ~sum(.)),
dir_y2 = map_dbl(dir_y, ~sum(.))) %>%
count(dir_x2, dir_y2) %>%
count(n)
ungroup() %>%
slice(1) %>% pull(direction)
mutate(input2 = gsub('(([ns][ew])|([^ns][ew]))', '\\1|', input)) %>% tail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment