Last active
July 8, 2016 02:17
-
-
Save eungju/36794aa14053a381592041574dd47b44 to your computer and use it in GitHub Desktop.
Ping Pong
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def contains_digit(n, k): | |
if n == 0: | |
return False | |
return True if n % 10 == k else contains_digit(n // 10, k) | |
def ping_pong(n, i=1, d=1, r=0): | |
if i > n: | |
return r | |
turn = i % 7 == 0 or contains_digit(i, 7) | |
return ping_pong(n, i + 1, -d if turn else d, r + d) | |
assert ping_pong(1) == 1 | |
assert ping_pong(8) == 6 | |
assert ping_pong(22) == 0 | |
assert ping_pong(68) == 2 | |
assert ping_pong(100) == 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
def contains_digit(n, k): | |
if n == 0: | |
return False | |
if n % 10 == k: | |
return True | |
else: | |
return contains_digit(n // 10, k) | |
def scan(func, iterable, initial=None): | |
acc = next(iterable) if initial is None else initial | |
yield acc | |
for e in iterable: | |
acc = func(acc, e) | |
yield acc | |
def last(iterable): | |
return reduce(lambda acc, e: e, iterable) | |
def pingpong(n): | |
k = 7 | |
turns = map(lambda i: i % k == 0 or contains_digit(i, k), range(1, n)) | |
directions = scan(lambda direction, turn: -direction if turn else direction, turns, 1) | |
points = scan(lambda point, direction: point + direction, directions) | |
return last(points) | |
print(pingpong(1)) | |
print(pingpong(8)) | |
print(pingpong(22)) | |
print(pingpong(68)) | |
print(pingpong(100)) | |
print(pingpong(100000)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PingPongTest { | |
fun containsDigit(n: Int, k: Int): Boolean = if (n == 0) false else if (n % 10 == k) true else containsDigit(n / 10, k) | |
fun pingPong(n: Int) = Observable.range(1, n - 1) | |
.map { it % 7 == 0 || containsDigit(it, 7) } | |
.scan(1, { direction, turn -> direction * if (turn) -1 else 1 }) | |
.scan { acc, direction -> acc + direction } | |
.last() | |
.toBlocking() | |
.single() | |
@Test fun examples() { | |
assertTrue(pingPong(8) == 6) | |
assertTrue(pingPong(22) == 0) | |
assertTrue(pingPong(68) == 2) | |
assertTrue(pingPong(100) == 2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment