├── bunny_prisoner_locating ├── solution.py └── readme.md ├── en_route_salute ├── solution.py └── readme.md ├── find_the_access_codes ├── solution.py └── readme.md ├── minion_labor_shifts ├── solution.py └── readme.md ├── re_id ├── solution.py └── readme.md ├── decode.py ├── bomb_baby ├── solution.py └── readme.md ├── dodge_the_lasers ├── solution.py └── readme.md ├── queue_to_do ├── solution.py └── readme.md ├── the_grandest_staircase_of_them_all ├── solution.py └── readme.md ├── lovely_lucky_lambs ├── solution.py └── readme.md ├── ion_flux_relabeling ├── solution.py └── readme.md ├── prepare_the_bunnies_escape ├── solution.py └── readme.md ├── bringing_a_gun_to_a_guard_fight ├── solution.py └── readme.md ├── distract_the_guards ├── solution.py └── readme.md ├── readme.md └── journal.md /bunny_prisoner_locating/solution.py: -------------------------------------------------------------------------------- 1 | def answer(x, y): 2 | layer = x + y - 1 3 | pre_total = layer * (layer - 1) // 2 4 | return str(pre_total + x) 5 | 6 | 7 | print(answer(1, 1) == "1") 8 | print(answer(3, 2) == "9") 9 | print(answer(2, 3) == "8") 10 | print(answer(5, 10) == "96") 11 | -------------------------------------------------------------------------------- /en_route_salute/solution.py: -------------------------------------------------------------------------------- 1 | def answer(s): 2 | ans = count = 0 3 | for ch in s: 4 | if ch == '>': 5 | count += 1 6 | elif ch == '<': 7 | ans += count 8 | return ans << 1 9 | 10 | print(answer("--->-><-><-->-")) 11 | print(answer(">----<")) 12 | print(answer("<<>><")) 13 | -------------------------------------------------------------------------------- /find_the_access_codes/solution.py: -------------------------------------------------------------------------------- 1 | def answer(l): 2 | factor = [[]] * len(l) 3 | for i in range(1, len(l)): 4 | factor[i] = [j for j in range(i) if l[i] % l[j] == 0] 5 | count = 0 6 | for i in range(2, len(l)): 7 | count += sum(len(factor[j]) for j in factor[i]) 8 | return count 9 | 10 | 11 | print(answer([1, 1, 1])) 12 | print(answer([1, 2, 3, 4, 5, 6])) 13 | -------------------------------------------------------------------------------- /minion_labor_shifts/solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def answer(data, n): 5 | if n == 0: 6 | return [] 7 | if len(data) < n: 8 | return data 9 | c = Counter(data) 10 | return [d for d in data if c[d] <= n] 11 | 12 | 13 | print(answer([1, 2, 3], 0) == []) 14 | print(answer([1, 2, 2, 3, 3, 3, 4, 5, 5], 1) == [1, 4]) 15 | print(answer([1, 2, 3], 6) == [1, 2, 3]) 16 | -------------------------------------------------------------------------------- /re_id/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generate prime table and then join them together into a single string. 3 | """ 4 | 5 | 6 | def answer(n): 7 | table = [True] * 20220 8 | table[0] = table[1] = False 9 | for i in range(2, 20220): 10 | if table[i]: 11 | for j in range(i + i, 20220, i): 12 | table[j] = False 13 | prime_str = "".join([str(i) for i in range(1, 20220) if table[i]]) 14 | return prime_str[n: n + 5] 15 | 16 | if __name__ == "__main__": 17 | print(answer(5000)) 18 | -------------------------------------------------------------------------------- /decode.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | # google account 4 | key = 'seudotw' 5 | 6 | # encypted string 7 | string = """ 8 | KEIGEQw3MiAWUkRVdHA0FxAFG3N7c0IWCwM4MjICAAFIdG1zQhAXGzEyPgARQ0N0cDYDEwsdICR0 RU9ESD05MBcQAAY2OzZCWURINTQ7DBASCjkyPRFSRFV0cCYLGQsMPzI3QllESCY2MQccEBxzd2lF UhcOMjJ0SVVDCTs4dEVPREgjPj1EUhk= 9 | """ 10 | 11 | 12 | def decode(): 13 | result = [chr(ord(char) ^ ord(key[idx % len(key)])) 14 | for idx, char in enumerate(base64.b64decode(string))] 15 | return ''.join(result) 16 | 17 | if __name__ == "__main__": 18 | print(decode()) 19 | -------------------------------------------------------------------------------- /bomb_baby/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose M > F, to hit (M, F), last state must be (M-F, F). 3 | 4 | We can use Euclidean algorithm to calcualte the generations 5 | from (M, F) down to (1, 1) 6 | 7 | A simple case: (1, 1)-(2, 1)-(3, 1)-(3, 4)-(7, 4) 8 | Impossible Case: gcd(M, F) != 1 9 | """ 10 | 11 | 12 | def answer(M, F): 13 | x, y = int(M), int(F) 14 | count = 0 15 | while y >= 1: 16 | if x < y: 17 | x, y = y, x 18 | x, y, q = y, x % y, x // y 19 | count += q 20 | return str(count - 1) if x == 1 else "impossible" 21 | 22 | 23 | print(answer("4", "7")) 24 | print(answer("2", "1")) 25 | print(answer("3", "6")) 26 | -------------------------------------------------------------------------------- /dodge_the_lasers/solution.py: -------------------------------------------------------------------------------- 1 | # beatty sequence sum 2 | # https://math.stackexchange.com/questions/2052179/how-to-find-sum-i-1n-left-lfloor-i-sqrt2-right-rfloor-a001951-a-beatty-s 3 | from decimal import Decimal, getcontext 4 | getcontext().prec = 101 5 | sqrt2m1 = Decimal(2).sqrt() - 1 6 | 7 | 8 | def answer(str_n): 9 | n = long(str_n) 10 | 11 | def s(n): 12 | if n == 1: 13 | return 1 14 | if n < 1: 15 | return 0 16 | n1 = long(sqrt2m1 * n) 17 | return n * n1 + n * (n + 1) // 2 - n1 * (n1 + 1) // 2 - s(n1) 18 | 19 | return str(s(n)) 20 | 21 | 22 | if __name__ == "__main__": 23 | print("4208", answer("77")) 24 | print("19", answer("5")) 25 | -------------------------------------------------------------------------------- /queue_to_do/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Use bulk_xor to speed up xor calculate. 3 | Let f(x) = 1 ^ 2 ^ 3 ^ ... ^ x 4 | Then, xor all integers in the range from m to n = f(n) ^ f(m-1) 5 | """ 6 | 7 | 8 | def answer(start, length): 9 | 10 | def bulk_xor(m, n): 11 | # f(x) = 1 ^ 2 ^ 3 ^ ... ^ x 12 | # bulk_xor(m, n) = m ^ m+1 ^ m+2 ... ^ n = f(n) ^ f(m-1) 13 | m -= 1 14 | f_m = [m, 1, m + 1, 0][m % 4] 15 | f_n = [n, 1, n + 1, 0][n % 4] 16 | return f_m ^ f_n 17 | 18 | xor = 0 19 | for i in range(length): 20 | xor ^= bulk_xor(start, start + length - i - 1) 21 | start += length 22 | 23 | return xor 24 | 25 | 26 | print(answer(0, 3)) 27 | print(answer(17, 4)) 28 | -------------------------------------------------------------------------------- /the_grandest_staircase_of_them_all/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | The problem can be transfered to Knapsack problem: 3 | 4 | 1. there are n-1 steps (not n, because we need at least 2 steps) 5 | 2. j bricks is needed to build the j-th steps. 6 | 3. for each step, we decide whether to build or not to build it 7 | 8 | dp[i][j] = the combination of using i bricks to build 1~j steps 9 | dp[i][j] = dp[i][j-1] (not build) + dp[i-j][j-1] (build) 10 | """ 11 | 12 | 13 | def answer(n): 14 | dp = [[0] * n for _ in range(n + 1)] 15 | dp[0][0] = dp[1][1] = dp[2][2] = 1 16 | 17 | for j in range(1, n): 18 | for i in range(n + 1): 19 | dp[i][j] = dp[i][j - 1] 20 | if i >= j: 21 | dp[i][j] += dp[i - j][j - 1] 22 | 23 | return dp[-1][-1] 24 | 25 | for i in range(3, 201): 26 | print(i, answer(i)) 27 | -------------------------------------------------------------------------------- /lovely_lucky_lambs/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Max: #(fib number list) 3 | 4 | Min: #(power of 2 list) 5 | last element a[n] can be any number between (a[n-1] + a[n-2], a[n-1] * 2) 6 | """ 7 | 8 | 9 | def answer(total_lambs): 10 | 11 | # Power of 2 list 12 | min_v = -1 13 | n = total_lambs + 1 14 | while n: 15 | n >>= 1 16 | min_v += 1 17 | # last element can smaller than 2 ** min_v 18 | # but still need to follow rules 19 | x = 1 << min_v 20 | if (x + x // 2 + x // 4 - 1) <= total_lambs: 21 | min_v += 1 22 | 23 | # Fib list 24 | max_v = 1 25 | x, y, n = 1, 1, total_lambs - 1 26 | while n > 0: 27 | x, y = y, x + y 28 | n -= y 29 | max_v += 1 30 | 31 | return max_v - min_v 32 | 33 | if __name__ == "__main__": 34 | for i in range(15): 35 | print(i, answer(i)) 36 | -------------------------------------------------------------------------------- /ion_flux_relabeling/solution.py: -------------------------------------------------------------------------------- 1 | def answer(h, q): 2 | ans = [-1] * len(q) 3 | max_v = (1 << h) - 1 4 | 5 | def getPid(h, target, bias): 6 | max_v = (1 << h) - 1 7 | max_hv = max_v // 2 8 | # target == left node 9 | if target == max_hv + bias: 10 | return max_v + bias 11 | # target == right node 12 | elif target == (max_hv << 1) + bias: 13 | return max_v + bias 14 | # target in left subtree 15 | elif target < max_hv + bias: 16 | return getPid(h - 1, target, bias) 17 | # target in right subtree 18 | else: 19 | return getPid(h - 1, target, bias + max_hv) 20 | 21 | for idx, elem in enumerate(q): 22 | if elem < max_v: 23 | ans[idx] = getPid(h, elem, 0) 24 | 25 | return ans 26 | 27 | print(answer(2, [1, 2, 3, 4, 5, 6, 7, 8, 9])) 28 | print(answer(3, [7, 3, 5, 1])) 29 | print(answer(5, [19, 14, 28])) 30 | -------------------------------------------------------------------------------- /re_id/readme.md: -------------------------------------------------------------------------------- 1 | ## Re-ID 2 | 3 | There's some unrest in the minion ranks: minions with ID numbers like "1", "42", and other "good" numbers have been lording it over the poor minions who are stuck with more boring IDs. To quell the unrest, Commander Lambda has tasked you with reassigning everyone new, random IDs based on her Completely Foolproof Scheme. 4 | 5 | She's concatenated the prime numbers in a single long string: "2357111317192329...". Now every minion must draw a number from a hat. That number is the starting index in that string of primes, and the minion's new ID number will be the next five digits in the string. So if a minion draws "3", their ID number will be "71113". 6 | 7 | Help the Commander assign these IDs by writing a function answer(n) which takes in the starting index n of Lambda's string of all primes, and returns the next five digits in the string. Commander Lambda has a lot of minions, so the value of n will always be between 0 and 10000. 8 | 9 | ### Test cases 10 | 11 | Inputs: 12 | 13 | ``` 14 | (int) n = 0 15 | ``` 16 | 17 | Output: 18 | 19 | ``` 20 | (string) "23571" 21 | ``` 22 | 23 | Inputs: 24 | 25 | ``` 26 | (int) n = 3 27 | ``` 28 | 29 | Output: 30 | 31 | ``` 32 | (string) "71113" 33 | ``` 34 | 35 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 36 | 37 | 38 | -------------------------------------------------------------------------------- /bunny_prisoner_locating/readme.md: -------------------------------------------------------------------------------- 1 | ## Bunny Prisoner Locating 2 | 3 | Keeping track of Commander Lambda's many bunny prisoners is starting to get tricky. You've been tasked with writing a program to match bunny prisoner IDs to cell locations. 4 | 5 | The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given numerical IDs starting from the corner, as follows: 6 | 7 | ``` 8 | | 7 9 | | 4 8 10 | | 2 5 9 11 | | 1 3 6 10 12 | ``` 13 | 14 | Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground. 15 | 16 | For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners). 17 | 18 | Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a string representation of the number. 19 | 20 | ### Test cases 21 | 22 | Inputs: 23 | 24 | ``` 25 | (int) x = 3 26 | (int) y = 2 27 | ``` 28 | 29 | Output: 30 | 31 | ``` 32 | (string) "9" 33 | ``` 34 | 35 | Inputs: 36 | 37 | ``` 38 | (int) x = 5 39 | (int) y = 10 40 | ``` 41 | 42 | Output: 43 | 44 | ``` 45 | (string) "96" 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /find_the_access_codes/readme.md: -------------------------------------------------------------------------------- 1 | ## Find the Access Codes 2 | 3 | In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that includes the locks' access codes, but only she knows how to figure out which of several lists contains the access codes. You need to find a way to determine which list contains the access codes once you're ready to go in. 4 | 5 | Fortunately, now that you're Commander Lambda's personal assistant, she's confided to you that she made all the access codes "lucky triples" in order to help her better find them in the lists. A "lucky triple" is a tuple (x, y, z) where x divides y and y divides z, such as (1, 2, 4). With that information, you can figure out which list contains the number of access codes that matches the number of locks on the door when you're ready to go in (for example, if there's 5 passcodes, you'd need to find a list with 5 "lucky triple" access codes). 6 | 7 | Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (lst[i], lst[j], lst[k]) where i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within a signed 32-bit integer. Some of the lists are purposely generated without any access codes to throw off spies, so if no triples are found, return 0. 8 | 9 | For example, [1, 2, 3, 4, 5, 6] has the triples: [1, 2, 4], [1, 2, 6], [1, 3, 6], making the answer 3 total. 10 | 11 | ### Test cases 12 | 13 | Inputs: 14 | ``` 15 | (int list) l = [1, 1, 1] 16 | ``` 17 | Output: 18 | ``` 19 | (int) 1 20 | ``` 21 | 22 | Inputs: 23 | ``` 24 | (int list) l = [1, 2, 3, 4, 5, 6] 25 | ``` 26 | Output: 27 | ``` 28 | (int) 3 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /en_route_salute/readme.md: -------------------------------------------------------------------------------- 1 | ## En Route Salute 2 | 3 | Commander Lambda loves efficiency and hates anything that wastes time. She's a busy lamb, after all! She generously rewards henchmen who identify sources of inefficiency and come up with ways to remove them. You've spotted one such source, and you think solving it will help you build the reputation you need to get promoted. 4 | 5 | Every time the Commander's employees pass each other in the hall, each of them must stop and salute each other - one at a time - before resuming their path. A salute is five seconds long, so each exchange of salutes takes a full ten seconds (Commander Lambda's salute is a bit, er, involved). You think that by removing the salute requirement, you could save several collective hours of employee time per day. But first, you need to show her how bad the problem really is. 6 | 7 | Write a program that counts how many salutes are exchanged during a typical walk along a hallway. The hall is represented by a string. For example: 8 | "--->-><-><-->-" 9 | 10 | Each hallway string will contain three different types of characters: '>', an employee walking to the right; '<', an employee walking to the left; and '-', an empty space. Every employee walks at the same speed either to right or to the left, according to their direction. Whenever two employees cross, each of them salutes the other. They then continue walking until they reach the end, finally leaving the hallway. In the above example, they salute 10 times. 11 | 12 | Write a function answer(s) which takes a string representing employees walking along a hallway and returns the number of times the employees will salute. s will contain at least 1 and at most 100 characters, each one of -, >, or <. 13 | 14 | ### Test cases 15 | 16 | Inputs: 17 | 18 | ``` 19 | (string) s = ">----<" 20 | ``` 21 | 22 | Output: 23 | 24 | ``` 25 | (int) 2 26 | ``` 27 | 28 | Inputs: 29 | 30 | ``` 31 | (string) s = "<<>><" 32 | ``` 33 | 34 | Output: 35 | 36 | ``` 37 | (int) 4 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /prepare_the_bunnies_escape/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | To get the fewest steps, use BFS to traverse the maze. 3 | Each step, there are possible four direction (up, down, left, right) 4 | Since we can break the wall once, use a bool wallBefore to memory this status 5 | """ 6 | 7 | 8 | def answer(maze): 9 | h = len(maze) 10 | w = len(maze[0]) 11 | 12 | visit = set() 13 | step = 1 14 | queue = [(0, 0, 0)] 15 | while queue: 16 | size = len(queue) 17 | for _ in range(size): 18 | i, j, wallBefore = queue.pop(0) 19 | # Reach the end 20 | if i == h - 1 and j == w - 1: 21 | return step 22 | # The position with status is visited, do nothing 23 | if (i, j, wallBefore) in visit: 24 | continue 25 | # The position is a wall and we have broken the other wall before, do nothing 26 | if wallBefore & maze[i][j]: 27 | continue 28 | # Record the position and status 29 | visit.add((i, j, wallBefore | maze[i][j])) 30 | # Add next positions into the queue 31 | if i < h - 1: 32 | queue.append([i+1, j, wallBefore | maze[i][j]]) 33 | if j < w - 1: 34 | queue.append([i, j+1, wallBefore | maze[i][j]]) 35 | if i > 0: 36 | queue.append([i-1, j, wallBefore | maze[i][j]]) 37 | if j > 0: 38 | queue.append([i, j-1, wallBefore | maze[i][j]]) 39 | step += 1 40 | return step 41 | 42 | if __name__ == "__main__": 43 | maze = [ 44 | [0, 1, 1, 0], 45 | [0, 0, 0, 1], 46 | [1, 1, 0, 0], 47 | [1, 1, 1, 0] 48 | ] 49 | print(answer(maze) == 7) 50 | 51 | maze = [ 52 | [0, 0, 0, 0, 0, 0], 53 | [1, 1, 1, 1, 1, 0], 54 | [0, 0, 0, 0, 0, 0], 55 | [0, 1, 1, 1, 1, 1], 56 | [0, 1, 1, 1, 1, 1], 57 | [0, 0, 0, 0, 0, 0] 58 | ] 59 | print(answer(maze) == 11) 60 | -------------------------------------------------------------------------------- /minion_labor_shifts/readme.md: -------------------------------------------------------------------------------- 1 | ## Minion Labor Shifts 2 | 3 | Commander Lambda's minions are upset! They're given the worst jobs on the whole space station, and some of them are starting to complain that even those worst jobs are being allocated unfairly. If you can fix this problem, it'll prove your chops to Commander Lambda so you can get promoted! 4 | 5 | Minions' tasks are assigned by putting their ID numbers into a list, one time for each day they'll work that task. As shifts are planned well in advance, the lists for each task will contain up to 99 integers. When a minion is scheduled for the same task too many times, they'll complain about it until they're taken off the task completely. Some tasks are worse than others, so the number of scheduled assignments before a minion will refuse to do a task varies depending on the task. You figure you can speed things up by automating the removal of the minions who have been assigned a task too many times before they even get a chance to start complaining. 6 | 7 | Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely. 8 | 9 | ### Test cases 10 | 11 | Inputs: 12 | 13 | ``` 14 | (int list) data = [1, 2, 3] 15 | (int) n = 0 16 | ``` 17 | 18 | Output: 19 | 20 | ``` 21 | (int list) [] 22 | ``` 23 | 24 | Inputs: 25 | 26 | ``` 27 | (int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5] 28 | (int) n = 1 29 | ``` 30 | 31 | Output: 32 | 33 | ``` 34 | (int list) [1, 4] 35 | ``` 36 | 37 | Inputs: 38 | 39 | ``` 40 | (int list) data = [1, 2, 3] 41 | (int) n = 6 42 | ``` 43 | 44 | Output: 45 | 46 | ``` 47 | (int list) [1, 2, 3] 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /the_grandest_staircase_of_them_all/readme.md: -------------------------------------------------------------------------------- 1 | ## The Grandest Staircase Of Them All 2 | 3 | With her LAMBCHOP doomsday device finished, Commander Lambda is preparing for her debut on the galactic stage - but in order to make a grand entrance, she needs a grand staircase! As her personal assistant, you've been tasked with figuring out how to build the best staircase EVER. 4 | 5 | Lambda has given you an overview of the types of bricks available, plus a budget. You can buy different amounts of the different types of bricks (for example, 3 little pink bricks, or 5 blue lace bricks). Commander Lambda wants to know how many different types of staircases can be built with each amount of bricks, so she can pick the one with the most options. 6 | 7 | Each type of staircase should consist of 2 or more steps. No two steps are allowed to be at the same height - each step must be lower than the previous one. All steps must contain at least one brick. A step's height is classified as the total amount of bricks that make up that step. 8 | For example, when N = 3, you have only 1 choice of how to build the staircase, with the first step having a height of 2 and the second step having a height of 1: (# indicates a brick) 9 | 10 | ``` 11 | # 12 | ## 13 | 21 14 | ``` 15 | 16 | When N = 4, you still only have 1 staircase choice: 17 | 18 | ``` 19 | # 20 | # 21 | ## 22 | 31 23 | ``` 24 | 25 | But when N = 5, there are two ways you can build a staircase from the given bricks. The two staircases can have heights (4, 1) or (3, 2), as shown below: 26 | 27 | ``` 28 | # 29 | # 30 | # 31 | ## 32 | 41 33 | 34 | # 35 | ## 36 | ## 37 | 32 38 | ``` 39 | 40 | Write a function called answer(n) that takes a positive integer n and returns the number of different staircases that can be built from exactly n bricks. n will always be at least 3 (so you can have a staircase at all), but no more than 200, because Commander Lambda's not made of money! 41 | 42 | ### Test cases 43 | 44 | Inputs: 45 | ``` 46 | (int) n = 3 47 | ``` 48 | Output: 49 | ``` 50 | (int) 1 51 | ``` 52 | 53 | Inputs: 54 | ``` 55 | (int) n = 200 56 | ``` 57 | Output: 58 | ``` 59 | (int) 487067745 60 | ``` 61 | -------------------------------------------------------------------------------- /bringing_a_gun_to_a_guard_fight/solution.py: -------------------------------------------------------------------------------- 1 | def answer(dimensions, captain_position, badguy_position, distance): 2 | cx, cy = captain_position 3 | sqr_dist = distance ** 2 4 | 5 | if captain_position == badguy_position: 6 | return 0 7 | 8 | def get_mirrored(node): 9 | yield (node[0], node[1] - 2 * (node[1] - dimensions[1])) 10 | yield (node[0], -node[1]) 11 | yield (node[0] - 2 * (node[0] - dimensions[0]), node[1]) 12 | yield (-node[0], node[1]) 13 | 14 | def get_slope(dx, dy): 15 | if dx == dy == 0: 16 | return (0, 0) 17 | tx, ty = abs(dx), abs(dy) 18 | while ty: 19 | tx, ty = ty, tx % ty 20 | return (dx // tx, dy // tx) 21 | 22 | def get_all_mirror(node): 23 | prev = mirrors = set([(node[0], node[1])]) 24 | while True: 25 | new_mirrors = set() 26 | for node in prev: 27 | for tmp in get_mirrored(node): 28 | if (cx - tmp[0]) ** 2 + (cy - tmp[1]) ** 2 > sqr_dist: 29 | continue 30 | new_mirrors.add(tmp) 31 | new_mirrors -= mirrors 32 | if not new_mirrors: 33 | break 34 | mirrors |= new_mirrors 35 | prev = new_mirrors 36 | return mirrors 37 | 38 | bads = get_all_mirror(badguy_position) 39 | caps = get_all_mirror(captain_position) 40 | caps_slope = {} 41 | 42 | for x, y in caps: 43 | dx = cx - x 44 | dy = cy - y 45 | dist = dx ** 2 + dy ** 2 46 | slope = get_slope(dx, dy) 47 | if dist <= caps_slope.get(slope, sqr_dist): 48 | caps_slope[slope] = dist 49 | 50 | ans = set() 51 | for x, y in bads: 52 | dx = cx - x 53 | dy = cy - y 54 | dist = dx ** 2 + dy ** 2 55 | slope = get_slope(dx, dy) 56 | if dist <= caps_slope.get(slope, sqr_dist): 57 | ans.add(slope) 58 | return len(ans) 59 | 60 | if __name__ == "__main__": 61 | print(0, answer((3, 2), (1, 1), (1, 1), 4)) 62 | print(7, answer((3, 2), (1, 1), (2, 1), 4)) 63 | print(9, answer((300, 275), (150, 150), (185, 100), 500)) 64 | print(27, answer((2, 5), (1, 2), (1, 4), 11)) 65 | -------------------------------------------------------------------------------- /prepare_the_bunnies_escape/readme.md: -------------------------------------------------------------------------------- 1 | ## Prepare the Bunnies' Escape 2 | 3 | You're awfully close to destroying the LAMBCHOP doomsday device and freeing Commander Lambda's bunny prisoners, but once they're free of the prison blocks, the bunnies are going to need to escape Lambda's space station via the escape pods as quickly as possible. Unfortunately, the halls of the space station are a maze of corridors and dead ends that will be a deathtrap for the escaping bunnies. Fortunately, Commander Lambda has put you in charge of a remodeling project that will give you the opportunity to make things a little easier for the bunnies. Unfortunately (again), you can't just remove all obstacles between the bunnies and the escape pods - at most you can remove one wall per escape pod path, both to maintain structural integrity of the station and to avoid arousing Commander Lambda's suspicions. 4 | 5 | You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1). 6 | 7 | Write a function answer(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed. 8 | 9 | ### Test cases 10 | 11 | Inputs: 12 | ``` 13 | (int) maze = [[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]] 14 | ``` 15 | Output: 16 | ``` 17 | (int) 7 18 | ``` 19 | 20 | Inputs: 21 | ``` 22 | (int) maze = [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]] 23 | ``` 24 | Output: 25 | ``` 26 | (int) 11 27 | ``` 28 | 29 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 30 | 31 | 32 | -------------------------------------------------------------------------------- /bomb_baby/readme.md: -------------------------------------------------------------------------------- 1 | ## Bomb, Baby! 2 | 3 | You're so close to destroying the LAMBCHOP doomsday device you can taste it! But in order to do so, you need to deploy special self-replicating bombs designed for you by the brightest scientists on Bunny Planet. There are two types: Mach bombs (M) and Facula bombs (F). The bombs, once released into the LAMBCHOP's inner workings, will automatically deploy to all the strategic points you've identified and destroy them at the same time. 4 | 5 | But there's a few catches. First, the bombs self-replicate via one of two distinct processes: 6 | Every Mach bomb retrieves a sync unit from a Facula bomb; for every Mach bomb, a Facula bomb is created; 7 | Every Facula bomb spontaneously creates a Mach bomb. 8 | 9 | For example, if you had 3 Mach bombs and 2 Facula bombs, they could either produce 3 Mach bombs and 5 Facula bombs, or 5 Mach bombs and 2 Facula bombs. The replication process can be changed each cycle. 10 | 11 | Second, you need to ensure that you have exactly the right number of Mach and Facula bombs to destroy the LAMBCHOP device. Too few, and the device might survive. Too many, and you might overload the mass capacitors and create a singularity at the heart of the space station - not good! 12 | 13 | And finally, you were only able to smuggle one of each type of bomb - one Mach, one Facula - aboard the ship when you arrived, so that's all you have to start with. (Thus it may be impossible to deploy the bombs to destroy the LAMBCHOP, but that's not going to stop you from trying!) 14 | 15 | You need to know how many replication cycles (generations) it will take to generate the correct amount of bombs to destroy the LAMBCHOP. Write a function answer(M, F) where M and F are the number of Mach and Facula bombs needed. Return the fewest number of generations (as a string) that need to pass before you'll have the exact number of bombs necessary to destroy the LAMBCHOP, or the string "impossible" if this can't be done! M and F will be string representations of positive integers no larger than 10^50. For example, if M = "2" and F = "1", one generation would need to pass, so the answer would be "1". However, if M = "2" and F = "4", it would not be possible. 16 | 17 | ### Test cases 18 | 19 | Inputs: 20 | ``` 21 | (string) M = "2" 22 | (string) F = "1" 23 | ``` 24 | Output: 25 | ``` 26 | (string) "1" 27 | ``` 28 | 29 | Inputs: 30 | ``` 31 | (string) M = "4" 32 | (string) F = "7" 33 | ``` 34 | Output: 35 | ``` 36 | (string) "4" 37 | ``` 38 | -------------------------------------------------------------------------------- /ion_flux_relabeling/readme.md: -------------------------------------------------------------------------------- 1 | ## Ion Flux Relabeling 2 | 3 | Oh no! Commander Lambda's latest experiment to improve the efficiency of her LAMBCHOP doomsday device has backfired spectacularly. She had been improving the structure of the ion flux converter tree, but something went terribly wrong and the flux chains exploded. Some of the ion flux converters survived the explosion intact, but others had their position labels blasted off. She's having her henchmen rebuild the ion flux converter tree by hand, but you think you can do it much more quickly - quickly enough, perhaps, to earn a promotion! 4 | 5 | Flux chains require perfect binary trees, so Lambda's design arranged the ion flux converters to form one. To label them, she performed a post-order traversal of the tree of converters and labeled each converter with the order of that converter in the traversal, starting at 1. For example, a tree of 7 converters would look like the following: 6 | 7 | ``` 8 | 7 9 | 3 6 10 | 1 2 4 5 11 | ``` 12 | 13 | Write a function answer(h, q) - where h is the height of the perfect tree of converters and q is a list of positive integers representing different flux converters - which returns a list of integers p where each element in p is the label of the converter that sits on top of the respective converter in q, or -1 if there is no such converter. For example, answer(3, [1, 4, 7]) would return the converters above the converters at indexes 1, 4, and 7 in a perfect binary tree of height 3, which is [3, 6, -1]. 14 | 15 | The domain of the integer h is 1 <= h <= 30, where h = 1 represents a perfect binary tree containing only the root, h = 2 represents a perfect binary tree with the root and two leaf nodes, h = 3 represents a perfect binary tree with the root, two internal nodes and four leaf nodes (like the example above), and so forth. The lists q and p contain at least one but no more than 10000 distinct integers, all of which will be between 1 and 2^h-1, inclusive. 16 | 17 | ### Test cases 18 | 19 | Inputs: 20 | 21 | ``` 22 | (int) h = 3 23 | (int list) q = [7, 3, 5, 1] 24 | ``` 25 | 26 | Output: 27 | 28 | ``` 29 | (int list) [-1, 7, 6, 3] 30 | ``` 31 | 32 | Inputs: 33 | 34 | ``` 35 | (int) h = 5 36 | (int list) q = [19, 14, 28] 37 | ``` 38 | 39 | Output: 40 | 41 | ``` 42 | (int list) [21, 15, 29] 43 | ``` 44 | 45 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 46 | 47 | 48 | -------------------------------------------------------------------------------- /distract_the_guards/solution.py: -------------------------------------------------------------------------------- 1 | def answer(banana_list): 2 | banana_list.sort(reverse=True) 3 | n = len(banana_list) 4 | 5 | def isLoop(x, y): 6 | z = x + y 7 | while y: 8 | x, y = y, y % x 9 | z //= x 10 | return (z & (z - 1)) != 0 11 | 12 | graph = {} 13 | for i in range(n - 1): 14 | for j in range(i + 1, n): 15 | if isLoop(banana_list[i], banana_list[j]): 16 | graph.setdefault(i, []) 17 | graph.setdefault(j, []) 18 | graph[i].append(j) 19 | graph[j].append(i) 20 | 21 | return maximum_matching(graph, n) 22 | 23 | 24 | def maximum_matching(graph, size): 25 | exposed = list(range(size)) 26 | nonmatch_e = set([(x, y) for x in graph for y in graph[x]]) 27 | match_e = set() 28 | 29 | hasPath = True 30 | while hasPath: 31 | hasPath = False 32 | for start in exposed: 33 | visited = set() 34 | flag = False 35 | path = [] 36 | u = start 37 | 38 | while True: 39 | visited.add(u) 40 | 41 | for v in graph.get(u, []): 42 | if v in visited: 43 | continue 44 | if (not flag and (u, v) in nonmatch_e) or (flag and (u, v) in match_e): 45 | path.append(u) 46 | path.append(v) 47 | break 48 | 49 | if not path: 50 | break 51 | 52 | if path[-1] in exposed and path[-1] != start: 53 | hasPath = True 54 | for i in range(len(path) - 1): 55 | if (path[i], path[i + 1]) in match_e: 56 | match_e.remove((path[i], path[i + 1])) 57 | match_e.remove((path[i + 1], path[i])) 58 | nonmatch_e.add((path[i], path[i + 1])) 59 | nonmatch_e.add((path[i + 1], path[i])) 60 | else: 61 | nonmatch_e.remove((path[i], path[i + 1])) 62 | nonmatch_e.remove((path[i + 1], path[i])) 63 | match_e.add((path[i], path[i + 1])) 64 | match_e.add((path[i + 1], path[i])) 65 | exposed.remove(path[0]) 66 | exposed.remove(path[-1]) 67 | break 68 | 69 | flag = not flag 70 | u = path.pop() 71 | 72 | return len(exposed) 73 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Google Foo.Bar 2 | 3 | My solutions from Google Foobar. For educational purposes only. 4 | 5 | https://foobar.withgoogle.com 6 | 7 | ``` 8 | Level 5 complete. 9 | 10 | Level 1 100% [==========================================] 11 | Level 2 100% [==========================================] 12 | Level 3 100% [==========================================] 13 | Level 4 100% [==========================================] 14 | Level 5 100% [==========================================] 15 | 16 | 17 | 18 | KEIGEQw3MiAWUkRVdHA0FxAFG3N7c0IWCwM4MjICAAFIdG1zQhAXGzEyPgARQ0N0cDYDEwsdICR0 RU9ESD05MBcQAAY2OzZCWURINTQ7DBASCjkyPRFSRFV0cCYLGQsMPzI3QllESCY2MQccEBxzd2lF UhcOMjJ0SVVDCTs4dEVPREgjPj1EUhk= 19 | 20 | 21 | # decoded message 22 | 23 | ['sucCESs' :Great 24 | 'colLEAgue''estEEMed',EfforTS : 'INCrediBLE', 'ACHieveMENt' :UnlocKED', 'RABbits 'saFE, 'fOO : 'WIN!'} 25 | ``` 26 | 27 | ## Languages & Constrains 28 | 29 | ### Python 30 | 31 | To provide a Python solution, edit solution.py 32 | 33 | Your code will run inside a Python 2.7.6 sandbox. 34 | Standard libraries are supported except for bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib. 35 | 36 | ### Java 37 | 38 | To provide a Java solution, edit solution.java 39 | 40 | Your code will be compiled using standard Java 7. It must implement the answer() method in the solution stub. 41 | Execution time is limited. Some classes are restricted (e.g. java.lang.ClassLoader). You will see a notice if you use a restricted class when you verify your solution. 42 | Third-party libraries, input/output operations, spawning threads or processes and changes to the execution environment are not allowed. 43 | 44 | ## Problems 45 | 46 | ### Level 1 47 | 48 | - [Re-ID](./re_id) 49 | - `*` [Minion Labor Shifts](./minion_labor_shifts) 50 | 51 | ### Level 2 52 | 53 | - [Ion Flux Relabeling](./ion_flux_relabeling) 54 | - [Lovely Lucky LAMBs](./lovely_lucky_lambs) 55 | - `*` [Bunny Prisoner Locating](./bunny_prisoner_locating) 56 | - `*` [En Route Salute](./en_route_salute) 57 | 58 | ### Level 3 59 | 60 | - [Bomb, Baby!](./bomb_baby) 61 | - [Queue To Do](./queue_to_do) 62 | - [Prepare the Bunnies' Escape](./prepare_the_bunnies_escape) 63 | - `*` [Find the Access Codes](./find_the_access_codes) 64 | - `*` [The Grandest Staircase Of Them All](./the_grandest_staircase_of_them_all) 65 | 66 | 67 | ### Level 4 68 | - [Bringing a Gun to a Guard Fight](./bringing_a_gun_to_a_guard_fight) 69 | - [Distract the Guards](./distract_the_guards) 70 | 71 | ### Level 5 72 | - [Dodge the Lasers!](./dodge_the_lasers/) 73 | 74 | ---- 75 | 76 | Note 77 | > Problems marked with `*` are collected from other place. 78 | > So I did't verify those solution, but I think they work. 79 | -------------------------------------------------------------------------------- /queue_to_do/readme.md: -------------------------------------------------------------------------------- 1 | ## Queue To Do 2 | 3 | You're almost ready to make your move to destroy the LAMBCHOP doomsday device, but the security checkpoints that guard the underlying systems of the LAMBCHOP are going to be a problem. You were able to take one down without tripping any alarms, which is great! Except that as Commander Lambda's assistant, you've learned that the checkpoints are about to come under automated review, which means that your sabotage will be discovered and your cover blown - unless you can trick the automated review system. 4 | 5 | To trick the system, you'll need to write a program to return the same security checksum that the guards would have after they would have checked all the workers through. Fortunately, Commander Lambda's desire for efficiency won't allow for hours-long lines, so the checkpoint guards have found ways to quicken the pass-through rate. Instead of checking each and every worker coming through, the guards instead go over everyone in line while noting their security IDs, then allow the line to fill back up. Once they've done that they go over the line again, this time leaving off the last worker. They continue doing this, leaving off one more worker from the line each time but recording the security IDs of those they do check, until they skip the entire line, at which point they XOR the IDs of all the workers they noted into a checksum and then take off for lunch. Fortunately, the workers' orderly nature causes them to always line up in numerical order without any gaps. 6 | 7 | For example, if the first worker in line has ID 0 and the security checkpoint line holds three workers, the process would look like this: 8 | 9 | ``` 10 | 0 1 2 / 11 | 3 4 / 5 12 | 6 / 7 8 13 | ``` 14 | 15 | where the guards' XOR (^) checksum is `0^1^2^3^4^6` == 2. 16 | 17 | Likewise, if the first worker has ID 17 and the checkpoint holds four workers, the process would look like: 18 | 19 | ``` 20 | 17 18 19 20 / 21 | 21 22 23 / 24 22 | 25 26 / 27 28 23 | 29 / 30 31 32 24 | ``` 25 | 26 | which produces the checksum `17^18^19^20^21^22^23^25^26^29` == 14. 27 | 28 | All worker IDs (including the first worker) are between 0 and 2000000000 inclusive, and the checkpoint line will always be at least 1 worker long. 29 | 30 | With this information, write a function answer(start, length) that will cover for the missing security checkpoint by outputting the same checksum the guards would normally submit before lunch. You have just enough time to find out the ID of the first worker to be checked (start) and the length of the line (length) before the automatic review occurs, so your program must generate the proper checksum with just those two values. 31 | 32 | ### Test cases 33 | 34 | Inputs: 35 | ``` 36 | (int) start = 0 37 | (int) length = 3 38 | ``` 39 | Output: 40 | ``` 41 | (int) 2 42 | ``` 43 | 44 | Inputs: 45 | ``` 46 | (int) start = 17 47 | (int) length = 4 48 | ``` 49 | Output: 50 | ``` 51 | (int) 14 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /dodge_the_lasers/readme.md: -------------------------------------------------------------------------------- 1 | Dodge the Lasers! 2 | ================= 3 | 4 | Oh no! You've managed to escape Commander Lambdas collapsing space station in an escape pod with the rescued bunny prisoners - but Commander Lambda isnt about to let you get away that easily. She's sent her elite fighter pilot squadron after you - and they've opened fire! 5 | 6 | Fortunately, you know something important about the ships trying to shoot you down. Back when you were still Commander Lambdas assistant, she asked you to help program the aiming mechanisms for the starfighters. They undergo rigorous testing procedures, but you were still able to slip in a subtle bug. The software works as a time step simulation: if it is tracking a target that is accelerating away at 45 degrees, the software will consider the targets acceleration to be equal to the square root of 2, adding the calculated result to the targets end velocity at each timestep. However, thanks to your bug, instead of storing the result with proper precision, it will be truncated to an integer before adding the new velocity to your current position. This means that instead of having your correct position, the targeting software will erringly report your position as sum(i=1..n, floor(i*sqrt(2))) - not far enough off to fail Commander Lambdas testing, but enough that it might just save your life. 7 | 8 | If you can quickly calculate the target of the starfighters' laser beams to know how far off they'll be, you can trick them into shooting an asteroid, releasing dust, and concealing the rest of your escape. Write a function answer(str_n) which, given the string representation of an integer n, returns the sum of (floor(1*sqrt(2)) + floor(2*sqrt(2)) + ... + floor(n*sqrt(2))) as a string. That is, for every number i in the range 1 to n, it adds up all of the integer portions of i*sqrt(2). 9 | 10 | For example, if str_n was "5", the answer would be calculated as 11 | floor(1*sqrt(2)) + 12 | floor(2*sqrt(2)) + 13 | floor(3*sqrt(2)) + 14 | floor(4*sqrt(2)) + 15 | floor(5*sqrt(2)) 16 | = 1+2+4+5+7 = 19 17 | so the function would return "19". 18 | 19 | str_n will be a positive integer between 1 and 10^100, inclusive. Since n can be very large (up to 101 digits!), using just sqrt(2) and a loop won't work. Sometimes, it's easier to take a step back and concentrate not on what you have in front of you, but on what you don't. 20 | 21 | Languages 22 | ========= 23 | 24 | To provide a Python solution, edit solution.py 25 | To provide a Java solution, edit solution.java 26 | 27 | Test cases 28 | ========== 29 | 30 | Inputs: 31 | ``` 32 | (string) str_n = "5" 33 | ``` 34 | Output: 35 | ``` 36 | (string) "19" 37 | ``` 38 | 39 | Inputs: 40 | ``` 41 | (string) str_n = "77" 42 | ``` 43 | Output: 44 | ``` 45 | (string) "4208" 46 | ``` 47 | 48 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 49 | -------------------------------------------------------------------------------- /lovely_lucky_lambs/readme.md: -------------------------------------------------------------------------------- 1 | ## Lovely Lucky LAMBs 2 | 3 | Being a henchman isn't all drudgery. Occasionally, when Commander Lambda is feeling generous, she'll hand out Lucky LAMBs (Lambda's All-purpose Money Bucks). Henchmen can use Lucky LAMBs to buy things like a second pair of socks, a pillow for their bunks, or even a third daily meal! 4 | 5 | However, actually passing out LAMBs isn't easy. Each henchman squad has a strict seniority ranking which must be respected - or else the henchmen will revolt and you'll all get demoted back to minions again! 6 | 7 | There are 4 key rules which you must follow in order to avoid a revolt: 8 | 9 | ``` 10 | 1. The most junior henchman (with the least seniority) gets exactly 1 LAMB. (There will always be at least 1 henchman on a team.) 11 | 2. A henchman will revolt if the person who ranks immediately above them gets more than double the number of LAMBs they do. 12 | 3. A henchman will revolt if the amount of LAMBs given to their next two subordinates combined is more than the number of LAMBs they get. (Note that the two most junior henchmen won't have two subordinates, so this rule doesn't apply to them. The 2nd most junior henchman would require at least as many LAMBs as the most junior henchman.) 13 | 4. You can always find more henchmen to pay - the Commander has plenty of employees. If there are enough LAMBs left over such that another henchman could be added as the most senior while obeying the other rules, you must always add and pay that henchman. 14 | ``` 15 | 16 | Note that you may not be able to hand out all the LAMBs. A single LAMB cannot be subdivided. That is, all henchmen must get a positive integer number of LAMBs. 17 | 18 | Write a function called answer(total_lambs), where total_lambs is the integer number of LAMBs in the handout you are trying to divide. It should return an integer which represents the difference between the minimum and maximum number of henchmen who can share the LAMBs (that is, being as generous as possible to those you pay and as stingy as possible, respectively) while still obeying all of the above rules to avoid a revolt. For instance, if you had 10 LAMBs and were as generous as possible, you could only pay 3 henchmen (1, 2, and 4 LAMBs, in order of ascending seniority), whereas if you were as stingy as possible, you could pay 4 henchmen (1, 1, 2, and 3 LAMBs). Therefore, answer(10) should return 4-3 = 1. 19 | 20 | To keep things interesting, Commander Lambda varies the sizes of the Lucky LAMB payouts: you can expect total_lambs to always be between 10 and 1 billion (10 ^ 9). 21 | 22 | ### Test cases 23 | 24 | Inputs: 25 | 26 | ``` 27 | (int) total_lambs = 10 28 | ``` 29 | 30 | Output: 31 | 32 | ``` 33 | (int) 1 34 | ``` 35 | 36 | Inputs: 37 | 38 | ``` 39 | (int) total_lambs = 143 40 | ``` 41 | 42 | Output: 43 | 44 | ``` 45 | (int) 3 46 | ``` 47 | 48 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 49 | 50 | 51 | -------------------------------------------------------------------------------- /bringing_a_gun_to_a_guard_fight/readme.md: -------------------------------------------------------------------------------- 1 | Bringing a Gun to a Guard Fight 2 | =============================== 3 | 4 | Uh-oh - you've been cornered by one of Commander Lambdas elite guards! Fortunately, you grabbed a beam weapon from an abandoned guardpost while you were running through the station, so you have a chance to fight your way out. But the beam weapon is potentially dangerous to you as well as to the elite guard: its beams reflect off walls, meaning youll have to be very careful where you shoot to avoid bouncing a shot toward yourself! 5 | 6 | Luckily, the beams can only travel a certain maximum distance before becoming too weak to cause damage. You also know that if a beam hits a corner, it will bounce back in exactly the same direction. And of course, if the beam hits either you or the guard, it will stop immediately (albeit painfully). 7 | 8 | Write a function answer(dimensions, your_position, guard_position, distance) that gives an array of 2 integers of the width and height of the room, an array of 2 integers of your x and y coordinates in the room, an array of 2 integers of the guard's x and y coordinates in the room, and returns an integer of the number of distinct directions that you can fire to hit the elite guard, given the maximum distance that the beam can travel. 9 | 10 | The room has integer dimensions [1 < x_dim <= 1000, 1 < y_dim <= 1000]. You and the elite guard are both positioned on the integer lattice at different distinct positions (x, y) inside the room such that [0 < x < x_dim, 0 < y < y_dim]. Finally, the maximum distance that the beam can travel before becoming harmless will be given as an integer 1 < distance <= 10000. 11 | 12 | For example, if you and the elite guard were positioned in a room with dimensions [3, 2], you_position [1, 1], guard_position [2, 1], and a maximum shot distance of 4, you could shoot in seven different directions to hit the elite guard (given as vector bearings from your location): [1, 0], [1, 2], [1, -2], [3, 2], [3, -2], [-3, 2], and [-3, -2]. As specific examples, the shot at bearing [1, 0] is the straight line horizontal shot of distance 1, the shot at bearing [-3, -2] bounces off the left wall and then the bottom wall before hitting the elite guard with a total shot distance of sqrt(13), and the shot at bearing [1, 2] bounces off just the top wall before hitting the elite guard with a total shot distance of sqrt(5). 13 | 14 | Languages 15 | ========= 16 | 17 | To provide a Python solution, edit solution.py 18 | To provide a Java solution, edit solution.java 19 | 20 | Test cases 21 | ========== 22 | 23 | Inputs: 24 | ``` 25 | (int list) dimensions = [3, 2] 26 | (int list) captain_position = [1, 1] 27 | (int list) badguy_position = [2, 1] 28 | (int) distance = 4 29 | ``` 30 | Output: 31 | ``` 32 | (int) 7 33 | ``` 34 | 35 | Inputs: 36 | ``` 37 | (int list) dimensions = [300, 275] 38 | (int list) captain_position = [150, 150] 39 | (int list) badguy_position = [185, 100] 40 | (int) distance = 500 41 | ``` 42 | Output: 43 | ``` 44 | (int) 9 45 | ``` 46 | 47 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 48 | -------------------------------------------------------------------------------- /distract_the_guards/readme.md: -------------------------------------------------------------------------------- 1 | Distract the Guards 2 | =================== 3 | 4 | The time for the mass escape has come, and you need to distract the guards so that the bunny prisoners can make it out! Unfortunately for you, they're watching the bunnies closely. Fortunately, this means they haven't realized yet that the space station is about to explode due to the destruction of the LAMBCHOP doomsday device. Also fortunately, all that time you spent working as first a minion and then a henchman means that you know the guards are fond of bananas. And gambling. And thumb wrestling. 5 | 6 | The guards, being bored, readily accept your suggestion to play the Banana Games. 7 | 8 | You will set up simultaneous thumb wrestling matches. In each match, two guards will pair off to thumb wrestle. The guard with fewer bananas will bet all their bananas, and the other guard will match the bet. The winner will receive all of the bet bananas. You don't pair off guards with the same number of bananas (you will see why, shortly). You know enough guard psychology to know that the one who has more bananas always gets over-confident and loses. Once a match begins, the pair of guards will continue to thumb wrestle and exchange bananas, until both of them have the same number of bananas. Once that happens, both of them will lose interest and go back to guarding the prisoners, and you don't want THAT to happen! 9 | 10 | For example, if the two guards that were paired started with 3 and 5 bananas, after the first round of thumb wrestling they will have 6 and 2 (the one with 3 bananas wins and gets 3 bananas from the loser). After the second round, they will have 4 and 4 (the one with 6 bananas loses 2 bananas). At that point they stop and get back to guarding. 11 | 12 | How is all this useful to distract the guards? Notice that if the guards had started with 1 and 4 bananas, then they keep thumb wrestling! 1, 4 -> 2, 3 -> 4, 1 -> 3, 2 -> 1, 4 and so on. 13 | 14 | Now your plan is clear. You must pair up the guards in such a way that the maximum number of guards go into an infinite thumb wrestling loop! 15 | 16 | Write a function answer(banana_list) which, given a list of positive integers depicting the amount of bananas the each guard starts with, returns the fewest possible number of guards that will be left to watch the prisoners. Element i of the list will be the number of bananas that guard i (counting from 0) starts with. 17 | 18 | The number of guards will be at least 1 and not more than 100, and the number of bananas each guard starts with will be a positive integer no more than 1073741823 (i.e. 2^30 -1). Some of them stockpile a LOT of bananas. 19 | 20 | Languages 21 | ========= 22 | 23 | To provide a Python solution, edit solution.py 24 | To provide a Java solution, edit solution.java 25 | 26 | Test cases 27 | ========== 28 | 29 | Inputs: 30 | ``` 31 | (int list) banana_list = [1, 1] 32 | ``` 33 | Output: 34 | ``` 35 | (int) 2 36 | ``` 37 | 38 | Inputs: 39 | ``` 40 | (int list) banana_list = [1, 7, 3, 21, 13, 19] 41 | ``` 42 | Output: 43 | ``` 44 | (int) 0 45 | ``` 46 | 47 | Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. 48 | -------------------------------------------------------------------------------- /journal.md: -------------------------------------------------------------------------------- 1 | LEVEL 1 2 | ======= 3 | 4 | Success! You've managed to infiltrate Commander Lambda's evil organization, and finally earned yourself an entry-level position as a Minion on her space station. From here, you just might be able to subvert her plans to use the LAMBCHOP doomsday device to destroy Bunny Planet. Problem is, Minions are the lowest of the low in the Lambda hierarchy. Better buck up and get working, or you'll never make it to the top... 5 | 6 | Why did you sign up for infiltration duty again? The pamphlets from Bunny HQ promised exotic and interesting missions, yet here you are drudging in the lowest level of Commander Lambda's organization. Hopefully you get that promotion soon... 7 | 8 | LEVEL 2 9 | ======= 10 | 11 | You survived a week in Commander Lambda's organization, and you even managed to get yourself promoted. Hooray! Henchmen still don't have the kind of security access you'll need to take down Commander Lambda, though, so you'd better keep working. Chop chop! 12 | 13 | The perks are definitely better as a Henchman than as a Minion. You're even allowed to sleep lying down! 14 | 15 | You got the guards to teach you a game today. It's kind of pointless, but they seem to like it and it helps you pass the time while you work your way up to Commander Lambda's inner circle. 16 | 17 | LEVEL 3 18 | ======= 19 | 20 | Awesome! Commander Lambda was so impressed by your efforts that she's made you her personal assistant. You'll be helping her directly with her work, which means you'll have access to all of her files-including the ones on the LAMBCHOP doomsday device. This is the chance you've been waiting for. Can you use your new access to finally topple Commander Lambda's evil empire? 21 | 22 | For a world-destroying despot with a penchant for making space-station-sized doomsday devices, Commander Lambda sure has good taste in office furniture. As her personal assistant, you have the latest in standing desk and ergonomic chair technology, and it sure makes a difference! 23 | 24 | There are a lot of difficult things about being undercover as Commander Lambda's personal assistant, but you have to say, the personal spa and private hot cocoa bar are pretty awesome. 25 | 26 | One of these days you're going to manage to glimpse Commander Lambda's password over her shoulder. But she's very careful about security, and you haven't managed it yet... 27 | 28 | LEVEL 4 29 | ======= 30 | 31 | Excellent! You've destroyed Commander Lambda's doomsday device and saved Bunny Planet! But there's one small problem: the LAMBCHOP was a wool-y important part of her space station, and when you blew it up, you triggered a chain reaction that's tearing the station apart. Can you rescue the imprisoned bunnies and escape before the entire thing explodes? 32 | 33 | 'Destroy a doomsday device,' they said. 'Rescue prisoners,' they said. 'Be a hero,' they said. They didn't mention anything about having to escape through a trash compactor that could turn on at any time. Doesn't anyone in Bunny HQ watch movies?! 34 | 35 | This was supposed to be an infiltration-and-rescue mission, not a repeat of the Great Cowland Station fiasco! You didn't think rescuing bunnies would involve this much running. 36 | 37 | LEVEL 5 38 | ======= 39 | 40 | Oh no! You escaped Commander Lambda's exploding space station - but so did she, and she's definitely not happy with you. She's chasing you in her heavily-armed starfighter, while you and your bunny refugees are stuck in these lumbering escape pods. It'll take all your wits and cleverness to escape such a hare-y situation, so you'd better hop to it! 41 | 42 | Uh-oh, your HUD shows half a dozen missiles headed your way. Better do a barrel roll! 43 | 44 | EPILOGUE 45 | ======== 46 | 47 | With one last roar of the escape pod's engines, you and your bunny companions jump to lightspeed. Congratulations! You've destroyed the LAMBCHOP, rescued the bunnies, gotten Commander Lambda off your tail, and saved the galaxy. Time for a little rest and relaxation back on Bunny Planet. Pat yourself on the back - you've earned it! 48 | --------------------------------------------------------------------------------