├── .gitignore ├── LICENSE ├── base64-encode ├── input.json └── java │ └── Base64Encode.java ├── binary-search ├── input.json ├── java │ └── BinarySearch.java ├── nodejs │ └── binary_search.js └── python │ └── binary_search.py ├── evaluate ├── input.json └── java │ └── Evaluate.java ├── insertion-sort ├── input.json └── java │ └── InsertionSort.java ├── lib └── java │ └── gson.jar ├── map-reduce ├── java │ └── MapReduce.java ├── map-input.json └── reduce-input.json ├── quick-sort ├── input.json └── java │ └── QuickSort.java ├── selection-sort ├── input.json └── java │ └── SelectionSort.java └── string-search ├── input.json └── java └── StringSearch.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | /bin/ 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /base64-encode/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "source": "AB", 4 | "result": "QUI=" 5 | }, 6 | { 7 | "source": "xyz", 8 | "result": "eHl6" 9 | }, 10 | { 11 | "source": "Hello, world!", 12 | "result": "SGVsbG8sIHdvcmxkIQ==" 13 | }, 14 | { 15 | "source": "\u4e2d\u6587\u6d4b\u8bd5", 16 | "result": "5Lit5paH5rWL6K+V" 17 | }, 18 | { 19 | "source": "\u00ff\u00fe\u00fd\u00fc", 20 | "result": "w7/DvsO9w7w=" 21 | } 22 | ] 23 | -------------------------------------------------------------------------------- /base64-encode/java/Base64Encode.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | 3 | import com.google.gson.Gson; 4 | 5 | public class Base64Encode { 6 | 7 | static final char[] BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); 8 | 9 | public static String base64Encode(byte[] input) { 10 | // DO NOT use JDK Base64.encode: 11 | int srcLength = input.length; 12 | int count = srcLength / 3; 13 | int paddings = srcLength % 3; 14 | int encLength = (count + (paddings == 0 ? 0 : 1)) * 4; 15 | char[] output = new char[encLength]; 16 | for (int i = 0; i < count; i++) { 17 | // encode every 3 bytes to 4 bytes: 18 | fill(input[i * 3], input[i * 3 + 1], input[i * 3 + 2], output, i * 4); 19 | } 20 | // padding: 21 | if (paddings == 1) { 22 | fill(input[input.length - 1], (byte) 0, (byte) 0, output, count * 4); 23 | output[count * 4 + 2] = '='; 24 | output[count * 4 + 3] = '='; 25 | } else if (paddings == 2) { 26 | fill(input[input.length - 2], input[input.length - 1], (byte) 0, output, count * 4); 27 | output[count * 4 + 3] = '='; 28 | } 29 | return new String(output); 30 | } 31 | 32 | static void fill(byte src1, byte src2, byte src3, char[] output, int offset) { 33 | int e1 = (src1 & 0xfc) >> 2; // 11111100 34 | int e2 = ((src1 & 0x03) << 4) | ((src2 & 0xf0) >> 4); // 11..11110000 35 | int e3 = ((src2 & 0x0f) << 2) | ((src3 & 0xc0) >> 6); // 1111..11000000 36 | int e4 = src3 & 0x3f; // 00111111 37 | output[offset] = BASE64_CHARS[e1]; 38 | output[offset + 1] = BASE64_CHARS[e2]; 39 | output[offset + 2] = BASE64_CHARS[e3]; 40 | output[offset + 3] = BASE64_CHARS[e4]; 41 | } 42 | 43 | public static void main(String[] args) throws Exception { 44 | Base64Input[] inputs = new Gson().fromJson(new FileReader("base64-encode/input.json"), Base64Input[].class); 45 | for (Base64Input input : inputs) { 46 | String r = base64Encode(input.source.getBytes("UTF-8")); 47 | System.out.println("base64Encode(\"" + input.source + "\") => " + r); 48 | if (!input.result.equals(r)) { 49 | throw new Exception("failed. expected = " + input.result + ", actual = " + r); 50 | } 51 | } 52 | } 53 | } 54 | 55 | class Base64Input { 56 | String source; 57 | String result; 58 | } 59 | -------------------------------------------------------------------------------- /binary-search/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "key": 44, 4 | "array": [9, 11, 27, 36, 41, 44, 64, 77, 78, 81], 5 | "result": 5 6 | }, 7 | { 8 | "key": 99, 9 | "array": [7, 13, 36, 64, 65, 68, 74, 77, 86, 99], 10 | "result": 9 11 | }, 12 | { 13 | "key": 47, 14 | "array": [0, 13, 24, 35, 47, 58, 66, 73, 75, 78], 15 | "result": 4 16 | }, 17 | { 18 | "key": 5, 19 | "array": [0, 17, 28, 38, 45, 56, 61, 76, 77, 99], 20 | "result": -1 21 | }, 22 | { 23 | "key": 48, 24 | "array": [14, 18, 22, 28, 48, 55, 60, 61, 97], 25 | "result": 4 26 | }, 27 | { 28 | "key": 82, 29 | "array": [82, 114, 133, 234, 238, 269, 279, 286, 303, 315, 320, 335, 377, 378, 401, 418, 420, 443], 30 | "result": 0 31 | }, 32 | { 33 | "key": 166, 34 | "array": [10, 68, 71, 73, 111, 126, 141, 154, 166, 168, 173, 185, 217, 251, 305, 397, 408, 472, 484, 496], 35 | "result": 8 36 | }, 37 | { 38 | "key": 493, 39 | "array": [9, 41, 49, 62, 100, 126, 131, 148, 182, 248, 254, 267, 312, 323, 342, 383, 384, 465, 487, 493], 40 | "result": 19 41 | }, 42 | { 43 | "key": 308, 44 | "array": [1, 6, 129, 145, 197, 199, 221, 223, 249, 264, 267, 309, 329, 335, 355, 366, 379, 439, 447, 463], 45 | "result": -1 46 | }, 47 | { 48 | "key": 405, 49 | "array": [59, 99, 104, 164, 171, 181, 184, 243, 246, 262, 292, 306, 333, 376, 405, 414, 431, 433, 472, 490], 50 | "result": 14 51 | } 52 | ] 53 | -------------------------------------------------------------------------------- /binary-search/java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | 3 | import com.google.gson.Gson; 4 | 5 | public class BinarySearch { 6 | 7 | public static int binarySearch(int key, int[] arr) { 8 | int lo = 0; 9 | int hi = arr.length - 1; 10 | while (lo <= hi) { 11 | int mid = lo + (hi - lo) / 2; 12 | if (key < arr[mid]) { 13 | hi = mid - 1; 14 | } else if (key > arr[mid]) { 15 | lo = mid + 1; 16 | } else { 17 | return mid; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | public static void main(String[] args) throws Exception { 24 | BinarySearchInput[] inputs = new Gson().fromJson(new FileReader("binary-search/input.json"), 25 | BinarySearchInput[].class); 26 | for (BinarySearchInput input : inputs) { 27 | int r = binarySearch(input.key, input.array); 28 | System.out.println("binarySearch(" + input.key + ", " + new Gson().toJson(input.array) + ") => " + r); 29 | if (input.result != r) { 30 | throw new Exception("failed. expected = " + input.result + ", actual = " + r); 31 | } 32 | } 33 | } 34 | 35 | } 36 | 37 | class BinarySearchInput { 38 | int key; 39 | int[] array; 40 | int result; 41 | } 42 | -------------------------------------------------------------------------------- /binary-search/nodejs/binary_search.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | function binarySearch(key, arr) { 4 | var 5 | mid, 6 | lo = 0, 7 | hi = arr.length - 1; 8 | while (lo <= hi) { 9 | mid = lo + Math.floor((hi - lo) / 2); 10 | if (key < arr[mid]) { 11 | hi = mid - 1; 12 | } else if (key > arr[mid]) { 13 | lo = mid + 1; 14 | } else { 15 | return mid; 16 | } 17 | } 18 | return -1; 19 | } 20 | 21 | function main() { 22 | var i, r, input, inputs = require('../input.json'); 23 | for (i=0; i ' + r) 27 | if (r !== input.result) { 28 | throw 'failed. expected = ' + JSON.stringify(input.result) + ', actual = ' + r; 29 | } 30 | } 31 | } 32 | 33 | main(); 34 | -------------------------------------------------------------------------------- /binary-search/python/binary_search.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os, json 4 | 5 | def binary_search(key, arr): 6 | lo = 0 7 | hi = len(arr) - 1 8 | while lo <= hi: 9 | mid = lo + (hi - lo) // 2; 10 | if key < arr[mid]: 11 | hi = mid - 1 12 | elif key > arr[mid]: 13 | lo = mid + 1 14 | else: 15 | return mid 16 | return -1 17 | 18 | def main(): 19 | with open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'input.json')) as f: 20 | for input in json.load(f): 21 | r = binary_search(input['key'], input['array']) 22 | print('binary_search(%s, %s) => %s' % (input['key'], input['array'], r)) 23 | if input['result'] != r: 24 | raise Error('failed. expected = %s, actual = %s' % (input['result'], r)) 25 | 26 | if __name__ == '__main__': 27 | main() 28 | -------------------------------------------------------------------------------- /evaluate/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "expression": "1 + 2", 4 | "result": 3 5 | }, 6 | { 7 | "expression": "1 + 2 * 5 - 3", 8 | "result": 8 9 | }, 10 | { 11 | "expression": "( 1 + 2 ) * ( 8 - 5 )", 12 | "result": 9 13 | }, 14 | { 15 | "expression": "5 + ( 9 - 1 ) / ( 2 * 2 )", 16 | "result": 7 17 | }, 18 | { 19 | "expression": "( 1 + ( 3 + 9 ) / ( 6 - 2 ) ) * 3", 20 | "result": 12 21 | }, 22 | { 23 | "expression": "( 1 + ( ( 3 + 9 ) ) / ( 6 - 2 ) ) * 3", 24 | "result": 12 25 | } 26 | ] 27 | -------------------------------------------------------------------------------- /evaluate/java/Evaluate.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | import java.util.Stack; 3 | 4 | import com.google.gson.Gson; 5 | 6 | public class Evaluate { 7 | 8 | static final int ADD = 0; 9 | static final int SUB = 1; 10 | static final int MUL = 2; 11 | static final int DIV = 3; 12 | static final int LT = 4; 13 | static final int RT = 5; 14 | 15 | static final int[][] priority = new int[][] { 16 | // + - * / 17 | { 1, 1, 0, 0 }, // + 18 | { 1, 1, 0, 0 }, // - 19 | { 1, 1, 1, 1 }, // * 20 | { 1, 1, 1, 1 }, // / 21 | }; 22 | 23 | static boolean isHigher(int op1, int op2) { 24 | return priority[op1][op2] > 0; 25 | } 26 | 27 | static int token2op(String token) { 28 | if ("+".equals(token)) { 29 | return ADD; 30 | } 31 | if ("-".equals(token)) { 32 | return SUB; 33 | } 34 | if ("*".equals(token)) { 35 | return MUL; 36 | } 37 | if ("/".equals(token)) { 38 | return DIV; 39 | } 40 | if ("(".equals(token)) { 41 | return LT; 42 | } 43 | if (")".equals(token)) { 44 | return RT; 45 | } 46 | return -1; 47 | } 48 | 49 | static int calculate(int op, int n1, int n2) { 50 | if (op == ADD) { 51 | return n1 + n2; 52 | } 53 | if (op == SUB) { 54 | return n1 - n2; 55 | } 56 | if (op == MUL) { 57 | return n1 * n2; 58 | } 59 | if (op == DIV) { 60 | return n1 / n2; 61 | } 62 | throw new IllegalArgumentException("Invalid operator: " + op); 63 | } 64 | 65 | public static int evaluate(String[] tokens) { 66 | Stack ops = new Stack(); 67 | Stack vals = new Stack(); 68 | for (String token : tokens) { 69 | int op = token2op(token); 70 | if (op != (-1)) { 71 | if (op == LT) { 72 | // always push '(': 73 | ops.push(op); 74 | } else if (op == RT) { 75 | // pop until find '(': 76 | int topOp; 77 | while ((topOp = ops.pop()) != LT) { 78 | int n2 = vals.pop(); 79 | int n1 = vals.pop(); 80 | vals.push(calculate(topOp, n1, n2)); 81 | } 82 | } else { 83 | // operator: 84 | // pop if top op > current op: 85 | while (!ops.isEmpty() && ops.peek() != LT && isHigher(ops.peek(), op)) { 86 | int topOp = ops.pop(); 87 | int n2 = vals.pop(); 88 | int n1 = vals.pop(); 89 | vals.push(calculate(topOp, n1, n2)); 90 | } 91 | ops.push(op); 92 | } 93 | } else { 94 | // number: 95 | vals.push(Integer.parseInt(token)); 96 | } 97 | } 98 | while (!ops.isEmpty()) { 99 | int n2 = vals.pop(); 100 | int n1 = vals.pop(); 101 | vals.push(calculate(ops.pop(), n1, n2)); 102 | } 103 | return vals.pop(); 104 | } 105 | 106 | public static void main(String[] args) throws Exception { 107 | EvaluateInput[] inputs = new Gson().fromJson(new FileReader("evaluate/input.json"), EvaluateInput[].class); 108 | for (EvaluateInput input : inputs) { 109 | int r = evaluate(input.expression.split("\\s+")); 110 | System.out.println(input.expression + " => " + r); 111 | if (input.result != r) { 112 | throw new Exception("failed. expected = " + input.result + ", actual = " + r); 113 | } 114 | } 115 | } 116 | } 117 | 118 | class EvaluateInput { 119 | String expression; 120 | int result; 121 | } 122 | -------------------------------------------------------------------------------- /insertion-sort/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "array": [2, 4, 16, 6, 15, 1, 4, 19, 3, 21], 4 | "result": [1, 2, 3, 4, 4, 6, 15, 16, 19, 21] 5 | }, 6 | { 7 | "array": [28, 0, 28, 27, 1, 0, 24, 6, 4, 4], 8 | "result": [0, 0, 1, 4, 4, 6, 24, 27, 28, 28] 9 | }, 10 | { 11 | "array": [20, 10, 7, 21, 9, 13, 12, 20, 17, 14], 12 | "result": [7, 9, 10, 12, 13, 14, 17, 20, 20, 21] 13 | }, 14 | { 15 | "array": [22, 20, 23, 19, 18, 13, 3, 1, 1, 0], 16 | "result": [0, 1, 1, 3, 13, 18, 19, 20, 22, 23] 17 | }, 18 | { 19 | "array": [12, 14, 6, 14, 8, 16, 9, 14, 0, 3], 20 | "result": [0, 3, 6, 8, 9, 12, 14, 14, 14, 16] 21 | }, 22 | { 23 | "array": [18, 17, 16, 7, 16, 25, 11, 20, 23, 7], 24 | "result": [7, 7, 11, 16, 16, 17, 18, 20, 23, 25] 25 | }, 26 | { 27 | "array": [27, 17, 9, 10, 15, 21, 25, 7, 19, 19], 28 | "result": [7, 9, 10, 15, 17, 19, 19, 21, 25, 27] 29 | }, 30 | { 31 | "array": [7, 4, 19, 20, 25, 15, 0, 22, 4, 28], 32 | "result": [0, 4, 4, 7, 15, 19, 20, 22, 25, 28] 33 | }, 34 | { 35 | "array": [11, 14, 29, 1, 22, 9, 9, 19, 29, 27], 36 | "result": [1, 9, 9, 11, 14, 19, 22, 27, 29, 29] 37 | }, 38 | { 39 | "array": [21, 14, 22, 16, 6, 5, 15, 22, 21, 11], 40 | "result": [5, 6, 11, 14, 15, 16, 21, 21, 22, 22] 41 | } 42 | ] -------------------------------------------------------------------------------- /insertion-sort/java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | import java.util.Objects; 3 | 4 | import com.google.gson.Gson; 5 | 6 | public class InsertionSort { 7 | 8 | public static void sort(int[] array) { 9 | for (int i = 1; i < array.length; i++) { 10 | for (int j = i; j > 0 && array[j] < array[j - 1]; j--) { 11 | int tmp = array[j]; 12 | array[j] = array[j - 1]; 13 | array[j - 1] = tmp; 14 | } 15 | } 16 | } 17 | 18 | public static void main(String[] args) throws Exception { 19 | InsertionSortInput[] inputs = new Gson().fromJson(new FileReader("insertion-sort/input.json"), 20 | InsertionSortInput[].class); 21 | for (InsertionSortInput input : inputs) { 22 | int[] array = new int[input.array.length]; 23 | System.arraycopy(input.array, 0, array, 0, array.length); 24 | System.out.println("original => " + new Gson().toJson(array)); 25 | sort(array); 26 | System.out.println("sorted => " + new Gson().toJson(array)); 27 | if (!Objects.deepEquals(array, input.result)) { 28 | throw new Exception("failed. expected = " + new Gson().toJson(input.result) + ", actual = " 29 | + new Gson().toJson(array)); 30 | } 31 | } 32 | } 33 | } 34 | 35 | class InsertionSortInput { 36 | int[] array; 37 | int[] result; 38 | } -------------------------------------------------------------------------------- /lib/java/gson.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/michaelliao/algorithms/7a81c6c10047a1466b95b8782ad1ad75af742b6f/lib/java/gson.jar -------------------------------------------------------------------------------- /map-reduce/java/MapReduce.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | import java.util.Objects; 3 | 4 | import com.google.gson.Gson; 5 | 6 | public class MapReduce { 7 | 8 | public static int[] map(Mapper mapper, int[] array) { 9 | int[] results = new int[array.length]; 10 | for (int i = 0; i < array.length; i++) { 11 | results[i] = mapper.apply(array[i]); 12 | } 13 | return results; 14 | } 15 | 16 | public static int reduce(Reducer reducer, int[] array) { 17 | int r = array[0]; 18 | for (int i = 1; i < array.length; i++) { 19 | r = reducer.apply(r, array[i]); 20 | } 21 | return r; 22 | } 23 | 24 | public static void main(String[] args) throws Exception { 25 | // test map: 26 | MapInput[] mapInputs = new Gson().fromJson(new FileReader("map-reduce/map-input.json"), MapInput[].class); 27 | for (MapInput mapInput : mapInputs) { 28 | int[] r = map(x -> { 29 | return x * x; 30 | } , mapInput.array); 31 | System.out.println("map(fn, " + new Gson().toJson(mapInput.array) + ") => " + new Gson().toJson(r)); 32 | if (!Objects.deepEquals(r, mapInput.result)) { 33 | throw new Exception("failed. expected = " + new Gson().toJson(mapInput.result) + ", actual = " 34 | + new Gson().toJson(r)); 35 | } 36 | } 37 | // test reduce: 38 | ReduceInput[] reduceInputs = new Gson().fromJson(new FileReader("map-reduce/reduce-input.json"), 39 | ReduceInput[].class); 40 | for (ReduceInput reduceInput : reduceInputs) { 41 | int result = reduce((r, x) -> { 42 | return r + x * x; 43 | } , reduceInput.array); 44 | System.out.println("reduce(fn, " + new Gson().toJson(reduceInput.array) + ") => " + result); 45 | if (result != reduceInput.result) { 46 | throw new Exception("failed. expected = " + reduceInput.result + ", actual = " + result); 47 | } 48 | } 49 | } 50 | } 51 | 52 | @FunctionalInterface 53 | interface Mapper { 54 | int apply(int x); 55 | } 56 | 57 | @FunctionalInterface 58 | interface Reducer { 59 | int apply(int r, int x); 60 | } 61 | 62 | class MapInput { 63 | int[] array; 64 | int[] result; 65 | } 66 | 67 | class ReduceInput { 68 | int[] array; 69 | int result; 70 | } 71 | -------------------------------------------------------------------------------- /map-reduce/map-input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "array": [9, 11, 27, 36, 41, 44, 64, 77, 78, 81], 4 | "result": [81, 121, 729, 1296, 1681, 1936, 4096, 5929, 6084, 6561] 5 | }, 6 | { 7 | "array": [7, 13, 36, 64, 65, 68, 74, 77, 86, 99], 8 | "result": [49, 169, 1296, 4096, 4225, 4624, 5476, 5929, 7396, 9801] 9 | }, 10 | { 11 | "array": [0, 13, 24, 35, 47, 58, 66, 73, 75, 78], 12 | "result": [0, 169, 576, 1225, 2209, 3364, 4356, 5329, 5625, 6084] 13 | }, 14 | { 15 | "array": [0, 17, 28, 38, 45, 56, 61, 76, 77, 99], 16 | "result": [0, 289, 784, 1444, 2025, 3136, 3721, 5776, 5929, 9801] 17 | }, 18 | { 19 | "array": [14, 18, 22, 28, 48, 55, 60, 61, 97], 20 | "result": [196, 324, 484, 784, 2304, 3025, 3600, 3721, 9409] 21 | } 22 | ] 23 | -------------------------------------------------------------------------------- /map-reduce/reduce-input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "array": [9, 11, 27, 36, 41, 44, 64, 77, 78, 81], 4 | "result": 28442 5 | }, 6 | { 7 | "array": [7, 13, 36, 64, 65, 68, 74, 77, 86, 99], 8 | "result": 43019 9 | }, 10 | { 11 | "array": [0, 13, 24, 35, 47, 58, 66, 73, 75, 78], 12 | "result": 28937 13 | }, 14 | { 15 | "array": [0, 17, 28, 38, 45, 56, 61, 76, 77, 99], 16 | "result": 32905 17 | }, 18 | { 19 | "array": [14, 18, 22, 28, 48, 55, 60, 61, 97], 20 | "result": 23665 21 | } 22 | ] 23 | -------------------------------------------------------------------------------- /quick-sort/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "array": [2, 4, 16, 6, 15, 1, 4, 19, 3, 21], 4 | "result": [1, 2, 3, 4, 4, 6, 15, 16, 19, 21] 5 | }, 6 | { 7 | "array": [28, 0, 28, 27, 1, 0, 24, 6, 4, 4], 8 | "result": [0, 0, 1, 4, 4, 6, 24, 27, 28, 28] 9 | }, 10 | { 11 | "array": [20, 10, 7, 21, 9, 13, 12, 20, 17, 14], 12 | "result": [7, 9, 10, 12, 13, 14, 17, 20, 20, 21] 13 | }, 14 | { 15 | "array": [22, 20, 23, 19, 18, 13, 3, 1, 1, 0], 16 | "result": [0, 1, 1, 3, 13, 18, 19, 20, 22, 23] 17 | }, 18 | { 19 | "array": [12, 14, 6, 14, 8, 16, 9, 14, 0, 3], 20 | "result": [0, 3, 6, 8, 9, 12, 14, 14, 14, 16] 21 | }, 22 | { 23 | "array": [18, 17, 16, 7, 16, 25, 11, 20, 23, 7], 24 | "result": [7, 7, 11, 16, 16, 17, 18, 20, 23, 25] 25 | }, 26 | { 27 | "array": [27, 17, 9, 10, 15, 21, 25, 7, 19, 19], 28 | "result": [7, 9, 10, 15, 17, 19, 19, 21, 25, 27] 29 | }, 30 | { 31 | "array": [7, 4, 19, 20, 25, 15, 0, 22, 4, 28], 32 | "result": [0, 4, 4, 7, 15, 19, 20, 22, 25, 28] 33 | }, 34 | { 35 | "array": [11, 14, 29, 1, 22, 9, 9, 19, 29, 27], 36 | "result": [1, 9, 9, 11, 14, 19, 22, 27, 29, 29] 37 | }, 38 | { 39 | "array": [21, 14, 22, 16, 6, 5, 15, 22, 21, 11], 40 | "result": [5, 6, 11, 14, 15, 16, 21, 21, 22, 22] 41 | } 42 | ] -------------------------------------------------------------------------------- /quick-sort/java/QuickSort.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | import java.util.Objects; 3 | 4 | import com.google.gson.Gson; 5 | 6 | public class QuickSort { 7 | 8 | static void sort(int[] array, int lo, int hi) { 9 | if (lo >= hi) { 10 | return; 11 | } 12 | int i = lo; 13 | int j = hi + 1; 14 | int base = array[lo]; 15 | while (true) { 16 | while (array[++i] < base && i < hi); 17 | while (base < array[--j] && lo < j); 18 | if (i >= j) { 19 | break; 20 | } 21 | int tmp = array[i]; 22 | array[i] = array[j]; 23 | array[j] = tmp; 24 | } 25 | array[lo] = array[j]; 26 | array[j] = base; 27 | // sort left part: 28 | sort(array, lo, j - 1); 29 | // sort right part: 30 | sort(array, j + 1, hi); 31 | } 32 | 33 | public static void sort(int[] array) { 34 | sort(array, 0, array.length - 1); 35 | } 36 | 37 | public static void main(String[] args) throws Exception { 38 | QuickSortInput[] inputs = new Gson().fromJson(new FileReader("quick-sort/input.json"), QuickSortInput[].class); 39 | for (QuickSortInput input : inputs) { 40 | int[] array = new int[input.array.length]; 41 | System.arraycopy(input.array, 0, array, 0, array.length); 42 | System.out.println("original => " + new Gson().toJson(array)); 43 | sort(array); 44 | System.out.println("sorted => " + new Gson().toJson(array)); 45 | if (!Objects.deepEquals(array, input.result)) { 46 | throw new Exception("failed. expected = " + new Gson().toJson(input.result) + ", actual = " 47 | + new Gson().toJson(array)); 48 | } 49 | } 50 | } 51 | } 52 | 53 | class QuickSortInput { 54 | int[] array; 55 | int[] result; 56 | } -------------------------------------------------------------------------------- /selection-sort/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "array": [2, 4, 16, 6, 15, 1, 4, 19, 3, 21], 4 | "result": [1, 2, 3, 4, 4, 6, 15, 16, 19, 21] 5 | }, 6 | { 7 | "array": [28, 0, 28, 27, 1, 0, 24, 6, 4, 4], 8 | "result": [0, 0, 1, 4, 4, 6, 24, 27, 28, 28] 9 | }, 10 | { 11 | "array": [20, 10, 7, 21, 9, 13, 12, 20, 17, 14], 12 | "result": [7, 9, 10, 12, 13, 14, 17, 20, 20, 21] 13 | }, 14 | { 15 | "array": [22, 20, 23, 19, 18, 13, 3, 1, 1, 0], 16 | "result": [0, 1, 1, 3, 13, 18, 19, 20, 22, 23] 17 | }, 18 | { 19 | "array": [12, 14, 6, 14, 8, 16, 9, 14, 0, 3], 20 | "result": [0, 3, 6, 8, 9, 12, 14, 14, 14, 16] 21 | }, 22 | { 23 | "array": [18, 17, 16, 7, 16, 25, 11, 20, 23, 7], 24 | "result": [7, 7, 11, 16, 16, 17, 18, 20, 23, 25] 25 | }, 26 | { 27 | "array": [27, 17, 9, 10, 15, 21, 25, 7, 19, 19], 28 | "result": [7, 9, 10, 15, 17, 19, 19, 21, 25, 27] 29 | }, 30 | { 31 | "array": [7, 4, 19, 20, 25, 15, 0, 22, 4, 28], 32 | "result": [0, 4, 4, 7, 15, 19, 20, 22, 25, 28] 33 | }, 34 | { 35 | "array": [11, 14, 29, 1, 22, 9, 9, 19, 29, 27], 36 | "result": [1, 9, 9, 11, 14, 19, 22, 27, 29, 29] 37 | }, 38 | { 39 | "array": [21, 14, 22, 16, 6, 5, 15, 22, 21, 11], 40 | "result": [5, 6, 11, 14, 15, 16, 21, 21, 22, 22] 41 | } 42 | ] -------------------------------------------------------------------------------- /selection-sort/java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | import java.util.Objects; 3 | 4 | import com.google.gson.Gson; 5 | 6 | public class SelectionSort { 7 | 8 | public static void sort(int[] array) { 9 | for (int i = 0; i < array.length; i++) { 10 | // swap the array[i] with min(array[i+1:]) 11 | int min = i; 12 | for (int j = i + 1; j < array.length; j++) { 13 | if (array[min] > array[j]) { 14 | min = j; 15 | } 16 | } 17 | // swap a[i] and a[min]: 18 | int tmp = array[i]; 19 | array[i] = array[min]; 20 | array[min] = tmp; 21 | } 22 | } 23 | 24 | public static void main(String[] args) throws Exception { 25 | SelectionSortInput[] inputs = new Gson().fromJson(new FileReader("selection-sort/input.json"), 26 | SelectionSortInput[].class); 27 | for (SelectionSortInput input : inputs) { 28 | int[] array = new int[input.array.length]; 29 | System.arraycopy(input.array, 0, array, 0, array.length); 30 | System.out.println("original => " + new Gson().toJson(array)); 31 | sort(array); 32 | System.out.println("sorted => " + new Gson().toJson(array)); 33 | if (!Objects.deepEquals(array, input.result)) { 34 | throw new Exception("failed. expected = " + new Gson().toJson(input.result) + ", actual = " 35 | + new Gson().toJson(array)); 36 | } 37 | } 38 | } 39 | } 40 | 41 | class SelectionSortInput { 42 | int[] array; 43 | int[] result; 44 | } 45 | -------------------------------------------------------------------------------- /string-search/input.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "source": "the quick brown fox jumps over the lazy dog", 4 | "target": "quick", 5 | "result": 4 6 | }, 7 | { 8 | "source": "the quick brown fox jumps over the lazy dog", 9 | "target": "lazy dog", 10 | "result": 35 11 | }, 12 | { 13 | "source": "the quick brown fox jumps over the lazy dog", 14 | "target": "the", 15 | "result": 0 16 | }, 17 | { 18 | "source": "the quick brown fox jumps over the lazy dog", 19 | "target": "jumped", 20 | "result": -1 21 | }, 22 | { 23 | "source": "the quick brown fox jumps over the lazy dog", 24 | "target": "the lazy", 25 | "result": 31 26 | } 27 | ] -------------------------------------------------------------------------------- /string-search/java/StringSearch.java: -------------------------------------------------------------------------------- 1 | import java.io.FileReader; 2 | 3 | import com.google.gson.Gson; 4 | 5 | public class StringSearch { 6 | 7 | public static int search(String source, String target) { 8 | // DO NOT use JDK String.indexOf(): 9 | char[] src = source.toCharArray(); 10 | char[] sub = target.toCharArray(); 11 | return source.indexOf(target); 12 | } 13 | 14 | public static void main(String[] args) throws Exception { 15 | StringSearchInput[] inputs = new Gson().fromJson(new FileReader("string-search/input.json"), 16 | StringSearchInput[].class); 17 | for (StringSearchInput input : inputs) { 18 | int r = search(input.source, input.target); 19 | System.out.println("search(\"" + input.source + "\", \"" + input.target + "\") => " + r); 20 | if (input.result != r) { 21 | throw new Exception("failed. expected = " + input.result + ", actual = " + r); 22 | } 23 | } 24 | } 25 | } 26 | 27 | class StringSearchInput { 28 | String source; 29 | String target; 30 | int result; 31 | } 32 | --------------------------------------------------------------------------------