|
1 | | -# def measure(bucket_one, bucket_two, goal, start_bucket): |
2 | | -# pass |
3 | | -''' |
4 | | - This solution implements a breadth-first search of the graph |
5 | | - of possible valid states for the two buckets until it reaches a state |
6 | | - in which one of the two buckets contains the goal amount |
7 | | -''' |
8 | | - |
9 | | - |
10 | 1 | def measure(bucket_one, bucket_two, goal, start_bucket): |
11 | | - sizes = [bucket_one, bucket_two] |
12 | | - goal_index = 0 if start_bucket == 'one' else 1 |
13 | | - |
14 | | - def empty(buckets, idx): |
15 | | - return [0, buckets[1]] if idx == 0 else [buckets[0], 0] |
16 | | - |
17 | | - def fill(buckets, idx): |
18 | | - return [sizes[0], buckets[1]] if idx == 0 else [buckets[0], sizes[1]] |
19 | | - |
20 | | - def consolidate(buckets, idx): |
21 | | - amount = min(buckets[1 - idx], sizes[idx] - buckets[idx]) |
22 | | - target = buckets[idx] + amount |
23 | | - source = buckets[1 - idx] - amount |
24 | | - return [target, source] if idx == 0 else [source, target] |
25 | | - |
26 | | - def bucket_str(buckets): |
27 | | - return f'{buckets[0]},{buckets[1]}' |
28 | | - |
29 | | - invalid = [0, 0] |
30 | | - invalid[1 - goal_index] = sizes[1 - goal_index] |
31 | | - invalid_string = bucket_str(invalid) |
32 | | - buckets = [0, 0] |
33 | | - buckets[goal_index] = sizes[goal_index] |
34 | | - to_visit = [] |
35 | | - visited = set() |
36 | | - count = 1 |
37 | | - while goal not in buckets: |
38 | | - key = bucket_str(buckets) |
39 | | - if key != invalid_string and key not in visited: |
40 | | - visited.add(key) |
41 | | - number_count = count + 1 |
42 | | - for idx in range(2): |
43 | | - if buckets[idx] != 0: |
44 | | - to_visit.append((empty(buckets, idx), number_count)) |
45 | | - if buckets[idx] != sizes[idx]: |
46 | | - to_visit.append((fill(buckets, idx), number_count)) |
47 | | - to_visit.append((consolidate(buckets, idx), number_count)) |
48 | | - if not any(to_visit): |
49 | | - raise ValueError('No more moves!') |
50 | | - buckets, count = to_visit.pop(0) |
51 | | - |
52 | | - goal_index = buckets.index(goal) |
53 | | - goal_bucket = ['one', 'two'][goal_index] |
54 | | - other_bucket = buckets[1 - goal_index] |
55 | | - return (count, goal_bucket, other_bucket) |
| 2 | + pass |
0 commit comments