Skip to content

Commit f2919d3

Browse files
author
Abhishek Sunkum Rammurthy
committed
Solutions till day6
0 parents  commit f2919d3

18 files changed

+2035
-0
lines changed

day1.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/python3
2+
import pandas as pd
3+
import numpy as np
4+
import re
5+
6+
filename="/home/abhi/repos/aoc/inputs/trebuchet_input.txt"
7+
with open(filename) as f:
8+
lines = [line.rstrip() for line in f]
9+
10+
word2int = {
11+
'one':'1',
12+
'two':'2',
13+
'three':'3',
14+
'four':'4',
15+
'five':'5',
16+
'six':'6',
17+
'seven':'7',
18+
'eight':'8',
19+
'nine':'9'
20+
}
21+
22+
total = 0
23+
for l in lines:
24+
df = pd.DataFrame(
25+
{
26+
'words':word2int.keys(),
27+
'id':-1,
28+
'len':0
29+
}
30+
)
31+
print(l, end=', ')
32+
temp_l = list(l)
33+
for w in word2int:
34+
ids = [m.start() for m in re.finditer(w, l)]
35+
for id in ids:
36+
temp_l[id] = word2int[w]
37+
l = ''.join(temp_l)
38+
n = ''.join(re.findall(r'\d+', l))
39+
print(n, end = ', ')
40+
calib_val = int(n[0])*10 + int(n[-1])
41+
print(calib_val)
42+
if len(n):
43+
total = total + calib_val
44+
print(f'total calibration value = {total}')
45+

day2.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/python3
2+
import pandas as pd
3+
import numpy as np
4+
import sys
5+
import re
6+
7+
argc = len(sys.argv)
8+
if argc != 2:
9+
print("Provide filename of the input")
10+
quit()
11+
12+
filename = sys.argv[1]
13+
print(f'input used {filename}')
14+
15+
with open(filename) as f:
16+
lines = [line.rstrip() for line in f]
17+
18+
num_games = len(lines)
19+
df = pd.DataFrame(
20+
{
21+
'id' : np.arange(0, num_games, dtype=int)+1,
22+
'red': np.zeros(num_games, dtype=int),
23+
'green': np.zeros(num_games, dtype=int),
24+
'blue': np.zeros(num_games, dtype=int)
25+
}
26+
)
27+
28+
power_of_set = 0
29+
for i, l in enumerate(lines):
30+
for c in ['red', 'green', 'blue']:
31+
num_cubes = [int(re.match(r'\d+', m).group(0)) for m in re.findall(r'\d+ '+c, l)]
32+
df.at[i, c] = max(num_cubes)
33+
df_part1 = df[(df['red'] <= 12) & (df['green'] <= 13) & (df['blue'] <= 14)]
34+
power_of_set = power_of_set + (df['red'][i] * df['green'][i] * df['blue'][i])
35+
36+
print(df_part1['id'].sum())
37+
print(f'{power_of_set=}')

day3.py

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/python3
2+
import pandas as pd
3+
import numpy as np
4+
import sys
5+
import re
6+
7+
argc = len(sys.argv)
8+
if argc != 2:
9+
print("Provide filename of the input")
10+
quit()
11+
12+
filename = sys.argv[1]
13+
print(f'input used {filename}')
14+
15+
with open(filename) as f:
16+
lines = [line.rstrip() for line in f]
17+
18+
line_count = len(lines)
19+
total = 0
20+
for line_num, l in enumerate(lines):
21+
matches = [m for m in re.finditer(r'\d+', l)]
22+
boundary = len(l)
23+
for m in matches:
24+
search_str = ''
25+
start = m.start()
26+
end = m.end()
27+
if end < boundary:
28+
end = end + 1
29+
if start > 0:
30+
start = start -1
31+
search_str = search_str + l[start:end] #current line
32+
if line_num > 0:
33+
search_str = search_str + lines[line_num - 1][start:end]
34+
if line_num < (line_count - 1):
35+
search_str = search_str + lines[line_num + 1][start:end]
36+
37+
if symbol_match := re.search(r'[^\d\.]', search_str):
38+
# print(symbol_match[0], m[0])
39+
total = total + int(m[0])
40+
print(total)
41+
42+
gear_ratio = 0
43+
for line_num, l in enumerate(lines):
44+
matches = [m for m in re.finditer(r'\*', l)]
45+
boundary = len(l)
46+
for m in matches:
47+
start = m.start()
48+
end = m.end() - 1
49+
if end < boundary:
50+
end = end + 1
51+
if start > 0:
52+
start = start -1
53+
54+
digit_matches = []
55+
digit_matches = digit_matches + [m for m in re.finditer(r'\d+', l)]
56+
if line_num > 0:
57+
search_str = lines[line_num - 1]
58+
digit_matches = digit_matches + [m for m in re.finditer(r'\d+', search_str)]
59+
if line_num < (line_count - 1):
60+
search_str = lines[line_num + 1]
61+
digit_matches = digit_matches + [m for m in re.finditer(r'\d+', search_str)]
62+
# print(f'symbol {start=},{end=}')
63+
adjacent_numbers=[]
64+
for dm in digit_matches:
65+
dm_start,dm_end = dm.span()
66+
ids = list(range(dm_start, dm_end))
67+
# print(ids)
68+
if start in ids or end in ids:
69+
adjacent_numbers.append(int(dm[0]))
70+
if len(adjacent_numbers) == 2:
71+
gear_ratio = gear_ratio + np.prod(adjacent_numbers)
72+
73+
print(f'{gear_ratio=}')
74+
75+
76+
77+

day4.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/python3
2+
import pandas as pd
3+
import numpy as np
4+
5+
filename="/home/abhi/repos/aoc/inputs/scratchcards_input.txt"
6+
with open(filename) as f:
7+
lines = [line.rstrip() for line in f]
8+
9+
10+
def get_matching_count(l):
11+
_,_,all_numbers = l.partition(":")
12+
winning,_,you_have = all_numbers.partition("|")
13+
all_numbers = winning.strip().replace(' ', ' ').split(' ') + you_have.strip().replace(' ', ' ').split(' ')
14+
complete_count = len(all_numbers) # total count of winning + you_have numbers
15+
get_matching_count = complete_count - len(set(all_numbers))
16+
return get_matching_count
17+
18+
def get_points(num_matching):
19+
if num_matching:
20+
return pow(2, num_matching - 1)
21+
else:
22+
return 0
23+
24+
total_points = 0
25+
for l in lines:
26+
total_points = total_points + get_points(get_matching_count(l))
27+
print(f'{total_points=}')
28+
29+
# part two -> find number of cards which will we end up with
30+
cards_points = pd.DataFrame({
31+
'index':np.arange(len(lines)),
32+
'count':1,
33+
'points':0
34+
})
35+
36+
for i, l in enumerate(lines):
37+
points = cards_points['points'][i] = get_matching_count(l)
38+
count = cards_points['count'][i]
39+
if points == 0:
40+
continue
41+
for j in range(i+1, points+i+1):
42+
cards_points['count'][j] = cards_points['count'][j] + count
43+
print(f"{cards_points['count'].sum()}")

day5.py

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#!/usr/bin/python3
2+
import pandas as pd
3+
import numpy as np
4+
import sys
5+
import re
6+
from multiprocessing import Pool
7+
argc = len(sys.argv)
8+
if argc != 2:
9+
print("Provide filename of the input")
10+
quit()
11+
12+
filename = sys.argv[1]
13+
print(f'input used {filename}')
14+
15+
with open(filename) as f:
16+
lines = [line.rstrip() for line in f]
17+
18+
line_count = len(lines)
19+
boundary = len(lines[0])
20+
21+
seeds_ranges = [int(m) for m in re.findall(r'\d+', lines[0])]
22+
seeds = pd.DataFrame(
23+
{
24+
'source':np.zeros(len(seeds_ranges)//2, dtype=int),
25+
'offset':np.zeros(len(seeds_ranges)//2, dtype=int)
26+
}
27+
)
28+
29+
for i in range(int(len(seeds_ranges)/2)):
30+
# print(seeds_ranges)
31+
seeds.at[i, 'source'] = int(seeds_ranges[i*2])
32+
seeds.at[i, 'offset'] = int(seeds_ranges[(i*2)+1])
33+
# print(seeds)
34+
35+
maps = []
36+
map_started = False
37+
for i, l in enumerate(lines):
38+
if 'map' in l:
39+
map_started = True
40+
index = 0
41+
d2s = pd.DataFrame({
42+
'destination':np.empty( 1, dtype=int),
43+
'source':np.empty( 1, dtype=int),
44+
'offset':np.empty( 1, dtype=int)
45+
})
46+
continue
47+
if (len(l)==0 or i == line_count -1) and map_started:
48+
map_started = False
49+
maps.append(d2s)
50+
# print(d2s)
51+
52+
if map_started:
53+
numbers = [int(m) for m in re.findall(r'\d+', l)]
54+
d2s.at[index, 'destination'] = numbers[0]
55+
d2s.at[index, 'source'] = numbers[1]
56+
d2s.at[index, 'offset'] = numbers[2]
57+
index = index + 1
58+
59+
def get_destination(df : pd.DataFrame, s):
60+
for _, row in df.iterrows():
61+
start = row['source']
62+
end = start + row['offset']
63+
if s >= start and s<= end:
64+
offset = s - start
65+
offset_remaining = end -s
66+
return row['destination']+offset , offset_remaining
67+
return s, 0
68+
69+
locations = []
70+
new_seeds = []
71+
def get_seeds(seed):
72+
start = seed[0]
73+
end = start + seed[1]
74+
return [s for s in range(start, end + 1)]
75+
76+
def get_mini_loc(seed):
77+
print(f'working on {seed[0]=}')
78+
min_loc = 10000000000
79+
for source in get_seeds(seed):
80+
# print(source, end= ' ')
81+
for m in maps:
82+
dest, _ = get_destination(m, source)
83+
source = dest
84+
min_loc = min(dest, min_loc)
85+
# print(dest, min_loc)
86+
print(f"{min_loc=} for {seed[0]=}")
87+
return min_loc
88+
89+
def split_ranges():
90+
seeds_list=[]
91+
for _, s in seeds.iterrows():
92+
start = s['source']
93+
offset = s['offset']
94+
range_size = 10000
95+
num_ranges = offset // range_size
96+
last_offset = offset % range_size
97+
for i in range(num_ranges):
98+
seeds_list.append((start + i*range_size, range_size))
99+
seeds_list.append((start + num_ranges*range_size, last_offset))
100+
return seeds_list
101+
102+
with Pool(processes=6) as pool:
103+
seeds_list = split_ranges()
104+
locs = pool.map(get_mini_loc, seeds_list)
105+
print(min(locs))

day6.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/python3
2+
import pandas as pd
3+
import numpy as np
4+
import sys
5+
6+
with open(sys.argv[1]) as f:
7+
lines = [line.rstrip() for line in f]
8+
9+
time = [ t.strip() for t in lines[0].split()][1:]
10+
distance = [ t.strip() for t in lines[1].split()][1:]
11+
12+
time = [ int(t) for t in time]
13+
distance = [ int(t) for t in distance]
14+
15+
total_ways = 1
16+
for t, d in zip(time, distance):
17+
stop_val = 0
18+
unpossible_ways = 0
19+
possible_ways = t - 1
20+
for i in range(1, t//2):
21+
if ((t-i) * i) > d:
22+
break
23+
unpossible_ways += 2
24+
ways = possible_ways - unpossible_ways
25+
print(ways)
26+
total_ways *=ways
27+
28+
print(f'{total_ways=}')
29+

0 commit comments

Comments
 (0)