├── qrcode.png ├── .gitignore ├── level1 └── i-love-lance-janice │ ├── src │ └── Solution.java │ └── readme.md ├── level2 ├── bunny-prisoner-locating │ ├── src │ │ └── Solution.java │ └── readme.md └── hey-i-already-did-that │ ├── src │ └── Solution.java │ └── readme.md ├── level3 ├── find-the-access-codes │ ├── src │ │ └── Solution.java │ └── readme.md ├── fuel-injection-perfection │ ├── src │ │ └── Solution.java │ └── readme.md └── prepare-the-bunnies-escape │ ├── src │ └── Solution.java │ └── readme.md ├── level5 └── dodge-the-lasers │ ├── src │ └── Solution.java │ └── readme.md ├── README.md └── level4 ├── free-the-bunny-prisoners ├── src │ └── Solution.java └── readme.md └── bringing-a-gun-to-a-guard-fight ├── readme.md └── src └── Solution.java /qrcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuyubobobo/My-Google-Foobar/HEAD/qrcode.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ###################### 2 | # OS generated files # 3 | ###################### 4 | .DS_Store 5 | .DS_Store? 6 | ._* 7 | .Spotlight-V100 8 | .Trashes 9 | ehthumbs.db 10 | Thumbs.db 11 | 12 | ##################### 13 | # Java Ignore files # 14 | ##################### 15 | *.class 16 | 17 | ##################### 18 | # C++ Ignore files # 19 | ##################### 20 | *.gch 21 | *.out 22 | 23 | ########################## 24 | # Jetbrains Ignore files # 25 | ########################## 26 | *.iml 27 | .idea/ 28 | 29 | ################# 30 | # Keynote # 31 | ################# 32 | *.key 33 | 34 | ################# 35 | # Course # 36 | ################# 37 | ppt/ 38 | text-contents/ 39 | *.pdf 40 | *.PDF 41 | *.key 42 | -------------------------------------------------------------------------------- /level1/i-love-lance-janice/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | /// Linear Scan 6 | /// Time Complexity: O(n) 7 | /// Space Complexity: O(n) 8 | public class Solution { 9 | 10 | public static String solution(String x) { 11 | 12 | 13 | StringBuilder sb = new StringBuilder(); 14 | for(char c: x.toCharArray()) { 15 | if (c >= 'a' && c <= 'z') 16 | sb.append(Character.toChars('a' + 25 - (c - 'a'))); 17 | else 18 | sb.append(c); 19 | } 20 | return sb.toString(); 21 | } 22 | 23 | public static void main(String[] args){ 24 | 25 | System.out.println(Solution.solution("Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!")); 26 | } 27 | } -------------------------------------------------------------------------------- /level2/bunny-prisoner-locating/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | /// Mathematics 6 | /// Time Complexity: O(log(res)) 7 | /// Space Complexity: O(1) 8 | 9 | public class Solution { 10 | 11 | public static String solution(long x, long y) { 12 | 13 | long res = (x + 1) * x / 2; 14 | if(y == 1) return String.valueOf(res); 15 | 16 | res += (x * 2 + y - 2) * (y - 1) / 2; 17 | return String.valueOf(res); 18 | } 19 | 20 | public static void main(String[] args){ 21 | 22 | System.out.println(Solution.solution(3, 2)); 23 | // 9 24 | 25 | System.out.println(Solution.solution(5, 10)); 26 | // 96 27 | 28 | System.out.println(Solution.solution(1, 1)); 29 | // 1 30 | 31 | System.out.println(Solution.solution(2, 3)); 32 | // 8 33 | 34 | System.out.println(Solution.solution(100000, 100000)); 35 | // 19999800001 36 | } 37 | } -------------------------------------------------------------------------------- /level3/find-the-access-codes/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | /// Dynamic Programming 6 | /// Time Complexity: O(n^2) 7 | /// Space Complexity: O(n) 8 | public class Solution { 9 | 10 | public static int solution(int[] l) { 11 | 12 | int n = l.length; 13 | int[] ok = new int[n]; 14 | for(int i = 1; i < n; i ++) 15 | for(int j = i - 1; j >= 0; j --) 16 | if(l[i] % l[j] == 0) ok[i] ++; 17 | 18 | int res = 0; 19 | for(int i = 2; i < n; i ++) 20 | for(int j = i - 1; j >= 0; j --) 21 | if(l[i] % l[j] == 0) res += ok[j]; 22 | return res; 23 | } 24 | 25 | public static void main(String[] args){ 26 | 27 | int[] l1 = {1, 1, 1}; 28 | System.out.println(Solution.solution(l1)); 29 | // 1 30 | 31 | int[] l2 = {1, 2, 3, 4, 5, 6}; 32 | System.out.println(Solution.solution(l2)); 33 | // 3 34 | } 35 | } -------------------------------------------------------------------------------- /level3/fuel-injection-perfection/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | import java.math.BigInteger; 6 | 7 | 8 | /// Greedy 9 | /// Time Complexity: O(logx) 10 | /// Space Complexioty: O(logx) 11 | public class Solution { 12 | 13 | public static int solution(String x) { 14 | 15 | BigInteger n = new BigInteger(x); 16 | int res = 0; 17 | while(!n.equals(BigInteger.ONE)){ 18 | int p = n.getLowestSetBit(); 19 | if(p != 0){ 20 | res += p; 21 | n = n.shiftRight(p); 22 | } 23 | else{ 24 | if(n.equals(BigInteger.valueOf(3)) || 25 | n.remainder(BigInteger.valueOf(4)).equals(BigInteger.ONE)){ 26 | n = n.subtract(BigInteger.ONE); 27 | res ++; 28 | } 29 | else{ 30 | n = n.add(BigInteger.ONE); 31 | res ++; 32 | } 33 | } 34 | } 35 | return res; 36 | } 37 | 38 | public static void main(String[] args){ 39 | 40 | System.out.println(Solution.solution("15")); 41 | // 5 42 | 43 | System.out.println(Solution.solution("4")); 44 | // 2 45 | 46 | System.out.println(Solution.solution("3")); 47 | // 2 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /level5/dodge-the-lasers/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-23 4 | 5 | import java.math.BigDecimal; 6 | import java.math.BigInteger; 7 | 8 | 9 | /// Math 10 | /// See here for details: 11 | /// https://math.stackexchange.com/questions/2052179/how-to-find-sum-i-1n-left-lfloor-i-sqrt2-right-rfloor-a001951-a-beatty-s/2053713#2053713 12 | /// 13 | /// Time Complexity: O(logs)? 14 | /// Space Complexity: O(h * |s|) 15 | public class Solution { 16 | 17 | private static BigDecimal sqrt2 = new BigDecimal("1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727"); 18 | 19 | public static String solution(String s) { 20 | 21 | BigInteger res = calc(new BigInteger(s)); 22 | return res.toString(); 23 | } 24 | 25 | private static BigInteger calc(BigInteger n){ 26 | 27 | if(n.equals(BigInteger.ZERO)) return BigInteger.ZERO; 28 | 29 | BigInteger n2 = sqrt2.subtract(BigDecimal.ONE).multiply(new BigDecimal(n)).toBigInteger(); 30 | 31 | return n.multiply(n2) 32 | .add(n.multiply(n.add(BigInteger.ONE)).shiftRight(1)) 33 | .subtract(n2.multiply(n2.add(BigInteger.ONE)).shiftRight(1)) 34 | .subtract(calc(n2)); 35 | } 36 | 37 | public static void main(String[] args){ 38 | 39 | System.out.println(Solution.solution("5")); 40 | // 19 41 | 42 | System.out.println(Solution.solution("77")); 43 | // 4208 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## My Google Foobar 2 | 3 | 我的 Google Foobar 题解。 4 | 5 | 因为大家的 Google Foobar 的题目可能不同,所以这里只能列出我遇到的题目。 6 | 7 | 作为一个 old School 的程序员,我选择全程使用 Java 解决。应该属于少数派了:) 8 | 9 | 因为 Google Foobar 在提交以后,题目会消失,同一题目的代码提交通道也就消失了。所以我的代码没有来得及做优化。可能一些逻辑又臭又长,仅供参考。 10 | 11 |
12 | 13 | **个人公众号:是不是很酷**:) 14 | 15 | ![QRCode](qrcode.png) 16 | 17 | --- 18 | 19 | | Level | Problem | My Solution | 20 | | :---: | :--- | :---: | 21 | | 1 | [I Love Lance & Janice](level1/i-love-lance-janice/) | [Java](level1/i-love-lance-janice/src/Solution.java) | 22 | | 2 | [Bunny Prisoner Locating](level2/bunny-prisoner-locating/) | [Java](level2/bunny-prisoner-locating/src/Solution.java) | 23 | | | [Hey, I Already Did That!](level2/hey-i-already-did-that/) | [Java](level2/hey-i-already-did-that/src/Solution.java) | 24 | | 3 | [Prepare the Bunnies' Escape](level3/prepare-the-bunnies-escape/) | [Java](level3/prepare-the-bunnies-escape/src/Solution.java) | 25 | | | [Find the Access Codes](level3/find-the-access-codes/) | [Java](level3/find-the-access-codes/src/Solution.java) | 26 | | | [Fuel Injection Perfection](level3/fuel-injection-perfection/) | [Java](level3/fuel-injection-perfection/src/Solution.java) | 27 | | 4 | [Bringing a Gun to a Guard Fight](level4/bringing-a-gun-to-a-guard-fight/) | [Java](level4/bringing-a-gun-to-a-guard-fight/src/Solution.java) | 28 | | | [Free the Bunny Prisoners](level4/free-the-bunny-prisoners/) | [Java](level4/free-the-bunny-prisoners/src/Solution.java) | 29 | | 5 | [Dodge the Lasers!](level5/dodge-the-lasers/) | [Java](level5/dodge-the-lasers/src/Solution.java) | 30 | 31 |
32 | 33 | **大家加油!:)** -------------------------------------------------------------------------------- /level2/bunny-prisoner-locating/readme.md: -------------------------------------------------------------------------------- 1 | Bunny Prisoner Locating 2 | ======================= 3 | 4 | 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. 5 | 6 | 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: 7 | 8 | ``` 9 | | 7 10 | | 4 8 11 | | 2 5 9 12 | | 1 3 6 10 13 | ``` 14 | 15 | 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. 16 | 17 | 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). 18 | 19 | Write a function solution(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 solution as a string representation of the number. 20 | 21 | Languages 22 | ========= 23 | 24 | To provide a Java solution, edit Solution.java 25 | 26 | To provide a Python solution, edit solution.py 27 | 28 | Test cases 29 | ========== 30 | 31 | Your code should pass the following test cases. 32 | 33 | Note that it may also be run against hidden test cases not shown here. 34 | 35 | -- Java cases -- 36 | 37 | Input: 38 | 39 | Solution.solution(3, 2) 40 | 41 | Output: 42 | 43 | 9 44 | 45 | Input: 46 | 47 | Solution.solution(5, 10) 48 | 49 | Output: 50 | 51 | 96 52 | 53 | -- Python cases -- 54 | 55 | Input: 56 | 57 | solution.solution(5, 10) 58 | 59 | Output: 60 | 61 | 96 62 | 63 | Input: 64 | 65 | solution.solution(3, 2) 66 | 67 | Output: 68 | 69 | 9 -------------------------------------------------------------------------------- /level1/i-love-lance-janice/readme.md: -------------------------------------------------------------------------------- 1 | I Love Lance & Janice 2 | ===================== 3 | 4 | You've caught two of your fellow minions passing coded notes back and forth - while they're on duty, no less! Worse, you're pretty sure it's not job-related - they're both huge fans of the space soap opera ""Lance & Janice"". You know how much Commander Lambda hates waste, so if you can prove that these minions are wasting her time passing non-job-related notes, it'll put you that much closer to a promotion. 5 | 6 | Fortunately for you, the minions aren't exactly advanced cryptographers. In their code, every lowercase letter [a..z] is replaced with the corresponding one in [z..a], while every other character (including uppercase letters and punctuation) is left untouched. That is, 'a' becomes 'z', 'b' becomes 'y', 'c' becomes 'x', etc. For instance, the word ""vmxibkgrlm"", when decoded, would become ""encryption"". 7 | 8 | Write a function called solution(s) which takes in a string and returns the deciphered string so you can show the commander proof that these minions are talking about ""Lance & Janice"" instead of doing their jobs. 9 | 10 | Languages 11 | ========= 12 | 13 | To provide a Python solution, edit solution.py 14 | 15 | To provide a Java solution, edit Solution.java 16 | 17 | Test cases 18 | ========== 19 | Your code should pass the following test cases. 20 | Note that it may also be run against hidden test cases not shown here. 21 | 22 | -- Python cases -- 23 | 24 | Input: 25 | 26 | solution.solution("wrw blf hvv ozhg mrtsg'h vkrhlwv?") 27 | 28 | Output: 29 | 30 | did you see last night's episode? 31 | 32 | Input: 33 | 34 | solution.solution("Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!") 35 | 36 | Output: 37 | 38 | Yeah! I can't believe Lance lost his job at the colony!! 39 | 40 | -- Java cases -- 41 | 42 | Input: 43 | 44 | Solution.solution("Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!") 45 | 46 | Output: 47 | 48 | Yeah! I can't believe Lance lost his job at the colony!! 49 | 50 | Input: 51 | 52 | Solution.solution("wrw blf hvv ozhg mrtsg'h vkrhlwv?") 53 | 54 | Output: 55 | 56 | did you see last night's episode? -------------------------------------------------------------------------------- /level2/hey-i-already-did-that/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | import java.util.Arrays; 6 | import java.util.HashSet; 7 | 8 | 9 | /// Using HashSet 10 | /// Time Complexity: O(|res| * |s|) 11 | /// Space Complexity: O(|res| * |s|) 12 | public class Solution { 13 | 14 | public static int solution(String n, int b) { 15 | 16 | int k = n.length(); 17 | 18 | HashSet hashset = new HashSet<>(); 19 | while(!hashset.contains(n)){ 20 | hashset.add(n); 21 | n = next(n, k, b); 22 | // System.out.println(n); 23 | } 24 | 25 | return cycleLength(n, k, b); 26 | } 27 | 28 | private static int cycleLength(String n, int k, int b){ 29 | 30 | HashSet hashset = new HashSet<>(); 31 | int res = 0; 32 | while(!hashset.contains(n)){ 33 | hashset.add(n); 34 | n = next(n, k, b); 35 | res ++; 36 | } 37 | return res; 38 | } 39 | 40 | private static String next(String n, int k, int b){ 41 | 42 | char[] charn1 = n.toCharArray(); 43 | char[] charn2 = n.toCharArray(); 44 | 45 | Arrays.sort(charn1); 46 | for(int i = 0; i < charn1.length / 2; i ++){ 47 | char t = charn1[i]; 48 | charn1[i] = charn1[charn1.length - 1 - i]; 49 | charn1[charn1.length - 1 - i] = t; 50 | } 51 | String n1 = String.copyValueOf(charn1); 52 | // System.out.println(n1); 53 | 54 | Arrays.sort(charn2); 55 | String n2 = String.copyValueOf(charn2); 56 | // System.out.println(n2); 57 | 58 | int res = Integer.parseInt(n1, b) - Integer.parseInt(n2, b); 59 | String ret = Integer.toString(res, b); 60 | 61 | StringBuilder zero = new StringBuilder(); 62 | for(int i = 0; i < k - ret.length(); i ++) zero.append('0'); 63 | return zero.toString() + ret; 64 | } 65 | 66 | public static void main(String[] args){ 67 | 68 | System.out.println(Solution.solution("210022", 3)); 69 | // 3 70 | 71 | System.out.println(Solution.solution("1211", 10)); 72 | // 1 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /level3/fuel-injection-perfection/readme.md: -------------------------------------------------------------------------------- 1 | Fuel Injection Perfection 2 | ========================= 3 | 4 | Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly. 5 | 6 | Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time. 7 | 8 | The fuel control mechanisms have three operations: 9 | 10 | 1) Add one fuel pellet 11 | 12 | 2) Remove one fuel pellet 13 | 14 | 3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets) 15 | 16 | Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. 17 | 18 | For example: 19 | 20 | solution(4) returns 2: 4 -> 2 -> 1 21 | 22 | solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 23 | 24 | Languages 25 | ========= 26 | 27 | To provide a Python solution, edit solution.py 28 | 29 | To provide a Java solution, edit Solution.java 30 | 31 | Test cases 32 | ========== 33 | 34 | Your code should pass the following test cases. 35 | Note that it may also be run against hidden test cases not shown here. 36 | 37 | -- Python cases -- 38 | 39 | Input: 40 | 41 | solution.solution('15') 42 | 43 | Output: 44 | 45 | 5 46 | 47 | Input: 48 | 49 | solution.solution('4') 50 | 51 | Output: 52 | 53 | 2 54 | 55 | -- Java cases -- 56 | 57 | Input: 58 | 59 | Solution.solution('4') 60 | 61 | Output: 62 | 63 | 2 64 | 65 | Input: 66 | 67 | Solution.solution('15') 68 | 69 | Output: 70 | 71 | 5 -------------------------------------------------------------------------------- /level4/free-the-bunny-prisoners/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-23 4 | 5 | 6 | /// DFS 7 | /// Time Complexity: O(num_buns ^ num_buns) 8 | /// Space Complexity: O(num_bums * C(num_buns, num_buns - num_required + 1)) 9 | import java.util.ArrayList; 10 | 11 | public class Solution { 12 | 13 | public static int[][] solution(int num_buns, int num_required) { 14 | 15 | ArrayList> combs = new ArrayList<>(); 16 | ArrayList cur = new ArrayList<>(); 17 | dfs(num_buns, num_buns - num_required + 1, 0, cur, combs); 18 | 19 | ArrayList> res = new ArrayList<>(); 20 | for(int i = 0; i < num_buns; i ++) 21 | res.add(new ArrayList<>()); 22 | for(int i = 0; i < combs.size(); i ++) 23 | for(int j: combs.get(i)) 24 | res.get(j).add(i); 25 | 26 | int sz = res.get(0).size(); 27 | int[][] ret = new int[num_buns][sz]; 28 | for(int i = 0; i < num_buns; i ++){ 29 | ret[i] = new int[sz]; 30 | if(res.get(i).size() != sz) throw new RuntimeException(); 31 | for(int j = 0; j < sz; j ++) ret[i][j] = res.get(i).get(j); 32 | } 33 | return ret; 34 | } 35 | 36 | private static void dfs(int n, int k, int index, 37 | ArrayList cur, ArrayList> comb){ 38 | 39 | if(cur.size() == k){ 40 | comb.add(new ArrayList<>(cur)); 41 | return; 42 | } 43 | 44 | for(int i = index; i < n; i ++){ 45 | cur.add(i); 46 | dfs(n, k, i + 1, cur, comb); 47 | cur.remove(cur.size() - 1); 48 | } 49 | } 50 | 51 | private static void printResult(int[][] res){ 52 | 53 | for(int[] row: res){ 54 | for(int e: row) System.out.print(e + " "); 55 | System.out.println(); 56 | } 57 | System.out.println(); 58 | } 59 | 60 | public static void main(String[] args){ 61 | 62 | printResult(Solution.solution(2, 1)); 63 | // 0 64 | // 0 65 | 66 | printResult(Solution.solution(4, 4)); 67 | // 0 68 | // 1 69 | // 2 70 | // 3 71 | 72 | printResult(Solution.solution(5, 3)); 73 | // 0 74 | // 1 75 | // 2 76 | // 3 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /level3/prepare-the-bunnies-escape/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | 9 | /// BFS 10 | /// Time Complexity: O(m * n * 2) 11 | /// Space Complexity: O(m * n * 2) 12 | public class Solution { 13 | 14 | private static int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 15 | 16 | public static int solution(int[][] map) { 17 | 18 | int m = map.length, n = map[0].length; 19 | 20 | int[][][] visited = new int[m][n][2]; 21 | Queue queue = new LinkedList<>(); 22 | queue.add(1); 23 | visited[0][0][0] = visited[0][0][1] = 1; 24 | while(!queue.isEmpty()){ 25 | 26 | int cur = queue.poll(); 27 | int curx = cur / 2 / n, cury = cur / 2 % n, left = cur % 2; 28 | if(curx == m - 1 && cury == n - 1) return visited[curx][cury][left]; 29 | 30 | for(int[] d: dirs){ 31 | int nextx = curx + d[0], nexty = cury + d[1]; 32 | if(inArea(nextx, nexty, m, n)){ 33 | if(map[nextx][nexty] == 0 && visited[nextx][nexty][left] == 0){ 34 | visited[nextx][nexty][left] = visited[curx][cury][left] + 1; 35 | queue.add(nextx * 2 * n + nexty * 2 + left); 36 | } 37 | else if(map[nextx][nexty] == 1 && left == 1 && visited[nextx][nexty][0] == 0){ 38 | visited[nextx][nexty][0] = visited[curx][cury][left] + 1; 39 | queue.add(nextx * 2 * n + nexty * 2); 40 | } 41 | } 42 | } 43 | } 44 | return -1; 45 | } 46 | 47 | private static boolean inArea(int x, int y, int m, int n){ 48 | return x >= 0 && x < m && y >= 0 && y < n; 49 | } 50 | 51 | public static void main(String[] args){ 52 | 53 | int[][] map1 = { 54 | {0, 1, 1, 0}, {0, 0, 0, 1}, {1, 1, 0, 0}, {1, 1, 1, 0} 55 | }; 56 | System.out.println(Solution.solution(map1)); 57 | // 7 58 | 59 | int[][] map2 = { 60 | {0, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 0}, 61 | {0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, 62 | {0, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0} 63 | }; 64 | System.out.println(Solution.solution(map2)); 65 | // 11 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /level3/find-the-access-codes/readme.md: -------------------------------------------------------------------------------- 1 | Find the Access Codes 2 | ===================== 3 | 4 | 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. 5 | 6 | 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). 7 | 8 | Write a function solution(l) that takes a list of positive integers l and counts the number of "lucky triples" of (li, lj, lk) where the list indices meet the requirement 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. 9 | 10 | 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. 11 | 12 | Languages 13 | ========= 14 | 15 | To provide a Java solution, edit Solution.java 16 | 17 | To provide a Python solution, edit solution.py 18 | 19 | Test cases 20 | ========== 21 | 22 | Your code should pass the following test cases. 23 | Note that it may also be run against hidden test cases not shown here. 24 | 25 | -- Java cases -- 26 | 27 | Input: 28 | 29 | Solution.solution([1, 1, 1]) 30 | 31 | Output: 32 | 33 | 1 34 | 35 | Input: 36 | 37 | Solution.solution([1, 2, 3, 4, 5, 6]) 38 | 39 | Output: 40 | 41 | 3 42 | 43 | -- Python cases -- 44 | 45 | Input: 46 | 47 | solution.solution([1, 2, 3, 4, 5, 6]) 48 | 49 | Output: 50 | 51 | 3 52 | 53 | Input: 54 | 55 | solution.solution([1, 1, 1]) 56 | 57 | Output: 58 | 59 | 1 -------------------------------------------------------------------------------- /level3/prepare-the-bunnies-escape/readme.md: -------------------------------------------------------------------------------- 1 | Prepare the Bunnies' Escape 2 | =========================== 3 | 4 | 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. 5 | 6 | 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). 7 | 8 | Write a function solution(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. 9 | 10 | Languages 11 | ========= 12 | 13 | To provide a Python solution, edit solution.py 14 | 15 | To provide a Java solution, edit Solution.java 16 | 17 | Test cases 18 | ========== 19 | 20 | Your code should pass the following test cases. 21 | 22 | Note that it may also be run against hidden test cases not shown here. 23 | 24 | -- Python cases -- 25 | 26 | Input: 27 | 28 | solution.solution([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]]) 29 | 30 | Output: 31 | 32 | 7 33 | 34 | Input: 35 | 36 | solution.solution([[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]]) 37 | 38 | Output: 39 | 40 | 11 41 | 42 | -- Java cases -- 43 | 44 | Input: 45 | 46 | Solution.solution({{0, 1, 1, 0}, {0, 0, 0, 1}, {1, 1, 0, 0}, {1, 1, 1, 0}}) 47 | 48 | Output: 49 | 50 | 7 51 | 52 | Input: 53 | 54 | Solution.solution({{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}}) 55 | 56 | Output: 57 | 58 | 11 -------------------------------------------------------------------------------- /level2/hey-i-already-did-that/readme.md: -------------------------------------------------------------------------------- 1 | Hey, I Already Did That! 2 | ======================== 3 | 4 | Commander Lambda uses an automated algorithm to assign minions randomly to tasks, in order to keep her minions on their toes. But you've noticed a flaw in the algorithm - it eventually loops back on itself, so that instead of assigning new minions as it iterates, it gets stuck in a cycle of values so that the same minions end up doing the same tasks over and over again. You think proving this to Commander Lambda will help you make a case for your next promotion. 5 | 6 | You have worked out that the algorithm has the following process: 7 | 8 | 1) Start with a random minion ID n, which is a nonnegative integer of length k in base b 9 | 10 | 2) Define x and y as integers of length k. x has the digits of n in descending order, and y has the digits of n in ascending order 11 | 12 | 3) Define z = x - y. Add leading zeros to z to maintain length k if necessary 13 | 14 | 4) Assign n = z to get the next minion ID, and go back to step 2 15 | 16 | For example, given minion ID n = 1211, k = 4, b = 10, then x = 2111, y = 1112 and z = 2111 - 1112 = 0999. Then the next minion ID will be n = 0999 and the algorithm iterates again: x = 9990, y = 0999 and z = 9990 - 0999 = 8991, and so on. 17 | 18 | Depending on the values of n, k (derived from n), and b, at some point the algorithm reaches a cycle, such as by reaching a constant value. For example, starting with n = 210022, k = 6, b = 3, the algorithm will reach the cycle of values [210111, 122221, 102212] and it will stay in this cycle no matter how many times it continues iterating. Starting with n = 1211, the routine will reach the integer 6174, and since 7641 - 1467 is 6174, it will stay as that value no matter how many times it iterates. 19 | 20 | Given a minion ID as a string n representing a nonnegative integer of length k in base b, where 2 <= k <= 9 and 2 <= b <= 10, write a function solution(n, b) which returns the length of the ending cycle of the algorithm above starting with n. For instance, in the example above, solution(210022, 3) would return 3, since iterating on 102212 would return to 210111 when done in base 3. If the algorithm reaches a constant, such as 0, then the length is 1. 21 | 22 | Languages 23 | ========= 24 | 25 | To provide a Java solution, edit Solution.java 26 | 27 | To provide a Python solution, edit solution.py 28 | 29 | Test cases 30 | ========== 31 | 32 | Your code should pass the following test cases. 33 | 34 | Note that it may also be run against hidden test cases not shown here. 35 | 36 | -- Java cases -- 37 | 38 | Input: 39 | 40 | Solution.solution('210022', 3) 41 | 42 | Output: 43 | 44 | 3 45 | 46 | Input: 47 | 48 | Solution.solution('1211', 10) 49 | 50 | Output: 51 | 52 | 1 53 | 54 | -- Python cases -- 55 | 56 | Input: 57 | 58 | solution.solution('1211', 10) 59 | 60 | Output: 61 | 62 | 1 63 | 64 | Input: 65 | 66 | solution.solution('210022', 3) 67 | 68 | Output: 69 | 70 | 3 -------------------------------------------------------------------------------- /level5/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 solution(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 solution would be calculated as 11 | 12 | floor(1*sqrt(2)) + 13 | 14 | floor(2*sqrt(2)) + 15 | 16 | floor(3*sqrt(2)) + 17 | 18 | floor(4*sqrt(2)) + 19 | 20 | floor(5*sqrt(2)) 21 | 22 | = 1+2+4+5+7 = 19 23 | 24 | so the function would return "19". 25 | 26 | 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. 27 | 28 | Languages 29 | ========= 30 | 31 | To provide a Java solution, edit Solution.java 32 | 33 | To provide a Python solution, edit solution.py 34 | 35 | Test cases 36 | ========== 37 | 38 | Your code should pass the following test cases. 39 | Note that it may also be run against hidden test cases not shown here. 40 | 41 | -- Java cases -- 42 | 43 | Input: 44 | 45 | Solution.solution('77') 46 | 47 | Output: 48 | 49 | 4208 50 | 51 | Input: 52 | 53 | Solution.solution('5') 54 | 55 | Output: 56 | 57 | 19 58 | 59 | -- Python cases -- 60 | 61 | Input: 62 | 63 | solution.solution('77') 64 | 65 | Output: 66 | 67 | 4208 68 | 69 | Input: 70 | 71 | solution.solution('5') 72 | 73 | Output: 74 | 75 | 19 -------------------------------------------------------------------------------- /level4/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 guard post 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 you'll 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 solution(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 <= 1250, 1 < y_dim <= 1250]. 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], your_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 Java solution, edit Solution.java 18 | 19 | To provide a Python solution, edit solution.py 20 | 21 | Test cases 22 | ========== 23 | 24 | Your code should pass the following test cases. 25 | Note that it may also be run against hidden test cases not shown here. 26 | 27 | -- Java cases -- 28 | 29 | Input: 30 | 31 | Solution.solution([3,2], [1,1], [2,1], 4) 32 | 33 | Output: 34 | 35 | 7 36 | 37 | Input: 38 | 39 | Solution.solution([300,275], [150,150], [185,100], 500) 40 | 41 | Output: 42 | 43 | 9 44 | 45 | -- Python cases -- 46 | 47 | Input: 48 | 49 | solution.solution([3,2], [1,1], [2,1], 4) 50 | 51 | Output: 52 | 53 | 7 54 | 55 | Input: 56 | 57 | solution.solution([300,275], [150,150], [185,100], 500) 58 | 59 | Output: 60 | 61 | 9 -------------------------------------------------------------------------------- /level4/free-the-bunny-prisoners/readme.md: -------------------------------------------------------------------------------- 1 | Free the Bunny Prisoners 2 | ======================== 3 | 4 | You need to free the bunny prisoners before Commander Lambda's space station explodes! Unfortunately, the commander was very careful with her highest-value prisoners - they're all held in separate, maximum-security cells. The cells are opened by putting keys into each console, then pressing the open button on each console simultaneously. When the open button is pressed, each key opens its corresponding lock on the cell. So, the union of the keys in all of the consoles must be all of the keys. The scheme may require multiple copies of one key given to different minions. 5 | 6 | The consoles are far enough apart that a separate minion is needed for each one. Fortunately, you have already freed some bunnies to aid you - and even better, you were able to steal the keys while you were working as Commander Lambda's assistant. The problem is, you don't know which keys to use at which consoles. The consoles are programmed to know which keys each minion had, to prevent someone from just stealing all of the keys and using them blindly. There are signs by the consoles saying how many minions had some keys for the set of consoles. You suspect that Commander Lambda has a systematic way to decide which keys to give to each minion such that they could use the consoles. 7 | 8 | You need to figure out the scheme that Commander Lambda used to distribute the keys. You know how many minions had keys, and how many consoles are by each cell. You know that Command Lambda wouldn't issue more keys than necessary (beyond what the key distribution scheme requires), and that you need as many bunnies with keys as there are consoles to open the cell. 9 | 10 | Given the number of bunnies available and the number of locks required to open a cell, write a function solution(num_buns, num_required) which returns a specification of how to distribute the keys such that any num_required bunnies can open the locks, but no group of (num_required - 1) bunnies can. 11 | 12 | Each lock is numbered starting from 0. The keys are numbered the same as the lock they open (so for a duplicate key, the number will repeat, since it opens the same lock). For a given bunny, the keys they get is represented as a sorted list of the numbers for the keys. To cover all of the bunnies, the final answer is represented by a sorted list of each individual bunny's list of keys. Find the lexicographically least such key distribution - that is, the first bunny should have keys sequentially starting from 0. 13 | 14 | num_buns will always be between 1 and 9, and num_required will always be between 0 and 9 (both inclusive). For example, if you had 3 bunnies and required only 1 of them to open the cell, you would give each bunny the same key such that any of the 3 of them would be able to open it, like so: 15 | 16 | ``` 17 | [ 18 | [0], 19 | [0], 20 | [0], 21 | ] 22 | ``` 23 | 24 | If you had 2 bunnies and required both of them to open the cell, they would receive different keys (otherwise they wouldn't both actually be required), and your answer would be as follows: 25 | 26 | ``` 27 | [ 28 | [0], 29 | [1], 30 | ] 31 | ``` 32 | 33 | Finally, if you had 3 bunnies and required 2 of them to open the cell, then any 2 of the 3 bunnies should have all of the keys necessary to open the cell, but no single bunny would be able to do it. Thus, the answer would be: 34 | 35 | ``` 36 | [ 37 | [0, 1], 38 | [0, 2], 39 | [1, 2], 40 | ] 41 | ``` 42 | 43 | Languages 44 | ========= 45 | 46 | To provide a Python solution, edit solution.py 47 | 48 | To provide a Java solution, edit Solution.java 49 | 50 | Test cases 51 | ========== 52 | 53 | Your code should pass the following test cases. 54 | Note that it may also be run against hidden test cases not shown here. 55 | 56 | -- Python cases -- 57 | 58 | Input: 59 | 60 | solution.solution(2, 1) 61 | 62 | Output: 63 | 64 | [[0], [0]] 65 | 66 | Input: 67 | 68 | solution.solution(4, 4) 69 | 70 | Output: 71 | 72 | [[0], [1], [2], [3]] 73 | 74 | Input: 75 | 76 | solution.solution(5, 3) 77 | 78 | Output: 79 | 80 | [[0, 1, 2, 3, 4, 5], [0, 1, 2, 6, 7, 8], [0, 3, 4, 6, 7, 9], [1, 3, 5, 6, 8, 9], [2, 4, 5, 7, 8, 9]] 81 | 82 | -- Java cases -- 83 | 84 | Input: 85 | 86 | Solution.solution(2, 1) 87 | 88 | Output: 89 | 90 | [[0], [0]] 91 | 92 | Input: 93 | 94 | Solution.solution(5, 3) 95 | 96 | Output: 97 | 98 | [[0, 1, 2, 3, 4, 5], [0, 1, 2, 6, 7, 8], [0, 3, 4, 6, 7, 9], [1, 3, 5, 6, 8, 9], [2, 4, 5, 7, 8, 9]] 99 | 100 | Input: 101 | 102 | Solution.solution(4, 4) 103 | 104 | Output: 105 | 106 | [[0], [1], [2], [3]] -------------------------------------------------------------------------------- /level4/bringing-a-gun-to-a-guard-fight/src/Solution.java: -------------------------------------------------------------------------------- 1 | /// Source : Google FooBar 2 | /// Author : liuyubobobo 3 | /// Time : 2020-05-22 4 | 5 | import java.util.LinkedList; 6 | import java.util.TreeSet; 7 | import java.util.TreeMap; 8 | import java.util.Queue; 9 | 10 | 11 | /// BFS 12 | /// Time Complexity: O(x_dim * y_dim) 13 | /// Space Complexity: O(x_dim * y_dim) 14 | public class Solution { 15 | 16 | private static class Pair implements Comparable{ 17 | 18 | public int a, b; 19 | 20 | public Pair(int a, int b){ 21 | this.a = a; 22 | this.b = b; 23 | } 24 | 25 | public Pair(){ 26 | this(0, 0); 27 | } 28 | 29 | @Override 30 | public int compareTo(Pair another){ 31 | 32 | if(a == another.a) return b - another.b; 33 | return a - another.a; 34 | } 35 | 36 | @Override 37 | public boolean equals(Object o){ 38 | 39 | if(this == o) 40 | return true; 41 | 42 | if(o == null || o.getClass() != this.getClass()) 43 | return false; 44 | 45 | Pair another = (Pair)o; 46 | return a == another.a && b == another.b; 47 | } 48 | } 49 | 50 | private static int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 51 | 52 | public static int solution(int[] dimensions, int[] your_position, int[] guard_position, int distance) { 53 | 54 | int w = dimensions[0], h = dimensions[1]; 55 | 56 | TreeSet res = new TreeSet<>(); 57 | TreeMap suiside = new TreeMap<>(); 58 | TreeMap yourVisited = new TreeMap<>(); 59 | TreeMap guardVisited = new TreeMap<>(); 60 | 61 | Queue queue = new LinkedList<>(); 62 | if(disSquare(your_position, guard_position) > distance * distance) 63 | return 0; 64 | 65 | res.add(directions(your_position, guard_position)); 66 | queue.add(new Pair()); 67 | yourVisited.put(new Pair(), your_position); 68 | guardVisited.put(new Pair(), guard_position); 69 | 70 | while(!queue.isEmpty()){ 71 | Pair cur = queue.poll(); 72 | 73 | for(int[] d: dirs){ 74 | 75 | Pair next = new Pair(cur.a + d[0], cur.b + d[1]); 76 | if(guardVisited.containsKey(next)){ 77 | if(!yourVisited.containsKey(next)) throw new RuntimeException(); 78 | continue; 79 | } 80 | 81 | int[] newGuardPosition = { 82 | next.a == cur.a ? guardVisited.get(cur)[0] : 83 | next.a >= 0 ? 84 | (next.a % 2 == 1 ? next.a * w + w - guard_position[0] : next.a * w + guard_position[0]) : 85 | ((-next.a) % 2 == 1 ? -(-next.a - 1) * w - guard_position[0] : -(-next.a - 1) * w - ( w - guard_position[0])) 86 | , 87 | next.b == cur.b ? guardVisited.get(cur)[1] : 88 | next.b >= 0 ? 89 | (next.b % 2 == 1 ? next.b * h + h - guard_position[1] : next.b * h + guard_position[1]) : 90 | ((-next.b) % 2 == 1 ? -(-next.b - 1) * h - guard_position[1] : -(-next.b - 1) * h - ( h - guard_position[1])) 91 | }; 92 | 93 | int[] newYourPosition = { 94 | next.a == cur.a ? yourVisited.get(cur)[0] : 95 | next.a >= 0 ? 96 | (next.a % 2 == 1 ? next.a * w + w - your_position[0] : next.a * w + your_position[0]) : 97 | ((-next.a) % 2 == 1 ? -(-next.a - 1) * w - your_position[0] : -(-next.a - 1) * w - (w - your_position[0])) 98 | , 99 | next.b == cur.b ? yourVisited.get(cur)[1] : 100 | next.b >= 0 ? 101 | (next.b % 2 == 1 ? next.b * h + h - your_position[1] : next.b * h + your_position[1]) : 102 | ((-next.b) % 2 == 1 ? -(-next.b - 1) * h - your_position[1] : -(-next.b - 1) * h - (h - your_position[1])) 103 | }; 104 | 105 | guardVisited.put(next, newGuardPosition); 106 | yourVisited.put(next, newYourPosition); 107 | 108 | Pair tres2 = directions(your_position, newYourPosition); 109 | if(!suiside.containsKey(tres2)) 110 | suiside.put(tres2, newYourPosition); 111 | 112 | if(disSquare(your_position, newGuardPosition) <= distance * distance){ 113 | 114 | Pair tres1 = directions(your_position, newGuardPosition); 115 | 116 | if(suiside.containsKey(tres1) && disSquare(your_position, suiside.get(tres1)) <= disSquare(your_position, newGuardPosition)) 117 | continue; 118 | 119 | if(tres1.equals(tres2) && disSquare(your_position, newYourPosition) <= disSquare(your_position, newGuardPosition)) 120 | continue; 121 | 122 | res.add(tres1); 123 | queue.add(next); 124 | } 125 | } 126 | } 127 | return res.size(); 128 | } 129 | 130 | private static Pair directions(int[] a, int[] b){ 131 | 132 | int[] res = {b[0] - a[0], b[1] - a[1]}; 133 | 134 | if(res[0] == 0) 135 | res[1] = sign(res[1]); 136 | else if(res[1] == 0) 137 | res[0] = sign(res[0]); 138 | else{ 139 | int g = gcd(Math.abs(res[0]), Math.abs(res[1])); 140 | res[0] /= g; res[1] /= g; 141 | } 142 | return new Pair(res[0], res[1]); 143 | } 144 | 145 | private static int sign(int x){ 146 | return Integer.compare(x, 0); 147 | } 148 | 149 | private static int gcd(int x, int y){ 150 | if(x < y) return gcd(y, x); 151 | return y == 0 ? x : gcd(y, x % y); 152 | } 153 | 154 | private static int disSquare(int[] a, int[] b){ 155 | return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]); 156 | } 157 | 158 | public static void main(String[] args){ 159 | 160 | int[] dimensions1 = {3, 2}; 161 | int[] your_position1 = {1, 1}; 162 | int[] guard_position1 = {2, 1}; 163 | System.out.println(Solution.solution(dimensions1, your_position1, guard_position1, 4)); 164 | // 7 165 | 166 | int[] dimensions2 = {300, 275}; 167 | int[] your_position2 = {150, 150}; 168 | int[] guard_position2 = {185, 100}; 169 | System.out.println(Solution.solution(dimensions2, your_position2, guard_position2, 500)); 170 | // 9 171 | 172 | int[] dimensions3 = {2, 5}; 173 | int[] your_position3 = {1, 2}; 174 | int[] guard_position3 = {1, 4}; 175 | System.out.println(Solution.solution(dimensions3, your_position3, guard_position3, 11)); 176 | // 25? 27? 177 | // I'm not sure the correct ouput of this data 178 | // My algorithm gives 25 179 | 180 | int[] dimensions4 = {10, 10}; 181 | int[] your_position4 = {4, 4}; 182 | int[] guard_position4 = {3, 3}; 183 | System.out.println(Solution.solution(dimensions4, your_position4, guard_position4, 5000)); 184 | // 739323 185 | 186 | int[] dimensions5 = {23, 10}; 187 | int[] your_position5 = {6, 4}; 188 | int[] guard_position5 = {3, 2}; 189 | System.out.println(Solution.solution(dimensions5, your_position5, guard_position5, 23)); 190 | // 8 191 | } 192 | } 193 | --------------------------------------------------------------------------------