|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import random |
| 3 | +import math |
| 4 | +import itertools |
| 5 | + |
| 6 | +from concurrent.futures.thread import ThreadPoolExecutor |
| 7 | + |
| 8 | +""" |
| 9 | +Return the number of possible combinations of three kind of stops during a trip, before |
| 10 | +a previous combination must be repeated. |
| 11 | +
|
| 12 | +Each list represent the distance from the trip origin where the stop is placed. |
| 13 | +Each list can be disordered. |
| 14 | +
|
| 15 | +Example: |
| 16 | +
|
| 17 | + A = [29, 50] |
| 18 | + B = [61, 37] |
| 19 | + C = [37, 70] |
| 20 | +
|
| 21 | +(29, 37, 70), (29, 61, 70), (50, 61, 70) |
| 22 | +
|
| 23 | +Should return 3. |
| 24 | +""" |
| 25 | + |
| 26 | + |
| 27 | +def solution_v1(A, B, C): |
| 28 | + |
| 29 | + def countt(it): |
| 30 | + itt = filter(lambda t: t[0] < t[1] and t[1] < t[2], it[0]) |
| 31 | + return sum(1 for _ in itt) |
| 32 | + |
| 33 | + N = len(A) |
| 34 | + NN = N * N * N |
| 35 | + |
| 36 | + prod = itertools.product(A, B, C) |
| 37 | + t = ThreadPoolExecutor(4) |
| 38 | + chunk = math.ceil(NN / 4) |
| 39 | + |
| 40 | + f1 = t.submit(countt, (itertools.islice(prod, chunk),)) |
| 41 | + f2 = t.submit(countt, (itertools.islice(prod, chunk),)) |
| 42 | + f3 = t.submit(countt, (itertools.islice(prod, chunk),)) |
| 43 | + f4 = t.submit(countt, (itertools.islice(prod, chunk),)) |
| 44 | + count = f1.result() + f2.result() + f3.result() + f4.result() |
| 45 | + return count if count < 1000000000 else -1 |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + |
| 50 | + A = [29, 50] |
| 51 | + B = [61, 37] |
| 52 | + C = [37, 70] |
| 53 | + |
| 54 | + ans = solution_v1(A, B, C) |
| 55 | + assert(ans == 3) |
| 56 | + |
| 57 | + A = [5] |
| 58 | + B = [5] |
| 59 | + C = [5] |
| 60 | + |
| 61 | + ans = solution_v1(A, B, C) |
| 62 | + assert(ans == 0) |
| 63 | + |
| 64 | + A = [5] |
| 65 | + B = [6] |
| 66 | + C = [7] |
| 67 | + |
| 68 | + ans = solution_v1(A, B, C) |
| 69 | + assert(ans == 1) |
| 70 | + |
| 71 | + A = [5, 6] |
| 72 | + B = [5, 7] |
| 73 | + C = [5, 8] |
| 74 | + |
| 75 | + ans = solution_v1(A, B, C) |
| 76 | + assert(ans == 2) |
| 77 | + |
| 78 | + N = 100 |
| 79 | + A = [random.randint(1, 500) for x in range(N)] |
| 80 | + B = [random.randint(501, 1000) for x in range(N)] |
| 81 | + C = [random.randint(1001, 1500) for x in range(N)] |
| 82 | + ans = solution_v1(A, B, C) |
| 83 | + assert(ans == N * N * N) |
| 84 | + |
| 85 | + N = 100 |
| 86 | + A = [random.randint(1, 500) for x in range(N)] |
| 87 | + B = [random.randint(501, 1000) for x in range(N)] |
| 88 | + C = [x for x in range(N - 1)] + [1001] |
| 89 | + ans = solution_v1(A, B, C) |
| 90 | + assert(ans == N * N * 1) |
0 commit comments