Skip to content

Commit 7cb42bc

Browse files
committed
Add solutions
1 parent b4990e9 commit 7cb42bc

File tree

10 files changed

+339
-5
lines changed

10 files changed

+339
-5
lines changed

dailycodingproblem/day_7.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from collections import deque
2+
from random import randint
3+
4+
5+
def generate_input(width):
6+
inp = str(randint(1, 9))
7+
for _ in range(width - 1):
8+
if inp[-1] in ['1', '2']:
9+
inp += str(randint(0, 9))
10+
else:
11+
inp += str(randint(1, 9))
12+
return inp
13+
14+
15+
def encode(string):
16+
return ''.join([str(ord(c) - 96) for c in string])
17+
18+
19+
def decode(string):
20+
solutions = []
21+
queue = deque([[[], string]])
22+
while queue:
23+
path, rem = queue.popleft()
24+
if rem:
25+
if 10 <= int(rem[:2]) <= 26:
26+
if len(rem[:3]) == 3 and int(rem[:3]) % 10 == 0:
27+
queue.append([path + [int(rem[0])], rem[1:]])
28+
continue
29+
queue.append([path + [int(rem[:2])], rem[2:]])
30+
if int(rem[:2]) % 10 == 0:
31+
continue
32+
queue.append([path + [int(rem[0])], rem[1:]])
33+
else:
34+
solutions.append(path)
35+
return solutions
36+
37+
38+
def main():
39+
# inp = generate_input(randint(5, 15))
40+
inp = encode('dailycoding')
41+
42+
sol = decode(inp)
43+
print('"{}" has {} way{} of being decoded.'.format(inp, len(sol), '' if len(sol) == 1 else 's'))
44+
decodes = [''.join([chr(o + 96) for o in s]) for s in sol]
45+
print(decodes)
46+
assert all([char.isalpha() for char in ''.join(decodes)])
47+
48+
49+
if __name__ == '__main__':
50+
main()

projecteuler/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,8 @@
7878
| 74 | Digit factorial chains | :small_blue_diamond: [Python](../projecteuler/python/p074.py)
7979
| 75 | Singular integer right triangles | :small_blue_diamond: [Python](../projecteuler/python/p075.py)
8080
| 76 | Counting summations | :small_blue_diamond: [Python](../projecteuler/python/p076.py)
81+
| 81 | Path sum: two ways | :small_blue_diamond: [Python](../projecteuler/python/p081.py)
82+
| 87 | Prime power triples | :small_blue_diamond: [Python](../projecteuler/python/p087.py)
83+
| 92 | Square digit chains | :small_orange_diamond: [Python](../projecteuler/python/p092.py)
84+
| 97 | Large non-Mersenne prime | :small_blue_diamond: [Python](../projecteuler/python/p097.py)
85+
| 206 | Concealed square | :small_blue_diamond: [Python](../projecteuler/python/p206.py)

projecteuler/inputs/p081.in

Lines changed: 80 additions & 0 deletions
Large diffs are not rendered by default.

projecteuler/python/p081.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# https://projecteuler.net/problem=81
2+
3+
4+
def load_file(file):
5+
with open(file) as f:
6+
data = f.read()
7+
return data
8+
9+
10+
def backtrack(start, goal, matrix):
11+
def get_moves(x, y, height, width):
12+
ACTIONS = {
13+
'U': (x - 1, y),
14+
'L': (x, y - 1),
15+
}
16+
moves = []
17+
for (nx, ny) in ACTIONS.values():
18+
if 0 <= nx <= height and 0 <= ny <= width:
19+
moves.append((nx, ny))
20+
return moves
21+
22+
def get_best_move(matrix, moves):
23+
children = [(matrix[nx][ny], (nx, ny)) for (nx, ny) in moves]
24+
return sorted(children)[0][1]
25+
26+
def get_values(path):
27+
return [matrix[x][y] for (x, y) in path]
28+
29+
gx, gy = goal
30+
height, width = gx + 1, gy + 1
31+
32+
path = [(gx, gy)]
33+
while path[-1] != start:
34+
ox, oy = path[-1]
35+
move = get_best_move(matrix, get_moves(ox, oy, height, width))
36+
path.append(move)
37+
38+
return sum(get_values(path)), path
39+
40+
41+
def djikstra(matrix):
42+
out = matrix
43+
width, height = len(matrix), len(matrix[-1])
44+
for r in range(height):
45+
for c in range(width):
46+
if r == 0 and c == 0:
47+
out[r][c] = matrix[r][c]
48+
elif r == 0:
49+
out[r][c] = matrix[r][c] + out[r][c - 1]
50+
elif c == 0:
51+
out[r][c] = matrix[r][c] + out[r - 1][c]
52+
else:
53+
out[r][c] = matrix[r][c] + min([out[r][c - 1], out[r - 1][c]])
54+
return out[-1][-1]
55+
56+
57+
def main():
58+
inp = load_file('inputs/p081.in')
59+
inp = [list(map(int, line.split(','))) for line in inp.splitlines()]
60+
61+
score = djikstra(inp)
62+
print(score)
63+
print('CORRECT ANSWER:', score == 427337)
64+
65+
66+
if __name__ == '__main__':
67+
main()

projecteuler/python/p087.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# https://projecteuler.net/problem=87
2+
3+
from itertools import product
4+
5+
6+
def sieve(limit):
7+
sieve = {n: True for n in range(2, limit + 1)}
8+
for n in range(2, limit + 1):
9+
if sieve[n]:
10+
for a in range(2, limit // n + 1):
11+
sieve[n * a] = False
12+
return [k for k, v in sieve.items() if v]
13+
14+
15+
def main():
16+
limit = 50 * 10 ** 6
17+
powers = {2: {}, 3: {}, 4: {}}
18+
seen = set()
19+
for a, b, c in product(sieve(7072), sieve(369), sieve(85)):
20+
if a not in powers[2]:
21+
powers[2][a] = a ** 2
22+
if b not in powers[3]:
23+
powers[3][b] = b ** 3
24+
if c not in powers[4]:
25+
powers[4][c] = c ** 4
26+
num = powers[2][a] + powers[3][b] + powers[4][c]
27+
if num > limit:
28+
continue
29+
if num not in seen:
30+
seen.add(num)
31+
print(len(seen))
32+
33+
34+
if __name__ == '__main__':
35+
main()

projecteuler/python/p092.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# https://projecteuler.net/problem=92
2+
3+
from collections import Counter
4+
from functools import lru_cache, reduce
5+
from math import factorial as f
6+
from operator import mul
7+
8+
9+
@lru_cache()
10+
def ss_digits(num):
11+
return sum(map(lambda x: pow(int(x), 2), str(num)))
12+
13+
14+
def multinomial(num, width=None):
15+
def _get_digits(num):
16+
return map(int, str(num))
17+
18+
if width is None:
19+
width = len(str(num))
20+
c = Counter(_get_digits(num))
21+
return f(width) // reduce(mul, [f(v) for v in c.values()])
22+
23+
24+
def generate_multisets(width):
25+
def _ltoi(seq):
26+
return int(''.join([str(d) for d in seq]))
27+
28+
num = [0] * width
29+
ptr = width - 1
30+
while True:
31+
if ptr == 0 and num[ptr] == 9:
32+
break
33+
if ptr == width - 1 and num[ptr] < 9:
34+
num[ptr] += 1
35+
yield _ltoi(num)
36+
elif num[ptr] == 9:
37+
ptr -= 1
38+
else:
39+
num[ptr] += 1
40+
for i in range(ptr + 1, width):
41+
num[i] = num[ptr]
42+
ptr = width - 1
43+
yield _ltoi(num)
44+
45+
46+
def main():
47+
limit = 7
48+
49+
counter = 0
50+
cache = {}
51+
for i in generate_multisets(limit):
52+
num = i
53+
while num not in (1, 89):
54+
if num not in cache:
55+
cache[num] = ss_digits(num)
56+
num = cache[num]
57+
if num == 89:
58+
counter += multinomial(i, limit)
59+
60+
print(counter)
61+
print('CORRECT ANSWER:', counter == 8581146)
62+
63+
64+
if __name__ == '__main__':
65+
main()

projecteuler/python/p097.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# https://projecteuler.net/problem=97
2+
3+
def main():
4+
num = 1
5+
for _ in range(7830457):
6+
num = (num * 2) % (10 ** 10)
7+
num = 28433 * num + 1
8+
print(str(num)[-10:])
9+
10+
11+
if __name__ == '__main__':
12+
main()

projecteuler/python/p206.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# https://projecteuler.net/problem=206
2+
3+
def match(num):
4+
return all([str(num)[i * 2] == str(i + 1) for i in range(9)])
5+
6+
7+
def main():
8+
start = int(19293949596979899 ** 0.5) + 1
9+
for n in range(start, 0, -2):
10+
if match(n ** 2):
11+
print(n * 10)
12+
break
13+
14+
15+
if __name__ == '__main__':
16+
main()

uvaonlinejudge/python/p103.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Stacking Boxes
22

3+
from collections import deque
4+
5+
36
def load_file(file):
47
with open(file) as f:
58
data = f.read()
@@ -38,7 +41,7 @@ def isfit(boxa, boxb):
3841
def find_path(boxes):
3942
best = []
4043
boxes = set(boxes)
41-
stack = [[[box], boxes - set(box)] for box in sorted(boxes, reverse=True)]
44+
stack = deque([[[box], boxes - set(box)] for box in sorted(boxes, reverse=True)])
4245
while stack:
4346
path, remaining = stack.pop()
4447
if len(path) >= len(best):

uvaonlinejudge/python/p104.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Arbitrage
22

3+
from collections import deque
34
from functools import reduce
45
from operator import mul
56

@@ -47,18 +48,18 @@ def convert(table, seq):
4748

4849
def find_arbitrage(table, starting=0):
4950
denoms = set([d for d, _ in enumerate(table)])
50-
queue = [[starting, starting]]
51+
stack = deque([[starting, starting]])
5152
best = ([], 1)
52-
while queue:
53-
path = queue.pop()
53+
while stack:
54+
path = stack.pop()
5455
if len(path) >= len(denoms):
5556
continue
5657
for child in denoms - set([path[-2]]):
5758
new = path[:-1] + [child] + path[-1:]
5859
cash = convert(table, new)
5960
if cash >= best[1]:
6061
best = (new, cash)
61-
queue.append(new)
62+
stack.append(new)
6263
if best[0]:
6364
return [i + 1 for i in best[0]]
6465
return None

0 commit comments

Comments
 (0)