+/foobar

google programming puzzles

git clone https://git.julia.blue/+/foobar

Joseph RyanI made it2e1d345

master
2.2 KiB76 linesraw
1from PIL import Image
2
3from operator import mul
4from fractions import gcd
5
6vec_mul = lambda a, b: tuple(map(lambda x: mul(*x), zip(a, b)))
7
8vec_scale = lambda a, b: vec_mul(a, (b, b))
9
10vec_add = lambda a, b: tuple(map(sum, zip(a, b)))
11
12vec_sub = lambda a, b: vec_add(a, vec_scale(b, -1))
13
14vec_magnitude = lambda a: sum(map(lambda x: x ** 2, a)) ** .5
15
16
17def get_mirror(pos, coords, dimensions):
18    temp = [pos[i] if coords[i] % 2 == 0 else dimensions[i] - pos[i] for i in range(2)]
19    return vec_add(temp, vec_mul(coords, dimensions))
20
21
22def vec_reduce(a):
23    if 0 in a:
24        return tuple(map(lambda x: x / abs(x) if x > 0 else 0, a))
25    return tuple(map(lambda x: x / gcd(*map(abs, a)), a))
26
27
28def answer(dimensions, us, target, distance):
29    us , target = target, us
30    img = Image.new("RGB", (400,400))
31    pix = img.load()
32
33    selfs = {}
34    hits = set([])
35    possible = [distance/dimensions[i] + 1 for i in range(2)]
36    for x in range(-possible[0], possible[0] + 1):
37        for y in range(-possible[1], possible[1] + 1):
38            current = vec_sub(get_mirror(us, (x, y), dimensions), us)
39            d = vec_magnitude(current)
40            current = vec_reduce(current)
41            if d < distance:
42                if current in selfs and selfs[current] < d:
43                    continue
44                selfs[current] = d
45
46    pix[us[0] + 200, us[1] + 200] = 255, 0, 0
47
48    for x in range(-possible[0], possible[0] + 1):
49        for y in range(-possible[1], possible[1] + 1):
50            current = vec_sub(get_mirror(target, (x, y), dimensions), us)
51            blah = vec_add(current, us)
52            d = vec_magnitude(current)
53            current = vec_reduce(current)
54            if d < distance:
55                if current in selfs and selfs[current] < d:
56                    continue
57                if current not in hits:
58                    pix[tuple([blah[i] + 200 for i in range(2)])] = 255, 255, 255
59                hits.add(current)
60
61    img.show()
62
63    return len(hits)
64
65
66dimensions = [3, 3]
67your_position = [1, 1]
68guard_position = [2, 1]
69distance = 195
70
71# dimensions = [300, 275]
72# your_position = [150, 150]
73# guard_position = [185, 100]
74# distance = 5000
75
76print answer(dimensions, your_position, guard_position, distance)