├── .gitignore ├── LICENSE ├── README.md ├── go └── interview.go ├── interviewcodecpp ├── interviewcodecpp.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcuserdata │ │ │ └── sam.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── sam.xcuserdatad │ │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ │ └── xcschemes │ │ ├── interviewcodecpp.xcscheme │ │ └── xcschememanagement.plist └── interviewcodecpp │ ├── entity.h │ └── main.cpp ├── interviewcodeswift ├── interviewcode.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcuserdata │ │ │ └── sam.xcuserdatad │ │ │ ├── UserInterfaceState.xcuserstate │ │ │ └── WorkspaceSettings.xcsettings │ └── xcuserdata │ │ └── sam.xcuserdatad │ │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ │ └── xcschemes │ │ ├── interviewcode.xcscheme │ │ └── xcschememanagement.plist └── interviewcode │ └── main.swift ├── javascript ├── index.js └── package.json ├── pom.xml ├── python └── interviewcode.py ├── rust ├── Cargo.lock ├── Cargo.toml ├── benchmarks_jemalloc │ ├── Cargo.toml │ ├── benches │ │ └── criterion_benchmark.rs │ └── src │ │ └── lib.rs ├── benchmarks_system │ ├── Cargo.toml │ ├── benches │ │ └── criterion_benchmark.rs │ └── src │ │ └── lib.rs └── unicode_test │ ├── Cargo.toml │ └── src │ ├── benchmark_base.rs │ └── lib.rs └── src ├── main └── java │ ├── interview │ ├── ArrayScan.java │ ├── BinarySearchSort.java │ ├── BinaryTree.java │ ├── Classic.java │ ├── Entity.java │ ├── HashMapScan.java │ ├── InsertionSort.java │ ├── LinkedListEntities.java │ ├── OptimizedClassic.java │ ├── OptimizedClassicWithCodePoints.java │ ├── Renderer.java │ ├── StringBuilderReplace.java │ ├── StringBuilderReplaceWithCodePoints.java │ ├── StringBuilderReplaceWithCodePointsAlreadySorted.java │ ├── StringReplacement.java │ └── Tree.java │ └── interviewkotlin │ └── KotlinStringBuilderReplaceWithCodePoints.kt └── test └── java └── interview ├── RendererBenchmarkTest.java ├── RendererTest.java └── example.json /.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 | 14 | .DS_Store 15 | .idea/ 16 | interviewcode.iml 17 | *~ 18 | target 19 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Interview Code 2 | 3 | At Twitter I often asked a simple question, render a tweet given the text and an unordered list of its entities (hashtags, URLs, @mentions). Each 4 | entity is represented by the replacement text, a start index and an end index. The classic solution is to sort the 5 | list of entities by their start index and build up the solution by iterating over the list grabbing text from the 6 | tweet and text from the replacement as you go. It was surprising that there were many people that could not get that 7 | far. If people made mistakes I would ask them to describe 4 unit tests they would write and I would tell them if 8 | those tests would fail or pass. One of the most difficult to write solutions was only described by a candidate, I 9 | later wrote BinaryTree to see how it did and it was pretty good relative to the Classic solution. However, it is 10 | painfully complicated and it took a while to get it to pass the tests. 11 | 12 | Since I don't think that anyone else at Twitter is currently using this question and I am unlikely to use it again, 13 | I thought it would be interesting to share it. One of the oddities of the question is that it is almost impossible 14 | to get right because no one ever asks what the indexes in the entities represent. In the API they are indexes into 15 | codepoints in the original tweet text. Many languages require very special handling of codepoints vs unicode vs 16 | ascii text. The solutions were universally focused on the default string behavior of the language they decided to 17 | write them in. The worst solution of the bunch, StringReplacement, was by far the most popular, sadly using that one 18 | at scale would be devastating. If someone got that far with a correct solution, we then would talk about optimizations 19 | you might perform when you need to do billions of them a day. 20 | 21 | I would love to see other solutions if you have a novel one. 22 | 23 | There is a rust implementation that has been heavily modified by a better Rust programmer than I. It is not quite apples to apples but it shows that you can get good performance out of it. In the Java case you can see that the JIT gets a pretty good workout as it optimizes. Another thing to note is just how slow processing UNICODE (with supplementary characters) is vs good old ascii (or even UNICODE-16). 24 | 25 | # Java Results 26 | 27 | ``` 28 | Running interview.RendererBenchmarkTest 29 | Classic: 1748 ns/op 30 | Classic: 1662 ns/op 31 | Classic: 1218 ns/op 32 | Classic: 909 ns/op 33 | Classic: 892 ns/op 34 | Memory: Classic: 1538 bytes/op 35 | Tree: 1037 ns/op 36 | Tree: 912 ns/op 37 | Tree: 924 ns/op 38 | Tree: 874 ns/op 39 | Tree: 940 ns/op 40 | Memory: Tree: 1206 bytes/op 41 | OptimizedClassic: 739 ns/op 42 | OptimizedClassic: 689 ns/op 43 | OptimizedClassic: 671 ns/op 44 | OptimizedClassic: 648 ns/op 45 | OptimizedClassic: 611 ns/op 46 | Memory: OptimizedClassic: 634 bytes/op 47 | OptimizedClassicWithCodePoints: 875 ns/op 48 | OptimizedClassicWithCodePoints: 899 ns/op 49 | OptimizedClassicWithCodePoints: 953 ns/op 50 | OptimizedClassicWithCodePoints: 931 ns/op 51 | OptimizedClassicWithCodePoints: 902 ns/op 52 | Memory: OptimizedClassicWithCodePoints: 676 bytes/op 53 | BinaryTree: 941 ns/op 54 | BinaryTree: 794 ns/op 55 | BinaryTree: 838 ns/op 56 | BinaryTree: 836 ns/op 57 | BinaryTree: 863 ns/op 58 | Memory: BinaryTree: 1332 bytes/op 59 | LinkedListEntities: 1231 ns/op 60 | LinkedListEntities: 1104 ns/op 61 | LinkedListEntities: 1074 ns/op 62 | LinkedListEntities: 1495 ns/op 63 | LinkedListEntities: 1115 ns/op 64 | Memory: LinkedListEntities: 1140 bytes/op 65 | InsertionSort: 862 ns/op 66 | InsertionSort: 761 ns/op 67 | InsertionSort: 707 ns/op 68 | InsertionSort: 682 ns/op 69 | InsertionSort: 700 ns/op 70 | Memory: InsertionSort: 1057 bytes/op 71 | BinarySearchSort: 883 ns/op 72 | BinarySearchSort: 792 ns/op 73 | BinarySearchSort: 807 ns/op 74 | BinarySearchSort: 777 ns/op 75 | BinarySearchSort: 855 ns/op 76 | Memory: BinarySearchSort: 1239 bytes/op 77 | StringReplacement: 1872 ns/op 78 | StringReplacement: 1790 ns/op 79 | StringReplacement: 1778 ns/op 80 | StringReplacement: 1857 ns/op 81 | StringReplacement: 1786 ns/op 82 | Memory: StringReplacement: 6740 bytes/op 83 | StringBuilderReplace: 701 ns/op 84 | StringBuilderReplace: 680 ns/op 85 | StringBuilderReplace: 724 ns/op 86 | StringBuilderReplace: 701 ns/op 87 | StringBuilderReplace: 673 ns/op 88 | Memory: StringBuilderReplace: 981 bytes/op 89 | HashMapScan: 1500 ns/op 90 | HashMapScan: 1563 ns/op 91 | HashMapScan: 1463 ns/op 92 | HashMapScan: 1518 ns/op 93 | HashMapScan: 1510 ns/op 94 | Memory: HashMapScan: 777 bytes/op 95 | ArrayScan: 712 ns/op 96 | ArrayScan: 683 ns/op 97 | ArrayScan: 668 ns/op 98 | ArrayScan: 665 ns/op 99 | ArrayScan: 683 ns/op 100 | Memory: ArrayScan: 1003 bytes/op 101 | ``` 102 | 103 | # Rust Results 104 | 105 | ``` 106 | interviewcode sam$ CARGO_INCREMENTAL="0" cargo bench 107 | Running target/release/interviewcode-d8a656227704114f 108 | 109 | running 6 tests 110 | test rendertest::correctness ... ignored 111 | test rendertest::correctness_ascii ... ignored 112 | test rendertest::correctness_chars ... ignored 113 | test rendertest::bench_replacement ... bench: 1,053 ns/iter (+/- 404) 114 | test rendertest::bench_replacement_ascii ... bench: 215 ns/iter (+/- 93) 115 | test rendertest::bench_replacement_chars ... bench: 604 ns/iter (+/- 250) 116 | 117 | test result: ok. 0 passed; 0 failed; 3 ignored; 3 measured 118 | ``` 119 | -------------------------------------------------------------------------------- /go/interview.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math/rand" 5 | "sort" 6 | "strconv" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | var text string = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 12 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!" 13 | 14 | func contains(s []int, e int) bool { 15 | for _, a := range s { 16 | if a == e { 17 | return true 18 | } 19 | } 20 | return false 21 | } 22 | 23 | type Entity struct { 24 | start int 25 | end int 26 | html string 27 | } 28 | 29 | func testEntities() map[Entity]bool { 30 | entities := make(map[Entity]bool) 31 | entities[Entity{25, 32, "<#mobile>"}] = true 32 | entities[Entity{33, 42, "<#startups>"}] = true 33 | entities[Entity{46, 51, "<#OF12>"}] = true 34 | entities[Entity{82, 102, ""}] = true 35 | entities[Entity{103, 110, "<@TiEcon>"}] = true 36 | entities[Entity{111, 127, "<@sv_entrepreneur>"}] = true 37 | entities[Entity{128, 132, "<@500>"}] = true 38 | return entities 39 | } 40 | 41 | 42 | func createEntityList() []map[Entity]bool { 43 | length := len(text) 44 | entitiesList := make([]map[Entity]bool, 1000) 45 | for i := 0; i < 1000; i++ { 46 | entities := make(map[Entity]bool) 47 | total := rand.Intn(10) 48 | indices := make([]int, total * 2) 49 | for j := 0; j < total * 2; j++ { 50 | var next int 51 | for { 52 | next = rand.Intn(length) 53 | if !contains(indices, next) { 54 | indices[j] = next 55 | break 56 | } 57 | } 58 | } 59 | sort.Ints(indices) 60 | for j := 0; j < total; j++ { 61 | start := indices[j*2] 62 | end := indices[j*2 + 1] 63 | length := end - start; 64 | sb := "" 65 | for k := 0; k < length; k++ { 66 | sb += "XX" 67 | } 68 | entities[Entity{start, end, sb}] = true 69 | } 70 | entitiesList[i] = entities 71 | } 72 | return entitiesList 73 | } 74 | 75 | func render(text string, entities map[Entity]bool) string { 76 | keys := make([]Entity, 0, len(entities)) 77 | for k := range entities { 78 | keys = append(keys, k) 79 | } 80 | sort.Slice(keys, func(o1 int, o2 int) bool { 81 | if keys[o1].start < keys[o2].start { 82 | return true 83 | } 84 | return false 85 | }) 86 | sb := strings.Builder{} 87 | sb.Grow(len(text) * 2) 88 | pos := 0 89 | for i := range keys { 90 | sb.WriteString(text[pos : keys[i].start]) 91 | sb.WriteString(keys[i].html) 92 | pos = keys[i].end 93 | } 94 | sb.WriteString(text[pos:]) 95 | return sb.String() 96 | } 97 | 98 | func main() { 99 | result := render(text, testEntities()) 100 | println(result) 101 | println(result == "Attend to hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, " + 102 | " <@TiEcon> <@sv_entrepreneur> <@500>!") 103 | 104 | entitiesList := createEntityList() 105 | 106 | for i := 0; i < 10; i++ { 107 | start := time.Now().UnixNano() 108 | total := 1000000 109 | for j := 0; j < total; j++ { 110 | render(text, entitiesList[j % 1000]) 111 | } 112 | end := time.Now().UnixNano() 113 | diff := (end - start) 114 | nanos := int64(diff / int64(total)) 115 | println(strconv.FormatInt(nanos, 10) + " ns/render") 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 22F2ADC91E2965100096E2D7 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 22F2ADC81E2965100096E2D7 /* main.cpp */; }; 11 | /* End PBXBuildFile section */ 12 | 13 | /* Begin PBXCopyFilesBuildPhase section */ 14 | 22F2ADC31E2965100096E2D7 /* CopyFiles */ = { 15 | isa = PBXCopyFilesBuildPhase; 16 | buildActionMask = 2147483647; 17 | dstPath = /usr/share/man/man1/; 18 | dstSubfolderSpec = 0; 19 | files = ( 20 | ); 21 | runOnlyForDeploymentPostprocessing = 1; 22 | }; 23 | /* End PBXCopyFilesBuildPhase section */ 24 | 25 | /* Begin PBXFileReference section */ 26 | 22F2ADC51E2965100096E2D7 /* interviewcodecpp */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = interviewcodecpp; sourceTree = BUILT_PRODUCTS_DIR; }; 27 | 22F2ADC81E2965100096E2D7 /* main.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = ""; }; 28 | 22F2ADCF1E2965B50096E2D7 /* entity.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = entity.h; sourceTree = ""; }; 29 | /* End PBXFileReference section */ 30 | 31 | /* Begin PBXFrameworksBuildPhase section */ 32 | 22F2ADC21E2965100096E2D7 /* Frameworks */ = { 33 | isa = PBXFrameworksBuildPhase; 34 | buildActionMask = 2147483647; 35 | files = ( 36 | ); 37 | runOnlyForDeploymentPostprocessing = 0; 38 | }; 39 | /* End PBXFrameworksBuildPhase section */ 40 | 41 | /* Begin PBXGroup section */ 42 | 22F2ADBC1E2965100096E2D7 = { 43 | isa = PBXGroup; 44 | children = ( 45 | 22F2ADC71E2965100096E2D7 /* interviewcodecpp */, 46 | 22F2ADC61E2965100096E2D7 /* Products */, 47 | ); 48 | sourceTree = ""; 49 | }; 50 | 22F2ADC61E2965100096E2D7 /* Products */ = { 51 | isa = PBXGroup; 52 | children = ( 53 | 22F2ADC51E2965100096E2D7 /* interviewcodecpp */, 54 | ); 55 | name = Products; 56 | sourceTree = ""; 57 | }; 58 | 22F2ADC71E2965100096E2D7 /* interviewcodecpp */ = { 59 | isa = PBXGroup; 60 | children = ( 61 | 22F2ADC81E2965100096E2D7 /* main.cpp */, 62 | 22F2ADCF1E2965B50096E2D7 /* entity.h */, 63 | ); 64 | path = interviewcodecpp; 65 | sourceTree = ""; 66 | }; 67 | /* End PBXGroup section */ 68 | 69 | /* Begin PBXNativeTarget section */ 70 | 22F2ADC41E2965100096E2D7 /* interviewcodecpp */ = { 71 | isa = PBXNativeTarget; 72 | buildConfigurationList = 22F2ADCC1E2965100096E2D7 /* Build configuration list for PBXNativeTarget "interviewcodecpp" */; 73 | buildPhases = ( 74 | 22F2ADC11E2965100096E2D7 /* Sources */, 75 | 22F2ADC21E2965100096E2D7 /* Frameworks */, 76 | 22F2ADC31E2965100096E2D7 /* CopyFiles */, 77 | ); 78 | buildRules = ( 79 | ); 80 | dependencies = ( 81 | ); 82 | name = interviewcodecpp; 83 | productName = interviewcodecpp; 84 | productReference = 22F2ADC51E2965100096E2D7 /* interviewcodecpp */; 85 | productType = "com.apple.product-type.tool"; 86 | }; 87 | /* End PBXNativeTarget section */ 88 | 89 | /* Begin PBXProject section */ 90 | 22F2ADBD1E2965100096E2D7 /* Project object */ = { 91 | isa = PBXProject; 92 | attributes = { 93 | LastUpgradeCheck = 1010; 94 | ORGANIZATIONNAME = "Sam Pullara"; 95 | TargetAttributes = { 96 | 22F2ADC41E2965100096E2D7 = { 97 | CreatedOnToolsVersion = 8.2.1; 98 | ProvisioningStyle = Automatic; 99 | }; 100 | }; 101 | }; 102 | buildConfigurationList = 22F2ADC01E2965100096E2D7 /* Build configuration list for PBXProject "interviewcodecpp" */; 103 | compatibilityVersion = "Xcode 3.2"; 104 | developmentRegion = English; 105 | hasScannedForEncodings = 0; 106 | knownRegions = ( 107 | en, 108 | ); 109 | mainGroup = 22F2ADBC1E2965100096E2D7; 110 | productRefGroup = 22F2ADC61E2965100096E2D7 /* Products */; 111 | projectDirPath = ""; 112 | projectRoot = ""; 113 | targets = ( 114 | 22F2ADC41E2965100096E2D7 /* interviewcodecpp */, 115 | ); 116 | }; 117 | /* End PBXProject section */ 118 | 119 | /* Begin PBXSourcesBuildPhase section */ 120 | 22F2ADC11E2965100096E2D7 /* Sources */ = { 121 | isa = PBXSourcesBuildPhase; 122 | buildActionMask = 2147483647; 123 | files = ( 124 | 22F2ADC91E2965100096E2D7 /* main.cpp in Sources */, 125 | ); 126 | runOnlyForDeploymentPostprocessing = 0; 127 | }; 128 | /* End PBXSourcesBuildPhase section */ 129 | 130 | /* Begin XCBuildConfiguration section */ 131 | 22F2ADCA1E2965100096E2D7 /* Debug */ = { 132 | isa = XCBuildConfiguration; 133 | buildSettings = { 134 | ALWAYS_SEARCH_USER_PATHS = NO; 135 | CLANG_ANALYZER_NONNULL = YES; 136 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 137 | CLANG_CXX_LIBRARY = "libc++"; 138 | CLANG_ENABLE_MODULES = YES; 139 | CLANG_ENABLE_OBJC_ARC = YES; 140 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 141 | CLANG_WARN_BOOL_CONVERSION = YES; 142 | CLANG_WARN_COMMA = YES; 143 | CLANG_WARN_CONSTANT_CONVERSION = YES; 144 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 145 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 146 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 147 | CLANG_WARN_EMPTY_BODY = YES; 148 | CLANG_WARN_ENUM_CONVERSION = YES; 149 | CLANG_WARN_INFINITE_RECURSION = YES; 150 | CLANG_WARN_INT_CONVERSION = YES; 151 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 152 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 153 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 154 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 155 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 156 | CLANG_WARN_STRICT_PROTOTYPES = YES; 157 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 158 | CLANG_WARN_UNREACHABLE_CODE = YES; 159 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 160 | CODE_SIGN_IDENTITY = "-"; 161 | COPY_PHASE_STRIP = NO; 162 | DEBUG_INFORMATION_FORMAT = dwarf; 163 | ENABLE_STRICT_OBJC_MSGSEND = YES; 164 | ENABLE_TESTABILITY = YES; 165 | GCC_C_LANGUAGE_STANDARD = gnu99; 166 | GCC_DYNAMIC_NO_PIC = NO; 167 | GCC_NO_COMMON_BLOCKS = YES; 168 | GCC_OPTIMIZATION_LEVEL = 0; 169 | GCC_PREPROCESSOR_DEFINITIONS = ( 170 | "DEBUG=1", 171 | "$(inherited)", 172 | ); 173 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 174 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 175 | GCC_WARN_UNDECLARED_SELECTOR = YES; 176 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 177 | GCC_WARN_UNUSED_FUNCTION = YES; 178 | GCC_WARN_UNUSED_VARIABLE = YES; 179 | MACOSX_DEPLOYMENT_TARGET = 10.12; 180 | MTL_ENABLE_DEBUG_INFO = YES; 181 | ONLY_ACTIVE_ARCH = YES; 182 | SDKROOT = macosx; 183 | }; 184 | name = Debug; 185 | }; 186 | 22F2ADCB1E2965100096E2D7 /* Release */ = { 187 | isa = XCBuildConfiguration; 188 | buildSettings = { 189 | ALWAYS_SEARCH_USER_PATHS = NO; 190 | CLANG_ANALYZER_NONNULL = YES; 191 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 192 | CLANG_CXX_LIBRARY = "libc++"; 193 | CLANG_ENABLE_MODULES = YES; 194 | CLANG_ENABLE_OBJC_ARC = YES; 195 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 196 | CLANG_WARN_BOOL_CONVERSION = YES; 197 | CLANG_WARN_COMMA = YES; 198 | CLANG_WARN_CONSTANT_CONVERSION = YES; 199 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 200 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 201 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 202 | CLANG_WARN_EMPTY_BODY = YES; 203 | CLANG_WARN_ENUM_CONVERSION = YES; 204 | CLANG_WARN_INFINITE_RECURSION = YES; 205 | CLANG_WARN_INT_CONVERSION = YES; 206 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 207 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 208 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 209 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 210 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 211 | CLANG_WARN_STRICT_PROTOTYPES = YES; 212 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 213 | CLANG_WARN_UNREACHABLE_CODE = YES; 214 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 215 | CODE_SIGN_IDENTITY = "-"; 216 | COPY_PHASE_STRIP = NO; 217 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 218 | ENABLE_NS_ASSERTIONS = NO; 219 | ENABLE_STRICT_OBJC_MSGSEND = YES; 220 | GCC_C_LANGUAGE_STANDARD = gnu99; 221 | GCC_NO_COMMON_BLOCKS = YES; 222 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 223 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 224 | GCC_WARN_UNDECLARED_SELECTOR = YES; 225 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 226 | GCC_WARN_UNUSED_FUNCTION = YES; 227 | GCC_WARN_UNUSED_VARIABLE = YES; 228 | MACOSX_DEPLOYMENT_TARGET = 10.12; 229 | MTL_ENABLE_DEBUG_INFO = NO; 230 | SDKROOT = macosx; 231 | }; 232 | name = Release; 233 | }; 234 | 22F2ADCD1E2965100096E2D7 /* Debug */ = { 235 | isa = XCBuildConfiguration; 236 | buildSettings = { 237 | PRODUCT_NAME = "$(TARGET_NAME)"; 238 | }; 239 | name = Debug; 240 | }; 241 | 22F2ADCE1E2965100096E2D7 /* Release */ = { 242 | isa = XCBuildConfiguration; 243 | buildSettings = { 244 | PRODUCT_NAME = "$(TARGET_NAME)"; 245 | }; 246 | name = Release; 247 | }; 248 | /* End XCBuildConfiguration section */ 249 | 250 | /* Begin XCConfigurationList section */ 251 | 22F2ADC01E2965100096E2D7 /* Build configuration list for PBXProject "interviewcodecpp" */ = { 252 | isa = XCConfigurationList; 253 | buildConfigurations = ( 254 | 22F2ADCA1E2965100096E2D7 /* Debug */, 255 | 22F2ADCB1E2965100096E2D7 /* Release */, 256 | ); 257 | defaultConfigurationIsVisible = 0; 258 | defaultConfigurationName = Release; 259 | }; 260 | 22F2ADCC1E2965100096E2D7 /* Build configuration list for PBXNativeTarget "interviewcodecpp" */ = { 261 | isa = XCConfigurationList; 262 | buildConfigurations = ( 263 | 22F2ADCD1E2965100096E2D7 /* Debug */, 264 | 22F2ADCE1E2965100096E2D7 /* Release */, 265 | ); 266 | defaultConfigurationIsVisible = 0; 267 | defaultConfigurationName = Release; 268 | }; 269 | /* End XCConfigurationList section */ 270 | }; 271 | rootObject = 22F2ADBD1E2965100096E2D7 /* Project object */; 272 | } 273 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp.xcodeproj/project.xcworkspace/xcuserdata/sam.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spullara/interviewcode/HEAD/interviewcodecpp/interviewcodecpp.xcodeproj/project.xcworkspace/xcuserdata/sam.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp.xcodeproj/xcuserdata/sam.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp.xcodeproj/xcuserdata/sam.xcuserdatad/xcschemes/interviewcodecpp.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp.xcodeproj/xcuserdata/sam.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | interviewcodecpp.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 22F2ADC41E2965100096E2D7 16 | 17 | primary 18 | 19 | 20 | 22F2ADD01E29BCC70096E2D7 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp/entity.h: -------------------------------------------------------------------------------- 1 | // 2 | // entity.h 3 | // interviewcodecpp 4 | // 5 | // Created by Sam Pullara on 1/13/17. 6 | // Copyright © 2017 Sam Pullara. All rights reserved. 7 | // 8 | 9 | #ifndef entity_h 10 | #define entity_h 11 | 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | class Entity : less { 18 | public: 19 | int start; 20 | int end; 21 | u32string html; 22 | 23 | struct PtrComparator { 24 | bool operator()(Entity const* left, Entity const* right) const { 25 | return left->start < right->start; 26 | } 27 | }; 28 | 29 | struct UniquePtrComparator { 30 | bool operator()(std::unique_ptr const& left, std::unique_ptr const& right) const { 31 | return left->start == right->start && 32 | left->end == right->end && 33 | left->html == right->html; 34 | } 35 | }; 36 | 37 | Entity(int, int, u32string&&); 38 | }; 39 | 40 | Entity::Entity(int start, int end, u32string&& html) { 41 | this->start = start; 42 | this->end = end; 43 | this->html = std::move(html); 44 | } 45 | 46 | template <> 47 | struct std::hash> 48 | { 49 | std::size_t operator()(unique_ptr const& k) const 50 | { 51 | using std::size_t; 52 | using std::hash; 53 | using std::string; 54 | 55 | // Compute individual hash values for first, 56 | // second and third and combine them using XOR 57 | // and bit shifting: 58 | return ((_int_hash(k->start) ^ (_int_hash(k->end) << 1)) >> 1) ^ (_u32string_hash(k->html) << 1); 59 | } 60 | 61 | private: 62 | std::hash _int_hash; 63 | std::hash _u32string_hash; 64 | }; 65 | 66 | #endif /* entity_h */ 67 | -------------------------------------------------------------------------------- /interviewcodecpp/interviewcodecpp/main.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // main.cpp 3 | // interviewcodecpp 4 | // 5 | // Created by Sam Pullara on 1/13/17. 6 | // Copyright © 2017 Sam Pullara. All rights reserved. 7 | // 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #include "entity.h" 20 | 21 | using namespace std; 22 | 23 | using EntitySet = unordered_set, std::hash>, Entity::UniquePtrComparator>; 24 | 25 | thread_local vector _render_entities_buffer; 26 | void render(const u32string &text, EntitySet const& entitySet, /* out */ u32string& result) { 27 | result.clear(); 28 | result.reserve(text.length() * 2); 29 | 30 | auto entities = &_render_entities_buffer; 31 | entities->clear(); 32 | entities->reserve(entitySet.size()); 33 | for (auto const& entity: entitySet) { 34 | entities->push_back(entity.get()); 35 | } 36 | std::sort(entities->begin(), entities->end(), Entity::PtrComparator()); 37 | 38 | int pos = 0; 39 | for (auto const& entity: *entities) { 40 | result.append(text, pos, entity->start - pos); 41 | result.append(entity->html); 42 | pos = entity->end; 43 | } 44 | 45 | result.append(text, pos); 46 | } 47 | 48 | vector createEntriesList(u32string text) { 49 | default_random_engine generator; 50 | 51 | uniform_int_distribution distribution(0, 9); 52 | auto r = bind(distribution, generator); 53 | 54 | uniform_int_distribution distribution2 = uniform_int_distribution(0, (int) (text.length() - 1)); 55 | auto r2 = bind(distribution2, generator); 56 | 57 | vector entityList; 58 | entityList.reserve(1000); 59 | 60 | for (int i = 0; i < 1000; i++) { 61 | int total = r(); 62 | EntitySet entitySet; 63 | entitySet.reserve(total * 2); 64 | auto indices = vector(); 65 | for (int j = 0; j < total * 2; j++) { 66 | int next; 67 | while(find(indices.begin(), indices.end(), next = r2()) != indices.end()); 68 | indices.push_back(next); 69 | } 70 | sort(indices.begin(), indices.end()); 71 | for (int j = 0; j < total * 2; j += 2) { 72 | int start = *next(indices.begin(), j); 73 | int end = *next(indices.begin(), j+1); 74 | int length = end - start; 75 | u32string html = U""; 76 | for (int k = 0; k < length; k++) { 77 | html.append(U"XX"); 78 | } 79 | entitySet.insert(std::unique_ptr(new Entity(start, end, std::move(html)))); 80 | } 81 | entityList.push_back(std::move(entitySet)); 82 | } 83 | 84 | return entityList; 85 | } 86 | 87 | long currentTimeMillis() { 88 | using namespace std::chrono; 89 | milliseconds ms = duration_cast(system_clock::now().time_since_epoch()); 90 | return ms.count(); 91 | } 92 | 93 | void bench() { 94 | u32string text = U"Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 95 | auto entityList = createEntriesList(text); 96 | 97 | { 98 | u32string result; 99 | for (int j = 0; j < 5; j++) { 100 | long start = currentTimeMillis(); 101 | for (int i = 0; i < 1000000; i++) { 102 | render(text, entityList[i % 1000], result); 103 | } 104 | cout << (currentTimeMillis() - start) << " ns/op\n"; 105 | } 106 | } 107 | } 108 | 109 | int main(int argc, const char * argv[]) { 110 | cout << "Starting\n"; 111 | EntitySet entitySet; 112 | entitySet.insert(std::unique_ptr(new Entity(25, 32, U"<#mobile>"))); 113 | entitySet.insert(std::unique_ptr(new Entity(33, 42, U"<#startups>"))); 114 | entitySet.insert(std::unique_ptr(new Entity(46, 51, U"<#OF12>"))); 115 | entitySet.insert(std::unique_ptr(new Entity(82, 102, U""))); 116 | entitySet.insert(std::unique_ptr(new Entity(103, 110, U"<@TiEcon>"))); 117 | entitySet.insert(std::unique_ptr(new Entity(111, 127, U"<@sv_entrepreneur>"))); 118 | entitySet.insert(std::unique_ptr(new Entity(128, 132, U"<@500>"))); 119 | 120 | u32string text = U"Attend \u4e20\u4e20 hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 121 | u32string test = U"Attend \u4e20\u4e20 hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 122 | 123 | u32string result; 124 | render(text, entitySet, result); 125 | 126 | std::wstring_convert, char32_t> convert; 127 | cout << convert.to_bytes(result) << ": " << (result == test) << "\n"; 128 | 129 | cout << "Running benchmark\n"; 130 | 131 | bench(); 132 | 133 | return 0; 134 | } 135 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 2215DBDE1E2569BF0068AAEB /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2215DBDD1E2569BF0068AAEB /* main.swift */; }; 11 | /* End PBXBuildFile section */ 12 | 13 | /* Begin PBXCopyFilesBuildPhase section */ 14 | 2215DBD81E2569BF0068AAEB /* CopyFiles */ = { 15 | isa = PBXCopyFilesBuildPhase; 16 | buildActionMask = 2147483647; 17 | dstPath = /usr/share/man/man1/; 18 | dstSubfolderSpec = 0; 19 | files = ( 20 | ); 21 | runOnlyForDeploymentPostprocessing = 1; 22 | }; 23 | /* End PBXCopyFilesBuildPhase section */ 24 | 25 | /* Begin PBXFileReference section */ 26 | 2215DBDA1E2569BF0068AAEB /* interviewcode */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = interviewcode; sourceTree = BUILT_PRODUCTS_DIR; }; 27 | 2215DBDD1E2569BF0068AAEB /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; 28 | /* End PBXFileReference section */ 29 | 30 | /* Begin PBXFrameworksBuildPhase section */ 31 | 2215DBD71E2569BF0068AAEB /* Frameworks */ = { 32 | isa = PBXFrameworksBuildPhase; 33 | buildActionMask = 2147483647; 34 | files = ( 35 | ); 36 | runOnlyForDeploymentPostprocessing = 0; 37 | }; 38 | /* End PBXFrameworksBuildPhase section */ 39 | 40 | /* Begin PBXGroup section */ 41 | 2215DBD11E2569BF0068AAEB = { 42 | isa = PBXGroup; 43 | children = ( 44 | 2215DBDC1E2569BF0068AAEB /* interviewcode */, 45 | 2215DBDB1E2569BF0068AAEB /* Products */, 46 | ); 47 | sourceTree = ""; 48 | }; 49 | 2215DBDB1E2569BF0068AAEB /* Products */ = { 50 | isa = PBXGroup; 51 | children = ( 52 | 2215DBDA1E2569BF0068AAEB /* interviewcode */, 53 | ); 54 | name = Products; 55 | sourceTree = ""; 56 | }; 57 | 2215DBDC1E2569BF0068AAEB /* interviewcode */ = { 58 | isa = PBXGroup; 59 | children = ( 60 | 2215DBDD1E2569BF0068AAEB /* main.swift */, 61 | ); 62 | path = interviewcode; 63 | sourceTree = ""; 64 | }; 65 | /* End PBXGroup section */ 66 | 67 | /* Begin PBXNativeTarget section */ 68 | 2215DBD91E2569BF0068AAEB /* interviewcode */ = { 69 | isa = PBXNativeTarget; 70 | buildConfigurationList = 2215DBE11E2569BF0068AAEB /* Build configuration list for PBXNativeTarget "interviewcode" */; 71 | buildPhases = ( 72 | 2215DBD61E2569BF0068AAEB /* Sources */, 73 | 2215DBD71E2569BF0068AAEB /* Frameworks */, 74 | 2215DBD81E2569BF0068AAEB /* CopyFiles */, 75 | ); 76 | buildRules = ( 77 | ); 78 | dependencies = ( 79 | ); 80 | name = interviewcode; 81 | productName = interviewcode; 82 | productReference = 2215DBDA1E2569BF0068AAEB /* interviewcode */; 83 | productType = "com.apple.product-type.tool"; 84 | }; 85 | /* End PBXNativeTarget section */ 86 | 87 | /* Begin PBXProject section */ 88 | 2215DBD21E2569BF0068AAEB /* Project object */ = { 89 | isa = PBXProject; 90 | attributes = { 91 | LastSwiftUpdateCheck = 0820; 92 | LastUpgradeCheck = 1010; 93 | ORGANIZATIONNAME = "Sam Pullara"; 94 | TargetAttributes = { 95 | 2215DBD91E2569BF0068AAEB = { 96 | CreatedOnToolsVersion = 8.2.1; 97 | LastSwiftMigration = 0920; 98 | ProvisioningStyle = Automatic; 99 | }; 100 | }; 101 | }; 102 | buildConfigurationList = 2215DBD51E2569BF0068AAEB /* Build configuration list for PBXProject "interviewcode" */; 103 | compatibilityVersion = "Xcode 3.2"; 104 | developmentRegion = English; 105 | hasScannedForEncodings = 0; 106 | knownRegions = ( 107 | en, 108 | ); 109 | mainGroup = 2215DBD11E2569BF0068AAEB; 110 | productRefGroup = 2215DBDB1E2569BF0068AAEB /* Products */; 111 | projectDirPath = ""; 112 | projectRoot = ""; 113 | targets = ( 114 | 2215DBD91E2569BF0068AAEB /* interviewcode */, 115 | ); 116 | }; 117 | /* End PBXProject section */ 118 | 119 | /* Begin PBXSourcesBuildPhase section */ 120 | 2215DBD61E2569BF0068AAEB /* Sources */ = { 121 | isa = PBXSourcesBuildPhase; 122 | buildActionMask = 2147483647; 123 | files = ( 124 | 2215DBDE1E2569BF0068AAEB /* main.swift in Sources */, 125 | ); 126 | runOnlyForDeploymentPostprocessing = 0; 127 | }; 128 | /* End PBXSourcesBuildPhase section */ 129 | 130 | /* Begin XCBuildConfiguration section */ 131 | 2215DBDF1E2569BF0068AAEB /* Debug */ = { 132 | isa = XCBuildConfiguration; 133 | buildSettings = { 134 | ALWAYS_SEARCH_USER_PATHS = NO; 135 | CLANG_ANALYZER_NONNULL = YES; 136 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 137 | CLANG_CXX_LIBRARY = "libc++"; 138 | CLANG_ENABLE_MODULES = YES; 139 | CLANG_ENABLE_OBJC_ARC = YES; 140 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 141 | CLANG_WARN_BOOL_CONVERSION = YES; 142 | CLANG_WARN_COMMA = YES; 143 | CLANG_WARN_CONSTANT_CONVERSION = YES; 144 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 145 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 146 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 147 | CLANG_WARN_EMPTY_BODY = YES; 148 | CLANG_WARN_ENUM_CONVERSION = YES; 149 | CLANG_WARN_INFINITE_RECURSION = YES; 150 | CLANG_WARN_INT_CONVERSION = YES; 151 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 152 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 153 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 154 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 155 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 156 | CLANG_WARN_STRICT_PROTOTYPES = YES; 157 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 158 | CLANG_WARN_UNREACHABLE_CODE = YES; 159 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 160 | CODE_SIGN_IDENTITY = "-"; 161 | COPY_PHASE_STRIP = NO; 162 | DEBUG_INFORMATION_FORMAT = dwarf; 163 | ENABLE_STRICT_OBJC_MSGSEND = YES; 164 | ENABLE_TESTABILITY = YES; 165 | GCC_C_LANGUAGE_STANDARD = gnu99; 166 | GCC_DYNAMIC_NO_PIC = NO; 167 | GCC_NO_COMMON_BLOCKS = YES; 168 | GCC_OPTIMIZATION_LEVEL = 0; 169 | GCC_PREPROCESSOR_DEFINITIONS = ( 170 | "DEBUG=1", 171 | "$(inherited)", 172 | ); 173 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 174 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 175 | GCC_WARN_UNDECLARED_SELECTOR = YES; 176 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 177 | GCC_WARN_UNUSED_FUNCTION = YES; 178 | GCC_WARN_UNUSED_VARIABLE = YES; 179 | MACOSX_DEPLOYMENT_TARGET = 10.12; 180 | MTL_ENABLE_DEBUG_INFO = YES; 181 | ONLY_ACTIVE_ARCH = YES; 182 | SDKROOT = macosx; 183 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 184 | }; 185 | name = Debug; 186 | }; 187 | 2215DBE01E2569BF0068AAEB /* Release */ = { 188 | isa = XCBuildConfiguration; 189 | buildSettings = { 190 | ALWAYS_SEARCH_USER_PATHS = NO; 191 | CLANG_ANALYZER_NONNULL = YES; 192 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 193 | CLANG_CXX_LIBRARY = "libc++"; 194 | CLANG_ENABLE_MODULES = YES; 195 | CLANG_ENABLE_OBJC_ARC = YES; 196 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 197 | CLANG_WARN_BOOL_CONVERSION = YES; 198 | CLANG_WARN_COMMA = YES; 199 | CLANG_WARN_CONSTANT_CONVERSION = YES; 200 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 201 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 202 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 203 | CLANG_WARN_EMPTY_BODY = YES; 204 | CLANG_WARN_ENUM_CONVERSION = YES; 205 | CLANG_WARN_INFINITE_RECURSION = YES; 206 | CLANG_WARN_INT_CONVERSION = YES; 207 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 208 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 209 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 210 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 211 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 212 | CLANG_WARN_STRICT_PROTOTYPES = YES; 213 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 214 | CLANG_WARN_UNREACHABLE_CODE = YES; 215 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 216 | CODE_SIGN_IDENTITY = "-"; 217 | COPY_PHASE_STRIP = NO; 218 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 219 | ENABLE_NS_ASSERTIONS = NO; 220 | ENABLE_STRICT_OBJC_MSGSEND = YES; 221 | GCC_C_LANGUAGE_STANDARD = gnu99; 222 | GCC_NO_COMMON_BLOCKS = YES; 223 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 224 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 225 | GCC_WARN_UNDECLARED_SELECTOR = YES; 226 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 227 | GCC_WARN_UNUSED_FUNCTION = YES; 228 | GCC_WARN_UNUSED_VARIABLE = YES; 229 | MACOSX_DEPLOYMENT_TARGET = 10.12; 230 | MTL_ENABLE_DEBUG_INFO = NO; 231 | SDKROOT = macosx; 232 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; 233 | }; 234 | name = Release; 235 | }; 236 | 2215DBE21E2569BF0068AAEB /* Debug */ = { 237 | isa = XCBuildConfiguration; 238 | buildSettings = { 239 | PRODUCT_NAME = "$(TARGET_NAME)"; 240 | SWIFT_SWIFT3_OBJC_INFERENCE = On; 241 | SWIFT_VERSION = 4.0; 242 | }; 243 | name = Debug; 244 | }; 245 | 2215DBE31E2569BF0068AAEB /* Release */ = { 246 | isa = XCBuildConfiguration; 247 | buildSettings = { 248 | PRODUCT_NAME = "$(TARGET_NAME)"; 249 | SWIFT_SWIFT3_OBJC_INFERENCE = On; 250 | SWIFT_VERSION = 4.0; 251 | }; 252 | name = Release; 253 | }; 254 | /* End XCBuildConfiguration section */ 255 | 256 | /* Begin XCConfigurationList section */ 257 | 2215DBD51E2569BF0068AAEB /* Build configuration list for PBXProject "interviewcode" */ = { 258 | isa = XCConfigurationList; 259 | buildConfigurations = ( 260 | 2215DBDF1E2569BF0068AAEB /* Debug */, 261 | 2215DBE01E2569BF0068AAEB /* Release */, 262 | ); 263 | defaultConfigurationIsVisible = 0; 264 | defaultConfigurationName = Release; 265 | }; 266 | 2215DBE11E2569BF0068AAEB /* Build configuration list for PBXNativeTarget "interviewcode" */ = { 267 | isa = XCConfigurationList; 268 | buildConfigurations = ( 269 | 2215DBE21E2569BF0068AAEB /* Debug */, 270 | 2215DBE31E2569BF0068AAEB /* Release */, 271 | ); 272 | defaultConfigurationIsVisible = 0; 273 | defaultConfigurationName = Release; 274 | }; 275 | /* End XCConfigurationList section */ 276 | }; 277 | rootObject = 2215DBD21E2569BF0068AAEB /* Project object */; 278 | } 279 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/project.xcworkspace/xcuserdata/sam.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spullara/interviewcode/HEAD/interviewcodeswift/interviewcode.xcodeproj/project.xcworkspace/xcuserdata/sam.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/project.xcworkspace/xcuserdata/sam.xcuserdatad/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | BuildLocationStyle 6 | UseAppPreferences 7 | CustomBuildLocationType 8 | RelativeToDerivedData 9 | DerivedDataLocationStyle 10 | Default 11 | EnabledFullIndexStoreVisibility 12 | 13 | IssueFilterStyle 14 | ShowActiveSchemeOnly 15 | LiveSourceIssuesEnabled 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/xcuserdata/sam.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/xcuserdata/sam.xcuserdatad/xcschemes/interviewcode.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode.xcodeproj/xcuserdata/sam.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | interviewcode.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 2215DBD91E2569BF0068AAEB 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /interviewcodeswift/interviewcode/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // interviewcode 4 | // 5 | // Created by Sam Pullara on 1/10/17. 6 | // Copyright © 2017 Sam Pullara. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | var text: String = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 12 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 13 | 14 | struct Entity : Hashable, Comparable { 15 | var start: Int 16 | var end: Int 17 | var html: String 18 | 19 | var hashValue: Int { 20 | return html.hashValue ^ start ^ end 21 | } 22 | 23 | static func == (lhs: Entity, rhs: Entity) -> Bool { 24 | return lhs.start == rhs.start && lhs.end == rhs.end && lhs.html == rhs.html 25 | } 26 | 27 | static func <(lhs: Entity, rhs: Entity) -> Bool { 28 | return lhs.start < rhs.start 29 | } 30 | } 31 | 32 | 33 | func createEntityList(text: String) -> Array> { 34 | let length = text.count 35 | var entitiesList: Array> = Array() 36 | for _ in 1...1000 { 37 | var entities: Set = Set() 38 | let total = Int(arc4random() % 10) 39 | var indices: Array = Array() 40 | for _ in 0.. Set { 64 | var entities: Set = Set() 65 | entities.insert(Entity(start: 25, end: 32, html: "<#mobile>")) 66 | entities.insert(Entity(start: 33, end: 42, html: "<#startups>")) 67 | entities.insert(Entity(start: 46, end: 51, html: "<#OF12>")) 68 | entities.insert(Entity(start: 82, end: 102, html: "")) 69 | entities.insert(Entity(start: 103, end: 110, html: "<@TiEcon>")) 70 | entities.insert(Entity(start: 111, end: 127, html: "<@sv_entrepreneur>")) 71 | entities.insert(Entity(start: 128, end: 132, html: "<@500>")) 72 | return entities 73 | } 74 | 75 | func render(text: String, entities: Set) -> String { 76 | let entityArray = Array(entities).sorted() 77 | var sb = String() 78 | var pos = 0 79 | var posIndex = text.startIndex 80 | for entity in entityArray { 81 | let startIndex = text.index(posIndex, offsetBy: entity.start - pos) 82 | sb.append(contentsOf: text[posIndex ..< startIndex]) 83 | sb += entity.html 84 | posIndex = text.index(startIndex, offsetBy: entity.end - entity.start) 85 | pos = entity.end 86 | } 87 | sb.append(contentsOf: text[posIndex...]) 88 | return sb 89 | } 90 | 91 | func time() -> UInt64 { 92 | var darwinTime : timeval = timeval(tv_sec: 0, tv_usec: 0) 93 | gettimeofday(&darwinTime, nil) 94 | return UInt64(darwinTime.tv_sec * 1000) + UInt64(darwinTime.tv_usec / 1000) 95 | } 96 | 97 | var entityList = createEntityList(text: text) 98 | print(render(text: text, entities: testEntities())) 99 | 100 | var entitiesList = createEntityList(text: text) 101 | 102 | for _ in 1...5 { 103 | let start = time() 104 | for i in 1...1000000 { 105 | render(text: text, entities: entitiesList[i % 1000]) 106 | } 107 | let diff = time() - start 108 | print(String(diff) + " ns/render") 109 | } 110 | -------------------------------------------------------------------------------- /javascript/index.js: -------------------------------------------------------------------------------- 1 | const text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!" 2 | 3 | function getEntities() { 4 | return [ 5 | {start: 25, end: 32, html: "<#mobile>"}, 6 | {start: 33, end: 42, html: "<#startups>"}, 7 | {start: 46, end: 51, html: "<#OF12>"}, 8 | {start: 82, end: 102, html: ""}, 9 | {start: 103, end: 110, html: "<@TiEcon>"}, 10 | {start: 111, end: 127, html: "<@sv_entrepreneur>"}, 11 | {start: 128, end: 132, html: "<@500>"}, 12 | ]; 13 | } 14 | 15 | function createEntriesList() { 16 | const entitiesList = []; 17 | for (let i = 0; i < 1000; i++) { 18 | const entities = []; 19 | const total = Math.random() * 10; 20 | const indices = []; 21 | for (var j = 0; j < total * 2; j++) { 22 | let next; 23 | while (indices.includes(next = Math.floor(Math.random() * text.length))) ; 24 | indices.push(next); 25 | } 26 | indices.sort(); 27 | for (j = 0; j < total * 2; j += 2) { 28 | const start = indices[j]; 29 | const end = indices[j + 1]; 30 | const length = end - start; 31 | let sb = ""; 32 | for (let k = 0; k < length; k++) { 33 | sb += "XX"; 34 | } 35 | entities.push({start, end, html: sb}); 36 | } 37 | entitiesList.push(entities); 38 | } 39 | return entitiesList; 40 | } 41 | 42 | function render(text, unsortedEntities) { 43 | const entities = [...unsortedEntities]; 44 | entities.sort((o1, o2) => o1.start - o2.start); 45 | let result = ''; 46 | const arr = Array.from(text) 47 | const arrLen = arr.length 48 | let pos = 0 49 | for (let entity of entities) { 50 | const start = entity.start; 51 | for (; pos < arrLen; pos++) { 52 | // If this is the start of an entity add it to the result 53 | if (start === pos) { 54 | result += entity.html; 55 | pos = entity.end; 56 | break; 57 | } else { 58 | result += arr[pos]; 59 | } 60 | } 61 | } 62 | for (; pos < arrLen; pos++) { 63 | result += arr[pos] 64 | } 65 | return result; 66 | } 67 | 68 | function renderInvert(text, unsortedEntities) { 69 | const entities = [...unsortedEntities]; 70 | entities.sort((o1, o2) => o1.start - o2.start); 71 | let result = ''; 72 | let entity = entities.shift(); 73 | if (!entity) return text; 74 | let start = entity.start; 75 | const codePoints = Array.from(text); 76 | const length = codePoints.length; 77 | for (let pos = 0; pos < length; pos++) { 78 | if (start === pos) { 79 | pos = entity.end - 1; 80 | result += entity.html; 81 | entity = entities.shift(); 82 | if (entity) { 83 | start = entity.start; 84 | } else { 85 | start = -1; 86 | } 87 | } else { 88 | result += codePoints[pos]; 89 | } 90 | } 91 | return result; 92 | } 93 | 94 | 95 | function renderMark(text, unsortedEntities) { 96 | const entities = [...unsortedEntities]; 97 | entities.sort((o1, o2) => o1.start - o2.start); 98 | 99 | let result = ''; 100 | const arr = Array.from(text) 101 | const arrLen = arr.length 102 | // let entityNum = 0 103 | 104 | let i = 0 105 | 106 | if (entities.length) { 107 | for (; i < arrLen; i++) { 108 | let didAddEntity = false 109 | // If this is the start of an entity add it to the result 110 | while (entities[0].start === i) { 111 | const entity = entities.shift(); 112 | result += entity.html; 113 | i = entity.end - 1 114 | didAddEntity = true 115 | if (!entities.length) { 116 | break 117 | } 118 | } 119 | 120 | if (didAddEntity) { 121 | if (entities.length === 0) { 122 | i++; 123 | break 124 | } 125 | } else { 126 | result += arr[i] 127 | } 128 | } 129 | } 130 | 131 | for (; i < arrLen; i++) { 132 | result += arr[i] 133 | } 134 | 135 | return result 136 | } 137 | 138 | function offsetByCodePoints(s, index, codePointOffset) { 139 | const length = s.length; 140 | let x = index; 141 | for (let i = 0; i < length && i < codePointOffset; i++) { 142 | const ch = s.charAt(x++); 143 | if (ch >= '\ud800' && ch < '\udc00') { 144 | const ch1 = s.charAt(x); 145 | if (ch1 >= '\udc00' && ch1 < '\ue000') { 146 | x++; 147 | } 148 | } 149 | } 150 | return x; 151 | } 152 | 153 | function renderJava(text, unsortedEntities) { 154 | const entities = [...unsortedEntities]; 155 | entities.sort((o1, o2) => o1.start - o2.start); 156 | let result = ''; 157 | let pos = 0; 158 | let codePointPosition = 0; 159 | for (let entity of entities) { 160 | const start = offsetByCodePoints(text, pos, entity.start - codePointPosition); 161 | for (let i = pos; i < start; i++) { 162 | result += text[i]; 163 | } 164 | result += entity.html; 165 | codePointPosition = entity.end; 166 | pos = offsetByCodePoints(text, start, entity.end - entity.start); 167 | } 168 | for (let i = pos; i < text.length; i++) { 169 | result += text[i]; 170 | } 171 | return result; 172 | } 173 | 174 | function bench(name, func) { 175 | const text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 176 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 177 | const entitiesList = createEntriesList(); 178 | 179 | for (var j = 0; j < 5; j++) { 180 | for (var i = 0; i < 10000; i++) { 181 | func(text, entitiesList[i % 1000]); 182 | } 183 | const start = new Date().getTime(); 184 | for (i = 0; i < 1000000; i++) { 185 | func(text, entitiesList[i % 1000]); 186 | } 187 | let elapsed = new Date().getTime() - start; 188 | console.log(name + ": " + elapsed + "ns per render"); 189 | } 190 | } 191 | 192 | console.log(renderInvert(text, getEntities())); 193 | 194 | const expected = "Attend to hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, " + 195 | " <@TiEcon> <@sv_entrepreneur> <@500>!"; 196 | console.log(renderMark(text, getEntities()) === expected); 197 | console.log(render(text, getEntities()) === expected); 198 | console.log(renderJava(text, getEntities()) === expected); 199 | console.log(renderInvert(text, getEntities()) === expected); 200 | 201 | bench("render by invert", renderInvert); 202 | bench("render by mark", renderMark); 203 | bench("render by character", render); 204 | bench("render by java", renderJava); 205 | -------------------------------------------------------------------------------- /javascript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "javascript", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC" 11 | } 12 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | interviewcode 8 | interviewcode 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 1.5.31 13 | 14 | 15 | 16 | 17 | 18 | com.fasterxml.jackson.core 19 | jackson-databind 20 | 2.13.0 21 | 22 | 23 | 24 | junit 25 | junit 26 | 4.13.1 27 | test 28 | 29 | 30 | org.jetbrains.kotlin 31 | kotlin-stdlib-jdk8 32 | ${kotlin.version} 33 | 34 | 35 | org.jetbrains.kotlin 36 | kotlin-test-junit 37 | ${kotlin.version} 38 | test 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.apache.maven.plugins 48 | maven-compiler-plugin 49 | 2.0.2 50 | 51 | 11 52 | 11 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.jetbrains.kotlin 60 | kotlin-maven-plugin 61 | ${kotlin.version} 62 | 63 | 64 | compile 65 | compile 66 | 67 | compile 68 | 69 | 70 | 71 | src/main/java 72 | src 73 | 74 | 75 | 76 | 77 | test-compile 78 | test-compile 79 | 80 | test-compile 81 | 82 | 83 | 84 | 85 | 1.8 86 | 87 | 88 | 89 | org.apache.maven.plugins 90 | maven-compiler-plugin 91 | 92 | 93 | compile 94 | 95 | compile 96 | 97 | 98 | 99 | testCompile 100 | test-compile 101 | 102 | testCompile 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /python/interviewcode.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http://t.co/HtzEMgAC @TiEcon " \ 5 | "@sv_entrepreneur @500!" 6 | 7 | def create_entity_list(): 8 | length = len(text) 9 | entityList = [] 10 | for i in range(0, 1000): 11 | entities = [] 12 | total = random.randint(0, 9) 13 | indices = [] 14 | for j in range(0, total*2): 15 | while True: 16 | next = random.randint(0, length - 1) 17 | if next not in indices: 18 | indices.append(next) 19 | break 20 | indices.sort() 21 | for j in range(0, total): 22 | start = indices[j*2] 23 | end = indices[j*2 + 1] 24 | l = end - start 25 | sb = "" 26 | for _ in range(0, l): 27 | sb += "XX" 28 | entities.append((start, end, sb)) 29 | entityList.append(entities) 30 | return entityList 31 | 32 | def testEntites(): 33 | entities = [] 34 | entities.append((82, 102, "")) 35 | entities.append((103, 110, "<@TiEcon>")) 36 | entities.append((25, 32, "<#mobile>")) 37 | entities.append((33, 42, "<#startups>")) 38 | entities.append((46, 51, "<#OF12>")) 39 | entities.append((111, 127, "<@sv_entrepreneur>")) 40 | entities.append((128, 132, "<@500>")) 41 | return entities 42 | 43 | def render(text, entities): 44 | entityList = entities.copy() 45 | entityList.sort(key = lambda x : x[0]) 46 | pos = 0 47 | sb = "" 48 | for entity in entityList: 49 | sb += text[pos : entity[0]] 50 | sb += entity[2] 51 | pos = entity[1] 52 | sb += text[pos :] 53 | return sb 54 | 55 | if __name__ == "__main__": 56 | result = render(text, testEntites()) 57 | expected = "Attend to hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!" 58 | print(result) 59 | print(result == expected) 60 | entityList = create_entity_list() 61 | 62 | total = 1000000 63 | for _ in range(0, 5): 64 | start = time.clock_gettime_ns(time.CLOCK_MONOTONIC) 65 | for i in range(0, total): 66 | render(text, entityList[i % 1000]) 67 | end = time.clock_gettime_ns(time.CLOCK_MONOTONIC) 68 | diff = end - start 69 | print(str(int(diff/total)) + " ns/render") 70 | -------------------------------------------------------------------------------- /rust/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "atty" 7 | version = "0.2.14" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 10 | dependencies = [ 11 | "hermit-abi", 12 | "libc", 13 | "winapi", 14 | ] 15 | 16 | [[package]] 17 | name = "autocfg" 18 | version = "1.0.1" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" 21 | 22 | [[package]] 23 | name = "benchmarks_system" 24 | version = "0.1.0" 25 | dependencies = [ 26 | "criterion", 27 | "unicode_test", 28 | ] 29 | 30 | [[package]] 31 | name = "bitflags" 32 | version = "1.3.2" 33 | source = "registry+https://github.com/rust-lang/crates.io-index" 34 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 35 | 36 | [[package]] 37 | name = "bstr" 38 | version = "0.2.17" 39 | source = "registry+https://github.com/rust-lang/crates.io-index" 40 | checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" 41 | dependencies = [ 42 | "lazy_static", 43 | "memchr", 44 | "regex-automata", 45 | "serde", 46 | ] 47 | 48 | [[package]] 49 | name = "byteorder" 50 | version = "1.4.3" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" 53 | 54 | [[package]] 55 | name = "cast" 56 | version = "0.2.7" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "4c24dab4283a142afa2fdca129b80ad2c6284e073930f964c3a1293c225ee39a" 59 | dependencies = [ 60 | "rustc_version", 61 | ] 62 | 63 | [[package]] 64 | name = "cfg-if" 65 | version = "1.0.0" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 68 | 69 | [[package]] 70 | name = "clap" 71 | version = "2.34.0" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" 74 | dependencies = [ 75 | "bitflags", 76 | "textwrap", 77 | "unicode-width", 78 | ] 79 | 80 | [[package]] 81 | name = "cloudabi" 82 | version = "0.0.3" 83 | source = "registry+https://github.com/rust-lang/crates.io-index" 84 | checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" 85 | dependencies = [ 86 | "bitflags", 87 | ] 88 | 89 | [[package]] 90 | name = "criterion" 91 | version = "0.2.11" 92 | source = "registry+https://github.com/rust-lang/crates.io-index" 93 | checksum = "0363053954f3e679645fc443321ca128b7b950a6fe288cf5f9335cc22ee58394" 94 | dependencies = [ 95 | "atty", 96 | "cast", 97 | "clap", 98 | "criterion-plot", 99 | "csv", 100 | "itertools", 101 | "lazy_static", 102 | "libc", 103 | "num-traits", 104 | "rand_core 0.3.1", 105 | "rand_os", 106 | "rand_xoshiro", 107 | "rayon", 108 | "rayon-core", 109 | "serde", 110 | "serde_derive", 111 | "serde_json", 112 | "tinytemplate", 113 | "walkdir", 114 | ] 115 | 116 | [[package]] 117 | name = "criterion-plot" 118 | version = "0.3.1" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "76f9212ddf2f4a9eb2d401635190600656a1f88a932ef53d06e7fa4c7e02fb8e" 121 | dependencies = [ 122 | "byteorder", 123 | "cast", 124 | "itertools", 125 | ] 126 | 127 | [[package]] 128 | name = "crossbeam-channel" 129 | version = "0.5.1" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" 132 | dependencies = [ 133 | "cfg-if", 134 | "crossbeam-utils", 135 | ] 136 | 137 | [[package]] 138 | name = "crossbeam-deque" 139 | version = "0.8.1" 140 | source = "registry+https://github.com/rust-lang/crates.io-index" 141 | checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" 142 | dependencies = [ 143 | "cfg-if", 144 | "crossbeam-epoch", 145 | "crossbeam-utils", 146 | ] 147 | 148 | [[package]] 149 | name = "crossbeam-epoch" 150 | version = "0.9.5" 151 | source = "registry+https://github.com/rust-lang/crates.io-index" 152 | checksum = "4ec02e091aa634e2c3ada4a392989e7c3116673ef0ac5b72232439094d73b7fd" 153 | dependencies = [ 154 | "cfg-if", 155 | "crossbeam-utils", 156 | "lazy_static", 157 | "memoffset", 158 | "scopeguard", 159 | ] 160 | 161 | [[package]] 162 | name = "crossbeam-utils" 163 | version = "0.8.5" 164 | source = "registry+https://github.com/rust-lang/crates.io-index" 165 | checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" 166 | dependencies = [ 167 | "cfg-if", 168 | "lazy_static", 169 | ] 170 | 171 | [[package]] 172 | name = "csv" 173 | version = "1.1.6" 174 | source = "registry+https://github.com/rust-lang/crates.io-index" 175 | checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" 176 | dependencies = [ 177 | "bstr", 178 | "csv-core", 179 | "itoa 0.4.8", 180 | "ryu", 181 | "serde", 182 | ] 183 | 184 | [[package]] 185 | name = "csv-core" 186 | version = "0.1.10" 187 | source = "registry+https://github.com/rust-lang/crates.io-index" 188 | checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" 189 | dependencies = [ 190 | "memchr", 191 | ] 192 | 193 | [[package]] 194 | name = "either" 195 | version = "1.6.1" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" 198 | 199 | [[package]] 200 | name = "fuchsia-cprng" 201 | version = "0.1.1" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" 204 | 205 | [[package]] 206 | name = "getrandom" 207 | version = "0.1.16" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" 210 | dependencies = [ 211 | "cfg-if", 212 | "libc", 213 | "wasi", 214 | ] 215 | 216 | [[package]] 217 | name = "hermit-abi" 218 | version = "0.1.19" 219 | source = "registry+https://github.com/rust-lang/crates.io-index" 220 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 221 | dependencies = [ 222 | "libc", 223 | ] 224 | 225 | [[package]] 226 | name = "itertools" 227 | version = "0.8.2" 228 | source = "registry+https://github.com/rust-lang/crates.io-index" 229 | checksum = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" 230 | dependencies = [ 231 | "either", 232 | ] 233 | 234 | [[package]] 235 | name = "itoa" 236 | version = "0.4.8" 237 | source = "registry+https://github.com/rust-lang/crates.io-index" 238 | checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" 239 | 240 | [[package]] 241 | name = "itoa" 242 | version = "1.0.1" 243 | source = "registry+https://github.com/rust-lang/crates.io-index" 244 | checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" 245 | 246 | [[package]] 247 | name = "lazy_static" 248 | version = "1.4.0" 249 | source = "registry+https://github.com/rust-lang/crates.io-index" 250 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 251 | 252 | [[package]] 253 | name = "libc" 254 | version = "0.2.112" 255 | source = "registry+https://github.com/rust-lang/crates.io-index" 256 | checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125" 257 | 258 | [[package]] 259 | name = "memchr" 260 | version = "2.4.1" 261 | source = "registry+https://github.com/rust-lang/crates.io-index" 262 | checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" 263 | 264 | [[package]] 265 | name = "memoffset" 266 | version = "0.6.5" 267 | source = "registry+https://github.com/rust-lang/crates.io-index" 268 | checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" 269 | dependencies = [ 270 | "autocfg", 271 | ] 272 | 273 | [[package]] 274 | name = "num-traits" 275 | version = "0.2.14" 276 | source = "registry+https://github.com/rust-lang/crates.io-index" 277 | checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" 278 | dependencies = [ 279 | "autocfg", 280 | ] 281 | 282 | [[package]] 283 | name = "num_cpus" 284 | version = "1.13.0" 285 | source = "registry+https://github.com/rust-lang/crates.io-index" 286 | checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3" 287 | dependencies = [ 288 | "hermit-abi", 289 | "libc", 290 | ] 291 | 292 | [[package]] 293 | name = "ppv-lite86" 294 | version = "0.2.15" 295 | source = "registry+https://github.com/rust-lang/crates.io-index" 296 | checksum = "ed0cfbc8191465bed66e1718596ee0b0b35d5ee1f41c5df2189d0fe8bde535ba" 297 | 298 | [[package]] 299 | name = "proc-macro2" 300 | version = "1.0.34" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "2f84e92c0f7c9d58328b85a78557813e4bd845130db68d7184635344399423b1" 303 | dependencies = [ 304 | "unicode-xid", 305 | ] 306 | 307 | [[package]] 308 | name = "quote" 309 | version = "1.0.10" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05" 312 | dependencies = [ 313 | "proc-macro2", 314 | ] 315 | 316 | [[package]] 317 | name = "rand" 318 | version = "0.7.3" 319 | source = "registry+https://github.com/rust-lang/crates.io-index" 320 | checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" 321 | dependencies = [ 322 | "getrandom", 323 | "libc", 324 | "rand_chacha", 325 | "rand_core 0.5.1", 326 | "rand_hc", 327 | ] 328 | 329 | [[package]] 330 | name = "rand_chacha" 331 | version = "0.2.2" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" 334 | dependencies = [ 335 | "ppv-lite86", 336 | "rand_core 0.5.1", 337 | ] 338 | 339 | [[package]] 340 | name = "rand_core" 341 | version = "0.3.1" 342 | source = "registry+https://github.com/rust-lang/crates.io-index" 343 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 344 | dependencies = [ 345 | "rand_core 0.4.2", 346 | ] 347 | 348 | [[package]] 349 | name = "rand_core" 350 | version = "0.4.2" 351 | source = "registry+https://github.com/rust-lang/crates.io-index" 352 | checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" 353 | 354 | [[package]] 355 | name = "rand_core" 356 | version = "0.5.1" 357 | source = "registry+https://github.com/rust-lang/crates.io-index" 358 | checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" 359 | dependencies = [ 360 | "getrandom", 361 | ] 362 | 363 | [[package]] 364 | name = "rand_hc" 365 | version = "0.2.0" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" 368 | dependencies = [ 369 | "rand_core 0.5.1", 370 | ] 371 | 372 | [[package]] 373 | name = "rand_os" 374 | version = "0.1.3" 375 | source = "registry+https://github.com/rust-lang/crates.io-index" 376 | checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" 377 | dependencies = [ 378 | "cloudabi", 379 | "fuchsia-cprng", 380 | "libc", 381 | "rand_core 0.4.2", 382 | "rdrand", 383 | "winapi", 384 | ] 385 | 386 | [[package]] 387 | name = "rand_xoshiro" 388 | version = "0.1.0" 389 | source = "registry+https://github.com/rust-lang/crates.io-index" 390 | checksum = "03b418169fb9c46533f326efd6eed2576699c44ca92d3052a066214a8d828929" 391 | dependencies = [ 392 | "byteorder", 393 | "rand_core 0.3.1", 394 | ] 395 | 396 | [[package]] 397 | name = "rayon" 398 | version = "1.5.1" 399 | source = "registry+https://github.com/rust-lang/crates.io-index" 400 | checksum = "c06aca804d41dbc8ba42dfd964f0d01334eceb64314b9ecf7c5fad5188a06d90" 401 | dependencies = [ 402 | "autocfg", 403 | "crossbeam-deque", 404 | "either", 405 | "rayon-core", 406 | ] 407 | 408 | [[package]] 409 | name = "rayon-core" 410 | version = "1.9.1" 411 | source = "registry+https://github.com/rust-lang/crates.io-index" 412 | checksum = "d78120e2c850279833f1dd3582f730c4ab53ed95aeaaaa862a2a5c71b1656d8e" 413 | dependencies = [ 414 | "crossbeam-channel", 415 | "crossbeam-deque", 416 | "crossbeam-utils", 417 | "lazy_static", 418 | "num_cpus", 419 | ] 420 | 421 | [[package]] 422 | name = "rdrand" 423 | version = "0.4.0" 424 | source = "registry+https://github.com/rust-lang/crates.io-index" 425 | checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" 426 | dependencies = [ 427 | "rand_core 0.3.1", 428 | ] 429 | 430 | [[package]] 431 | name = "regex-automata" 432 | version = "0.1.10" 433 | source = "registry+https://github.com/rust-lang/crates.io-index" 434 | checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" 435 | 436 | [[package]] 437 | name = "rustc_version" 438 | version = "0.4.0" 439 | source = "registry+https://github.com/rust-lang/crates.io-index" 440 | checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" 441 | dependencies = [ 442 | "semver", 443 | ] 444 | 445 | [[package]] 446 | name = "ryu" 447 | version = "1.0.9" 448 | source = "registry+https://github.com/rust-lang/crates.io-index" 449 | checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" 450 | 451 | [[package]] 452 | name = "same-file" 453 | version = "1.0.6" 454 | source = "registry+https://github.com/rust-lang/crates.io-index" 455 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 456 | dependencies = [ 457 | "winapi-util", 458 | ] 459 | 460 | [[package]] 461 | name = "scopeguard" 462 | version = "1.1.0" 463 | source = "registry+https://github.com/rust-lang/crates.io-index" 464 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 465 | 466 | [[package]] 467 | name = "semver" 468 | version = "1.0.4" 469 | source = "registry+https://github.com/rust-lang/crates.io-index" 470 | checksum = "568a8e6258aa33c13358f81fd834adb854c6f7c9468520910a9b1e8fac068012" 471 | 472 | [[package]] 473 | name = "serde" 474 | version = "1.0.132" 475 | source = "registry+https://github.com/rust-lang/crates.io-index" 476 | checksum = "8b9875c23cf305cd1fd7eb77234cbb705f21ea6a72c637a5c6db5fe4b8e7f008" 477 | 478 | [[package]] 479 | name = "serde_derive" 480 | version = "1.0.132" 481 | source = "registry+https://github.com/rust-lang/crates.io-index" 482 | checksum = "ecc0db5cb2556c0e558887d9bbdcf6ac4471e83ff66cf696e5419024d1606276" 483 | dependencies = [ 484 | "proc-macro2", 485 | "quote", 486 | "syn", 487 | ] 488 | 489 | [[package]] 490 | name = "serde_json" 491 | version = "1.0.73" 492 | source = "registry+https://github.com/rust-lang/crates.io-index" 493 | checksum = "bcbd0344bc6533bc7ec56df11d42fb70f1b912351c0825ccb7211b59d8af7cf5" 494 | dependencies = [ 495 | "itoa 1.0.1", 496 | "ryu", 497 | "serde", 498 | ] 499 | 500 | [[package]] 501 | name = "syn" 502 | version = "1.0.82" 503 | source = "registry+https://github.com/rust-lang/crates.io-index" 504 | checksum = "8daf5dd0bb60cbd4137b1b587d2fc0ae729bc07cf01cd70b36a1ed5ade3b9d59" 505 | dependencies = [ 506 | "proc-macro2", 507 | "quote", 508 | "unicode-xid", 509 | ] 510 | 511 | [[package]] 512 | name = "textwrap" 513 | version = "0.11.0" 514 | source = "registry+https://github.com/rust-lang/crates.io-index" 515 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 516 | dependencies = [ 517 | "unicode-width", 518 | ] 519 | 520 | [[package]] 521 | name = "tinytemplate" 522 | version = "1.2.1" 523 | source = "registry+https://github.com/rust-lang/crates.io-index" 524 | checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" 525 | dependencies = [ 526 | "serde", 527 | "serde_json", 528 | ] 529 | 530 | [[package]] 531 | name = "unicode-width" 532 | version = "0.1.9" 533 | source = "registry+https://github.com/rust-lang/crates.io-index" 534 | checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" 535 | 536 | [[package]] 537 | name = "unicode-xid" 538 | version = "0.2.2" 539 | source = "registry+https://github.com/rust-lang/crates.io-index" 540 | checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" 541 | 542 | [[package]] 543 | name = "unicode_test" 544 | version = "0.0.1" 545 | dependencies = [ 546 | "criterion", 547 | "rand", 548 | "same-file", 549 | ] 550 | 551 | [[package]] 552 | name = "walkdir" 553 | version = "2.3.2" 554 | source = "registry+https://github.com/rust-lang/crates.io-index" 555 | checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" 556 | dependencies = [ 557 | "same-file", 558 | "winapi", 559 | "winapi-util", 560 | ] 561 | 562 | [[package]] 563 | name = "wasi" 564 | version = "0.9.0+wasi-snapshot-preview1" 565 | source = "registry+https://github.com/rust-lang/crates.io-index" 566 | checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" 567 | 568 | [[package]] 569 | name = "winapi" 570 | version = "0.3.9" 571 | source = "registry+https://github.com/rust-lang/crates.io-index" 572 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 573 | dependencies = [ 574 | "winapi-i686-pc-windows-gnu", 575 | "winapi-x86_64-pc-windows-gnu", 576 | ] 577 | 578 | [[package]] 579 | name = "winapi-i686-pc-windows-gnu" 580 | version = "0.4.0" 581 | source = "registry+https://github.com/rust-lang/crates.io-index" 582 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 583 | 584 | [[package]] 585 | name = "winapi-util" 586 | version = "0.1.5" 587 | source = "registry+https://github.com/rust-lang/crates.io-index" 588 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 589 | dependencies = [ 590 | "winapi", 591 | ] 592 | 593 | [[package]] 594 | name = "winapi-x86_64-pc-windows-gnu" 595 | version = "0.4.0" 596 | source = "registry+https://github.com/rust-lang/crates.io-index" 597 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 598 | -------------------------------------------------------------------------------- /rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "unicode_test", 5 | "benchmarks_system" 6 | ] 7 | 8 | [profile.release] 9 | lto = true 10 | codegen-units = 1 11 | -------------------------------------------------------------------------------- /rust/benchmarks_jemalloc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "benchmarks_jemalloc" 3 | version = "0.1.0" 4 | authors = ["Stephan Hügel "] 5 | 6 | [dependencies] 7 | unicode_test = { path = "../unicode_test" } 8 | criterion = "0.2" 9 | jemallocator = "0.1.8" 10 | 11 | [[bench]] 12 | name = "criterion_benchmark" 13 | harness = false 14 | -------------------------------------------------------------------------------- /rust/benchmarks_jemalloc/benches/criterion_benchmark.rs: -------------------------------------------------------------------------------- 1 | extern crate jemallocator; 2 | #[global_allocator] 3 | static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; 4 | 5 | #[macro_use] 6 | extern crate criterion; 7 | 8 | extern crate unicode_test; 9 | use unicode_test::{ 10 | bench_render_coords, bench_replacement, bench_replacement_chars, bench_replacement_chars2, 11 | bench_replacement_chars_entity_references, bench_replacement_chars_entity_references_to_chars, 12 | }; 13 | 14 | criterion_group!( 15 | benches, 16 | bench_replacement, 17 | bench_replacement_chars, 18 | bench_replacement_chars2, 19 | bench_replacement_chars_entity_references, 20 | bench_replacement_chars_entity_references_to_chars, 21 | bench_render_coords 22 | ); 23 | criterion_main!(benches); 24 | -------------------------------------------------------------------------------- /rust/benchmarks_jemalloc/src/lib.rs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /rust/benchmarks_system/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "benchmarks_system" 3 | version = "0.1.0" 4 | authors = ["Stephan Hügel "] 5 | 6 | [dependencies] 7 | unicode_test = { path = "../unicode_test" } 8 | criterion = "0.2" 9 | 10 | [[bench]] 11 | name = "criterion_benchmark" 12 | harness = false 13 | -------------------------------------------------------------------------------- /rust/benchmarks_system/benches/criterion_benchmark.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate criterion; 3 | 4 | extern crate unicode_test; 5 | use unicode_test::{ 6 | bench_replacement, 7 | bench_replacement_chars, 8 | bench_replacement_chars2, 9 | bench_replacement_chars_entity_references, 10 | bench_replacement_chars_entity_references_to_chars, 11 | bench_render_coords 12 | }; 13 | 14 | criterion_group!( 15 | benches, 16 | bench_replacement, 17 | bench_replacement_chars, 18 | bench_replacement_chars2, 19 | bench_replacement_chars_entity_references, 20 | bench_replacement_chars_entity_references_to_chars, 21 | bench_render_coords 22 | ); 23 | criterion_main!(benches); 24 | -------------------------------------------------------------------------------- /rust/benchmarks_system/src/lib.rs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /rust/unicode_test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "unicode_test" 4 | version = "0.0.1" 5 | authors = [ "Sam Pullara " ] 6 | 7 | [dependencies] 8 | criterion = "0.2" 9 | rand = "0.7.3" 10 | same-file = "1.0.6" 11 | -------------------------------------------------------------------------------- /rust/unicode_test/src/benchmark_base.rs: -------------------------------------------------------------------------------- 1 | // These functions are re-exported as public from lib.rs 2 | // this makes them available to the benchmark crates in the workspace 3 | use super::criterion::Criterion; 4 | use super::rand::Rng; 5 | use super::{ 6 | decoded_entities, entity_refs, render, render_chars, render_chars2, 7 | render_chars_entity_references, render_chars_entity_references_to_chars, render_coords, 8 | DecodedEntity, Entity, ASCII_TEXT, UNICODE_TEXT, 9 | }; 10 | 11 | // Benchmark functions 12 | pub fn generate_entities() -> Vec>> { 13 | let mut rng = rand::thread_rng(); 14 | let mut entities_list: Vec>> = Vec::with_capacity(1000); 15 | 16 | for _ in 0..1000 { 17 | let total = rng.gen::() % 10; 18 | let mut indices = Vec::with_capacity(total); 19 | for _ in 0..(total * 2) { 20 | loop { 21 | let index = rng.gen::() % ASCII_TEXT.len(); 22 | if !indices.contains(&index) { 23 | indices.push(index); 24 | break; 25 | } 26 | } 27 | } 28 | 29 | indices.sort(); 30 | let entities = indices.chunks(2).map(|chunk| { 31 | let (start, end) = (chunk[0], chunk[1]); 32 | let length = end - start; 33 | Entity { 34 | start, 35 | end, 36 | html: (0..length).map(|_| "X").collect(), 37 | } 38 | }); 39 | entities_list.push(entities.collect()); 40 | } 41 | 42 | entities_list 43 | } 44 | 45 | pub fn generate_decoded_entities() -> Vec> { 46 | generate_entities() 47 | .into_iter() 48 | .map(decoded_entities) 49 | .collect() 50 | } 51 | 52 | pub fn bench_replacement(c: &mut Criterion) { 53 | c.bench_function("replacement", |b| { 54 | let entities_list = generate_entities(); 55 | let mut index_iter = (0..1000).cycle(); 56 | b.iter(|| render(UNICODE_TEXT, &entities_list[index_iter.next().unwrap()])) 57 | }); 58 | } 59 | 60 | pub fn bench_replacement_chars(c: &mut Criterion) { 61 | c.bench_function("replacement chars", |b| { 62 | let entities_list = generate_decoded_entities(); 63 | let mut index_iter = (0..1000).cycle(); 64 | let decoded_text = UNICODE_TEXT.chars().collect(); 65 | b.iter(|| { 66 | let option = index_iter.next(); 67 | render_chars(&decoded_text, &entities_list[option.unwrap()]) 68 | }) 69 | }); 70 | } 71 | 72 | pub fn bench_replacement_chars2(c: &mut Criterion) { 73 | c.bench_function("replacement chars 2", |b| { 74 | let entities_list = generate_entities(); 75 | let mut index_iter = (0..1000).cycle(); 76 | let decoded_text = UNICODE_TEXT.chars().collect(); 77 | b.iter(|| { 78 | let option = index_iter.next(); 79 | render_chars2(&decoded_text, &entities_list[option.unwrap()]) 80 | }) 81 | }); 82 | } 83 | 84 | pub fn bench_replacement_chars_entity_references(c: &mut Criterion) { 85 | c.bench_function("replacement chars entity references", |b| { 86 | let entities_list = generate_entities(); 87 | let mut refs = Vec::with_capacity(1000); 88 | for (i, _) in entities_list.iter().enumerate() { 89 | refs.push(entity_refs(&entities_list[i])); 90 | } 91 | let mut index_iter = (0..1000).cycle(); 92 | let decoded_text = UNICODE_TEXT.chars().collect(); 93 | b.iter(|| { 94 | let option = index_iter.next(); 95 | render_chars_entity_references(&decoded_text, &refs[option.unwrap()]) 96 | }) 97 | }); 98 | } 99 | 100 | pub fn bench_replacement_chars_entity_references_to_chars(c: &mut Criterion) { 101 | c.bench_function("replacement chars entity references to chars", |b| { 102 | let entities_list = generate_decoded_entities(); 103 | let mut refs = Vec::with_capacity(1000); 104 | let mut index_iter = (0..1000).cycle(); 105 | let decoded_text = UNICODE_TEXT.chars().collect(); 106 | for (i, _) in entities_list.iter().enumerate() { 107 | refs.push(entity_refs(&entities_list[i])); 108 | } 109 | b.iter(|| { 110 | let option = index_iter.next(); 111 | render_chars_entity_references_to_chars(&decoded_text, &refs[option.unwrap()]) 112 | }) 113 | }); 114 | } 115 | 116 | // Benchmark only sorting entities and determining substitutions. 117 | pub fn bench_render_coords(c: &mut Criterion) { 118 | c.bench_function("render coords", |b| { 119 | let entities_list = generate_decoded_entities(); 120 | let mut refs = Vec::with_capacity(1000); 121 | for (i, _) in entities_list.iter().enumerate() { 122 | refs.push(entity_refs(&entities_list[i])); 123 | } 124 | let mut index_iter = (0..1000).cycle(); 125 | let decoded_text = UNICODE_TEXT.chars().collect(); 126 | let mut ht = Vec::with_capacity(64); 127 | 128 | b.iter(|| { 129 | let option = index_iter.next(); 130 | ht.clear(); 131 | // Sort entities 132 | let refs = &refs[option.unwrap()]; 133 | let mut sorted: Vec<&DecodedEntity> = Vec::with_capacity(refs.len()); 134 | for e in refs { 135 | sorted.push(e); 136 | } 137 | sorted.sort_unstable(); 138 | render_coords(&mut ht, &decoded_text, &sorted); 139 | }) 140 | }); 141 | } 142 | -------------------------------------------------------------------------------- /rust/unicode_test/src/lib.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::cmp::Ordering; 3 | extern crate criterion; 4 | extern crate rand; 5 | 6 | mod benchmark_base; 7 | pub use benchmark_base::*; 8 | 9 | pub static ASCII_TEXT: &'static str = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 10 | pub static UNICODE_TEXT: &'static str = "Attend \u{20000}\u{20000} hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 11 | 12 | #[derive(Clone, PartialEq, Hash, Eq)] 13 | pub struct Entity { 14 | start: usize, 15 | end: usize, 16 | html: T, 17 | } 18 | 19 | impl Ord for Entity { 20 | fn cmp(&self, other: &Self) -> Ordering { 21 | self.start.cmp(&other.start) 22 | } 23 | } 24 | 25 | impl PartialOrd for Entity { 26 | fn partial_cmp(&self, other: &Self) -> Option { 27 | Some(self.cmp(other)) 28 | } 29 | } 30 | 31 | pub type DecodedEntity = Entity>; 32 | 33 | impl Ord for DecodedEntity { 34 | fn cmp(&self, other: &Self) -> Ordering { 35 | self.start.cmp(&other.start) 36 | } 37 | } 38 | 39 | impl PartialOrd for DecodedEntity { 40 | fn partial_cmp(&self, other: &Self) -> Option { 41 | Some(self.cmp(other)) 42 | } 43 | } 44 | 45 | pub fn render(text: &str, entities: &Vec>) -> String { 46 | let mut sb = String::with_capacity(text.len() * 2); 47 | let mut my_entities = entities.to_owned(); 48 | my_entities.sort_by(|e1, e2| e1.start.cmp(&e2.start)); 49 | 50 | let mut pos = 0 as usize; 51 | my_entities.iter().for_each(|entity| { 52 | sb.extend(text.chars().skip(pos).take(entity.start - pos)); 53 | sb.push_str(entity.html.as_str()); 54 | pos = entity.end;}); 55 | for c in text.chars().skip(pos).take(text.chars().count() - pos) { 56 | sb.push(c); 57 | } 58 | sb 59 | } 60 | 61 | pub fn render_chars(text: &Vec, entities: &Vec) -> String { 62 | let mut sb: Vec = Vec::with_capacity(text.len() * 2); 63 | let mut my_entities = entities.to_owned(); 64 | my_entities.sort_by(|e1, e2| e1.start.cmp(&e2.start)); 65 | 66 | let mut pos = 0 as usize; 67 | my_entities.iter().for_each(|entity| { 68 | sb.extend_from_slice(&text[pos..entity.start]); 69 | sb.extend_from_slice(&entity.html); 70 | pos = entity.end; 71 | }); 72 | sb.extend_from_slice(&text[pos..text.len()]); 73 | sb.into_iter().collect() // <-- UTF-8 encoding 74 | } 75 | 76 | pub fn render_chars2(text: &Vec, entities: &Vec>) -> String { 77 | let mut my_entities = entities.to_owned(); 78 | my_entities.sort(); 79 | let mut sb = String::with_capacity(text.len() * 2); 80 | let mut pos = 0 as usize; 81 | my_entities.iter().for_each(|entity| { 82 | for item in text.iter().take(entity.start).skip(pos) { 83 | sb.push(*item); 84 | } 85 | sb.push_str(&entity.html); 86 | pos = entity.end; 87 | }); 88 | for item in text.iter().skip(pos) { 89 | sb.push(*item); 90 | } 91 | sb 92 | } 93 | 94 | pub fn render_chars_entity_references(text: &Vec, entities: &Vec<&Entity>) -> String { 95 | let mut my_entities: Vec<&Entity> = Vec::with_capacity(entities.len()); 96 | for e in entities { 97 | my_entities.push(e); 98 | } 99 | my_entities.sort(); 100 | 101 | let mut sb = String::with_capacity(text.len() * 2); 102 | let mut pos = 0 as usize; 103 | my_entities.iter().for_each(|entity| { 104 | for item in text.iter().take(entity.start).skip(pos) { 105 | sb.push(*item); 106 | } 107 | sb.push_str(&entity.html); 108 | pos = entity.end; 109 | }); 110 | for item in text.iter().skip(pos) { 111 | sb.push(*item); 112 | } 113 | sb 114 | } 115 | 116 | pub fn render_chars_entity_references_to_chars( 117 | text: &Vec, 118 | entities: &Vec<&DecodedEntity>, 119 | ) -> Vec { 120 | let mut my_entities: Vec<&DecodedEntity> = Vec::with_capacity(entities.len()); 121 | for e in entities { 122 | my_entities.push(e); 123 | } 124 | my_entities.sort_unstable(); 125 | 126 | let mut sb: Vec = Vec::with_capacity(text.len() * 2); 127 | let mut pos = 0 as usize; 128 | my_entities.iter().for_each(|entity| { 129 | sb.extend_from_slice(&text[pos..entity.start]); 130 | sb.extend_from_slice(&entity.html); 131 | pos = entity.end; 132 | }); 133 | sb.extend_from_slice(&text[pos..text.len()]); 134 | sb 135 | } 136 | 137 | #[derive(Copy, Clone, Debug)] 138 | pub struct Coord { 139 | start: usize, 140 | end: usize, 141 | } 142 | 143 | pub fn render_coords( 144 | coordinates: &mut Vec, 145 | text: &Vec, 146 | entities: &Vec<&DecodedEntity>, 147 | ) { 148 | let mut pos = 0 as usize; 149 | entities.iter().for_each(|entity| { 150 | coordinates.push(Coord { 151 | start: pos, 152 | end: entity.start, 153 | }); 154 | coordinates.push(Coord { 155 | start: 0, 156 | end: entity.html.len(), 157 | }); 158 | pos = entity.end; 159 | }); 160 | coordinates.push(Coord { 161 | start: pos, 162 | end: text.len(), 163 | }); 164 | } 165 | 166 | pub fn coordinates_to_utf8( 167 | coordinates: &Vec, 168 | text: &Vec, 169 | entities: &Vec<&DecodedEntity>, 170 | ) -> String { 171 | let mut sb = String::with_capacity(text.len() * 2); 172 | let mut in_entity = false; 173 | let mut entity_index = 0; 174 | 175 | let mut source: &Vec = text; 176 | 177 | for coord in coordinates { 178 | if in_entity { 179 | source = &entities[entity_index].html; 180 | entity_index += 1; 181 | } else { 182 | source = text; 183 | } 184 | 185 | for item in source.iter().take(coord.end).skip(coord.start) { 186 | sb.push(*item); 187 | } 188 | in_entity = !in_entity; 189 | } 190 | 191 | sb 192 | } 193 | 194 | fn main() { 195 | let result = render(&ASCII_TEXT, &entities()); 196 | println!("Result: {}", result); 197 | } 198 | 199 | pub fn entities() -> Vec> { 200 | let entities = vec![ 201 | Entity { 202 | start: 82, 203 | end: 102, 204 | html: "".to_string(), 205 | }, 206 | Entity { 207 | start: 128, 208 | end: 132, 209 | html: "<@500>".to_string(), 210 | }, 211 | Entity { 212 | start: 25, 213 | end: 32, 214 | html: "<#mobile>".to_string(), 215 | }, 216 | Entity { 217 | start: 33, 218 | end: 42, 219 | html: "<#startups>".to_string(), 220 | }, 221 | Entity { 222 | start: 111, 223 | end: 127, 224 | html: "<@sv_entrepreneur>".to_string(), 225 | }, 226 | Entity { 227 | start: 46, 228 | end: 51, 229 | html: "<#OF12>".to_string(), 230 | }, 231 | Entity { 232 | start: 103, 233 | end: 110, 234 | html: "<@TiEcon>".to_string(), 235 | }, 236 | ]; 237 | entities 238 | } 239 | 240 | pub fn decoded_entities(entities: Vec>) -> Vec { 241 | entities 242 | .iter() 243 | .map(|e| DecodedEntity { 244 | start: e.start, 245 | end: e.end, 246 | html: e.html.chars().collect(), 247 | }) 248 | .collect() 249 | } 250 | 251 | pub fn entity_refs<'a, T>(entities: &'a Vec) -> Vec<&'a T> { 252 | entities.iter().map(|e| e).collect() 253 | } 254 | 255 | #[cfg(test)] 256 | 257 | mod rendertest { 258 | use super::*; 259 | 260 | #[test] 261 | fn correctness_chars() { 262 | let result = "Attend \u{20000}\u{20000} hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 263 | assert_eq!( 264 | result, 265 | render_chars( 266 | &UNICODE_TEXT.chars().collect(), 267 | &decoded_entities(entities()) 268 | ) 269 | ) 270 | } 271 | 272 | #[test] 273 | fn correctness() { 274 | let result = "Attend \u{20000}\u{20000} hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 275 | assert_eq!(result, render(&UNICODE_TEXT, &entities())) 276 | } 277 | 278 | #[test] 279 | fn correctness_chars2() { 280 | let result = "Attend \u{20000}\u{20000} hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 281 | assert_eq!( 282 | result, 283 | render_chars2(&UNICODE_TEXT.chars().collect(), &entities()) 284 | ) 285 | } 286 | 287 | #[test] 288 | fn correctness_chars_entity_references() { 289 | let result = "Attend \u{20000}\u{20000} hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 290 | assert_eq!( 291 | result, 292 | render_chars_entity_references( 293 | &UNICODE_TEXT.chars().collect(), 294 | &entity_refs(&entities()) 295 | ) 296 | ) 297 | } 298 | 299 | #[test] 300 | fn correctness_chars_entity_reference_to_chars() { 301 | let result = "Attend \u{20000}\u{20000} hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 302 | let chars = render_chars_entity_references_to_chars( 303 | &UNICODE_TEXT.chars().collect(), 304 | &entity_refs(&decoded_entities(entities())), 305 | ); 306 | let s: String = chars.iter().collect(); 307 | assert_eq!(result, s); 308 | } 309 | 310 | #[test] 311 | fn correctness_render_steps() { 312 | let result = "Attend \u{20000}\u{20000} hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, <@TiEcon> <@sv_entrepreneur> <@500>!"; 313 | 314 | // Decode from UTF-8 315 | let decoded = &decoded_entities(entities()); 316 | let refs = &entity_refs(decoded); 317 | let text = &UNICODE_TEXT.chars().collect(); 318 | 319 | // Sort entities 320 | let mut sorted: Vec<&DecodedEntity> = Vec::with_capacity(refs.len()); 321 | for e in refs { 322 | sorted.push(e); 323 | } 324 | sorted.sort_unstable(); 325 | 326 | // Render coordinates 327 | let mut ht = Vec::with_capacity(64); 328 | render_coords(&mut ht, text, &sorted); 329 | 330 | // Encode to UTF-8 331 | let s = coordinates_to_utf8(&ht, text, &sorted); 332 | 333 | assert_eq!(result, s); 334 | } 335 | } 336 | -------------------------------------------------------------------------------- /src/main/java/interview/ArrayScan.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Set; 4 | 5 | public class ArrayScan implements Renderer { 6 | @Override 7 | public CharSequence render(CharSequence text, Set entities) { 8 | int length = text.length(); 9 | Entity[] map = new Entity[length]; 10 | int total = length; 11 | for (Entity entity : entities) { 12 | map[entity.start] = entity; 13 | total += entity.html.length() - (entity.end - entity.start); 14 | } 15 | StringBuilder sb = new StringBuilder(total); 16 | for (int i = 0; i < length; ) { 17 | Entity entity = map[i]; 18 | if (entity == null) { 19 | sb.append(text.charAt(i++)); 20 | } else { 21 | sb.append(entity.html); 22 | i = entity.end; 23 | } 24 | } 25 | return sb; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/interview/BinarySearchSort.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | /** 9 | * The classic solution. 10 | */ 11 | public class BinarySearchSort implements Renderer { 12 | public CharSequence render(CharSequence text, Set entities) { 13 | int total = text.length(); 14 | int size = entities.size(); 15 | List list = new ArrayList(size); 16 | for (Entity e : entities) { 17 | int current = list.size(); 18 | if (current == 0) { 19 | list.add(e); 20 | } else if (current == 1) { 21 | if (e.start < list.get(0).start) { 22 | list.add(0, e); 23 | } else { 24 | list.add(e); 25 | } 26 | } else { 27 | list.add(-(Collections.binarySearch(list, e) + 1), e); 28 | } 29 | } 30 | StringBuilder sb = new StringBuilder(total); 31 | int pos = 0; 32 | for (int i = 0; i < size; i++) { 33 | Entity entity = list.get(i); 34 | sb.append(text.subSequence(pos, entity.start)); 35 | sb.append(entity.html); 36 | pos = entity.end; 37 | } 38 | sb.append(text.subSequence(pos, text.length())); 39 | return sb; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/interview/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Set; 4 | 5 | /** 6 | * Rongrong Zhong 7 | */ 8 | public class BinaryTree implements Renderer { 9 | 10 | @Override 11 | public CharSequence render(CharSequence text, Set entities) { 12 | int size = text.length(); 13 | // Root is the full string initially 14 | Node root = new Node(); 15 | root.start = 0; 16 | root.end = size; 17 | 18 | // Loop over the entities, finding them in the tree, and inserting them 19 | for (Entity entity : entities) { 20 | insert(root, entity); 21 | size += (entity.end - entity.start + entity.html.length()); 22 | } 23 | 24 | // In-order traverse the tree to generate the output 25 | StringBuilder sb = new StringBuilder(size); 26 | traverse(text, root, sb); 27 | return sb; 28 | } 29 | 30 | void insert(Node node, Entity entity) { 31 | // Is the node on the left? 32 | if (entity.start <= node.start) { 33 | if (node.left != null) { 34 | // More nodes to the left 35 | insert(node.left, entity); 36 | } else { 37 | // Create the new node 38 | Node newnode = createNode(entity); 39 | // Split the current node 40 | if (node.text != null) { 41 | throw new AssertionError("Overlapping entities"); 42 | } 43 | node.start = newnode.end; 44 | node.left = newnode; 45 | } 46 | // Is the node on the right? 47 | } else if (entity.start <= node.end) { 48 | // Create the new node 49 | Node newnode = createNode(entity); 50 | // Split the current node 51 | if (node.text != null) { 52 | throw new AssertionError("Overlapping entities"); 53 | } 54 | if (entity.end <= node.end) { 55 | if (entity.end < node.end) { 56 | // Make a new right node 57 | Node right = new Node(); 58 | newnode.right = right; 59 | right.start = newnode.end; 60 | right.end = node.end; 61 | } 62 | // Make the left node 63 | Node left = new Node(); 64 | newnode.left = left; 65 | left.start = node.start; 66 | left.end = newnode.start; 67 | // Replace the parent 68 | node.text = newnode.text; 69 | node.start = newnode.start; 70 | node.end = newnode.end; 71 | node.left = newnode.left; 72 | node.right = newnode.right; 73 | } else { 74 | throw new AssertionError("Overlapping nodes"); 75 | } 76 | } else if (node.right != null) { 77 | insert(node.right, entity); 78 | } else { 79 | throw new AssertionError("Invalid tree"); 80 | } 81 | } 82 | 83 | private Node createNode(Entity entity) { 84 | Node newnode = new Node(); 85 | newnode.text = entity.html; 86 | newnode.start = entity.start; 87 | newnode.end = entity.end; 88 | return newnode; 89 | } 90 | 91 | void traverse(CharSequence text, Node node, StringBuilder sb) { 92 | if (node.left != null) { 93 | traverse(text, node.left, sb); 94 | } 95 | if (node.text == null) { 96 | sb.append(text.subSequence(node.start, node.end)); 97 | } else { 98 | sb.append(node.text); 99 | } 100 | if (node.right != null) { 101 | traverse(text, node.right, sb); 102 | } 103 | } 104 | } 105 | 106 | class Node { 107 | // Either the text or a reference into the string 108 | CharSequence text; 109 | int start; 110 | int end; 111 | Node left; 112 | Node right; 113 | } -------------------------------------------------------------------------------- /src/main/java/interview/Classic.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | import java.util.Set; 8 | 9 | /** 10 | * The classic solution. 11 | */ 12 | public class Classic implements Renderer { 13 | public CharSequence render(CharSequence text, Set entities) { 14 | StringBuilder sb = new StringBuilder(); 15 | List array = new ArrayList(entities); 16 | Collections.sort(array); 17 | int pos = 0; 18 | for (Entity entity : array) { 19 | sb.append(text.subSequence(pos, entity.start)); 20 | sb.append(entity.html); 21 | pos = entity.end; 22 | } 23 | sb.append(text.subSequence(pos, text.length())); 24 | return sb; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/interview/Entity.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Comparator; 4 | 5 | public class Entity implements Comparable, Comparator { 6 | Entity(int start, int end, CharSequence html) { 7 | this.start = start; 8 | this.end = end; 9 | this.html = html; 10 | } 11 | public int start; 12 | public int end; 13 | public CharSequence html; 14 | 15 | @Override 16 | public int compareTo(Entity o) { 17 | return start - o.start; 18 | } 19 | 20 | @Override 21 | public int compare(Entity o1, Entity o2) { 22 | return o1.start - o2.start; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/interview/HashMapScan.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | public class HashMapScan implements Renderer { 8 | @Override 9 | public CharSequence render(CharSequence text, Set entities) { 10 | Map map = new HashMap(); 11 | int length = text.length(); 12 | int total = length; 13 | for (Entity entity : entities) { 14 | map.put(entity.start, entity); 15 | total += entity.html.length() - (entity.end - entity.start); 16 | } 17 | StringBuilder sb = new StringBuilder(total); 18 | for (int i = 0; i < length; ) { 19 | Entity entity = map.get(i); 20 | if (entity == null) { 21 | sb.append(text.charAt(i++)); 22 | } else { 23 | sb.append(entity.html); 24 | i = entity.end; 25 | } 26 | } 27 | return sb; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/interview/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Set; 4 | 5 | /** 6 | * The classic solution. 7 | */ 8 | public class InsertionSort implements Renderer { 9 | public CharSequence render(CharSequence text, Set entities) { 10 | int total = text.length(); 11 | int size = entities.size(); 12 | Entity[] array = new Entity[size]; 13 | int i = 0; 14 | for (Entity entity : entities) { 15 | total += (entity.end - entity.start + entity.html.length()); 16 | int j; 17 | for (j = 0; j < i; j++) { 18 | if (entity.start < array[j].start) { 19 | System.arraycopy(array, j, array, j + 1, size - j - 1); 20 | break; 21 | } 22 | } 23 | array[j] = entity; 24 | i++; 25 | } 26 | StringBuilder sb = new StringBuilder(total); 27 | int pos = 0; 28 | for (Entity entity : array) { 29 | sb.append(text.subSequence(pos, entity.start)); 30 | sb.append(entity.html); 31 | pos = entity.end; 32 | } 33 | sb.append(text.subSequence(pos, text.length())); 34 | return sb; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/interview/LinkedListEntities.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Collections; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | /** 9 | * Inspired by the binary tree version. Left and right linearized. 10 | */ 11 | public class LinkedListEntities implements Renderer { 12 | 13 | @Override 14 | public CharSequence render(CharSequence text, Set entities) { 15 | int size = 2 * entities.size() + 1; 16 | if (size == 1) return text; 17 | List list = new LinkedList(); 18 | boolean first = true; 19 | int length = text.length(); 20 | for (Entity e : entities) { 21 | length += e.html.length() - (e.end - e.start); 22 | if (first) { 23 | // First one is easy 24 | list.add(new Entity(0, e.start, null)); 25 | list.add(e); 26 | list.add(new Entity(e.end, text.length(), null)); 27 | first = false; 28 | } else { 29 | // Find the array index 30 | int i = Collections.binarySearch(list, e); 31 | if (i < 0) i = -i - 2; 32 | Entity current = list.get(i); 33 | list.add(i + 1, e); 34 | list.add(i + 2, new Entity(e.end, current.end, null)); 35 | current.end = e.start; 36 | } 37 | } 38 | StringBuilder sb = new StringBuilder(length); 39 | for (Entity e : list) { 40 | if (e.html == null) { 41 | sb.append(text, e.start, e.end); 42 | } else { 43 | sb.append(e.html); 44 | } 45 | } 46 | return sb.toString(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/interview/OptimizedClassic.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Arrays; 4 | import java.util.Set; 5 | 6 | /** 7 | * The classic solution. 8 | */ 9 | public class OptimizedClassic implements Renderer { 10 | public CharSequence render(CharSequence text, Set entities) { 11 | Entity[] array = new Entity[entities.size()]; 12 | int capacity = text.length(); 13 | int i = 0; 14 | for (Entity entity : entities) { 15 | capacity += entity.html.length() - (entity.end - entity.start); 16 | array[i++] = entity; 17 | } 18 | StringBuilder sb = new StringBuilder(capacity); 19 | Arrays.sort(array); 20 | int pos = 0; 21 | for (Entity entity : array) { 22 | sb.append(text, pos, entity.start).append(entity.html); 23 | pos = entity.end; 24 | } 25 | sb.append(text, pos, text.length()); 26 | return sb; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/interview/OptimizedClassicWithCodePoints.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Set; 6 | 7 | /** 8 | * The classic solution. 9 | */ 10 | public class OptimizedClassicWithCodePoints implements Renderer { 11 | public CharSequence render(CharSequence text, Set entities) { 12 | var list = new ArrayList<>(entities); 13 | Collections.sort(list); 14 | var sb = new StringBuilder(text.length() * 2); 15 | var s = text.toString(); 16 | var pos = 0; 17 | var codePointPosition = 0; 18 | for (var entity : list) { 19 | var start = s.offsetByCodePoints(pos, entity.start - codePointPosition); 20 | sb.append(s, pos, start); 21 | sb.append(entity.html); 22 | codePointPosition = entity.end; 23 | pos = s.offsetByCodePoints(start, entity.end - entity.start); 24 | } 25 | sb.append(text, pos, text.length()); 26 | return sb; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/interview/Renderer.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Set; 4 | 5 | public interface Renderer { 6 | CharSequence render(CharSequence text, Set entities); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/interview/StringBuilderReplace.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Arrays; 4 | import java.util.Set; 5 | 6 | /** 7 | * The classic solution. 8 | */ 9 | public class StringBuilderReplace implements Renderer { 10 | 11 | public CharSequence render(CharSequence text, Set entities) { 12 | Entity[] array = entities.toArray(new Entity[0]); 13 | Arrays.sort(array, (o1, o2) -> o2.start - o1.start); 14 | StringBuilder sb = new StringBuilder(text.length() * 2).append(text); 15 | for (Entity entity : array) { 16 | sb.replace(entity.start, entity.end, entity.html.toString()); 17 | } 18 | return sb; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/interview/StringBuilderReplaceWithCodePoints.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Arrays; 4 | import java.util.Set; 5 | 6 | public class StringBuilderReplaceWithCodePoints implements Renderer { 7 | 8 | public CharSequence render(CharSequence text, Set entities) { 9 | var array = entities.toArray(new Entity[0]); 10 | Arrays.sort(array, (o1, o2) -> o2.start - o1.start); 11 | var sb = new StringBuilder(text.length() * 2).append(text); 12 | var s = text.toString(); 13 | var pos = 0; 14 | var codePointPosition = 0; 15 | for (Entity entity : array) { 16 | var start = s.offsetByCodePoints(pos, entity.start - codePointPosition); 17 | var end = s.offsetByCodePoints(pos, entity.end - codePointPosition); 18 | sb.replace(start, end, entity.html.toString()); 19 | codePointPosition = entity.end; 20 | pos = end; 21 | } 22 | return sb; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/interview/StringBuilderReplaceWithCodePointsAlreadySorted.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Arrays; 4 | import java.util.Set; 5 | 6 | /** 7 | * The classic solution. 8 | */ 9 | public class StringBuilderReplaceWithCodePointsAlreadySorted implements Renderer { 10 | 11 | public CharSequence render(CharSequence text, Set entities) { 12 | StringBuilder sb = new StringBuilder(text.length() * 2).append(text); 13 | String s = text.toString(); 14 | int pos = 0; 15 | int codePointPosition = 0; 16 | for (Entity entity : entities) { 17 | int start = s.offsetByCodePoints(pos, entity.start - codePointPosition); 18 | int end = s.offsetByCodePoints(pos, entity.end - codePointPosition); 19 | sb.replace(start, end, entity.html.toString()); 20 | codePointPosition = entity.end; 21 | pos = end; 22 | } 23 | return sb; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/interview/StringReplacement.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.Set; 6 | 7 | /** 8 | * The classic solution. 9 | */ 10 | public class StringReplacement implements Renderer { 11 | private static Comparator reverse = new Comparator() { 12 | @Override 13 | public int compare(Entity o1, Entity o2) { 14 | return o2.start - o1.start; 15 | } 16 | }; 17 | 18 | public CharSequence render(CharSequence text, Set entities) { 19 | Entity[] array = entities.toArray(new Entity[entities.size()]); 20 | Arrays.sort(array, reverse); 21 | for (Entity entity : array) { 22 | text = text.subSequence(0, entity.start) + entity.html.toString() + text.subSequence(entity.end, text.length()); 23 | } 24 | return text; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/interview/Tree.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import java.util.Set; 4 | import java.util.TreeSet; 5 | 6 | /** 7 | * The classic solution. 8 | */ 9 | public class Tree implements Renderer { 10 | public CharSequence render(CharSequence text, Set entities) { 11 | StringBuilder sb = new StringBuilder(256); 12 | TreeSet tree = new TreeSet(entities); 13 | int pos = 0; 14 | for (Entity entity : tree) { 15 | sb.append(text.subSequence(pos, entity.start)); 16 | sb.append(entity.html); 17 | pos = entity.end; 18 | } 19 | sb.append(text.subSequence(pos, text.length())); 20 | return sb; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/interviewkotlin/KotlinStringBuilderReplaceWithCodePoints.kt: -------------------------------------------------------------------------------- 1 | package interviewkotlin 2 | 3 | import interview.Entity 4 | import interview.Renderer 5 | import java.util.* 6 | 7 | class KotlinStringBuilderReplaceWithCodePoints : Renderer { 8 | 9 | override fun render(text: CharSequence, entities: Set): CharSequence { 10 | val array = entities.toTypedArray() 11 | Arrays.sort(array) { o1, o2 -> o2.start - o1.start } 12 | val sb = StringBuilder(text.length * 2).append(text) 13 | val s = text.toString() 14 | var pos = 0 15 | var codePointPosition = 0 16 | for (entity in array) { 17 | val start = s.offsetByCodePoints(pos, entity.start - codePointPosition) 18 | val end = s.offsetByCodePoints(pos, entity.end - codePointPosition) 19 | sb.replace(start, end, entity.html.toString()) 20 | codePointPosition = entity.end 21 | pos = end 22 | } 23 | return sb 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/interview/RendererBenchmarkTest.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import interviewkotlin.KotlinStringBuilderReplaceWithCodePoints; 4 | import org.junit.BeforeClass; 5 | import org.junit.Test; 6 | 7 | import java.lang.management.ManagementFactory; 8 | import java.lang.management.MemoryMXBean; 9 | import java.util.*; 10 | 11 | public class RendererBenchmarkTest { 12 | private static List> entitiesList; 13 | private static String text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 14 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 15 | 16 | 17 | @BeforeClass 18 | public static void setup() { 19 | entitiesList = createEntriesList(); 20 | } 21 | 22 | @Test 23 | public void testClassic() throws Exception { 24 | Renderer renderer = new Classic(); 25 | bench(renderer); 26 | memory(renderer); 27 | } 28 | 29 | @Test 30 | public void testOptimizedClassic() throws Exception { 31 | Renderer renderer = new OptimizedClassic(); 32 | bench(renderer); 33 | memory(renderer); 34 | } 35 | 36 | @Test 37 | public void testOptimizedClassicWithCodePoints() throws Exception { 38 | Renderer renderer = new OptimizedClassicWithCodePoints(); 39 | bench(renderer); 40 | memory(renderer); 41 | } 42 | 43 | @Test 44 | public void testBinaryTree() throws Exception { 45 | Renderer renderer = new BinaryTree(); 46 | bench(renderer); 47 | memory(renderer); 48 | } 49 | 50 | @Test 51 | public void testLinearNodes() throws Exception { 52 | Renderer renderer = new LinkedListEntities(); 53 | bench(renderer); 54 | memory(renderer); 55 | } 56 | 57 | @Test 58 | public void testInsertionSort() throws Exception { 59 | Renderer renderer = new InsertionSort(); 60 | bench(renderer); 61 | memory(renderer); 62 | } 63 | 64 | @Test 65 | public void testBinarySearchSort() throws Exception { 66 | Renderer renderer = new BinarySearchSort(); 67 | bench(renderer); 68 | memory(renderer); 69 | } 70 | 71 | @Test 72 | public void testTree() throws Exception { 73 | Renderer renderer = new Tree(); 74 | bench(renderer); 75 | memory(renderer); 76 | } 77 | 78 | @Test 79 | public void testStringReplacement() throws Exception { 80 | Renderer renderer = new StringReplacement(); 81 | bench(renderer); 82 | memory(renderer); 83 | } 84 | 85 | @Test 86 | public void testStringBuilderReplace() throws Exception { 87 | Renderer renderer = new StringBuilderReplace(); 88 | bench(renderer); 89 | memory(renderer); 90 | } 91 | 92 | @Test 93 | public void testStringBuilderReplaceWithCodePoints() throws Exception { 94 | Renderer renderer = new StringBuilderReplaceWithCodePoints(); 95 | bench(renderer); 96 | memory(renderer); 97 | } 98 | 99 | @Test 100 | public void testKotlinStringBuilderReplaceWithCodePoints() throws Exception { 101 | Renderer renderer = new KotlinStringBuilderReplaceWithCodePoints(); 102 | bench(renderer); 103 | memory(renderer); 104 | } 105 | 106 | @Test 107 | public void testStringBuilderReplaceWithCodePointsSorted() throws Exception { 108 | Renderer renderer = new StringBuilderReplaceWithCodePointsAlreadySorted(); 109 | benchSorted(renderer); 110 | memory(renderer); 111 | } 112 | 113 | @Test 114 | public void testHashMapScan() throws Exception { 115 | Renderer renderer = new HashMapScan(); 116 | bench(renderer); 117 | memory(renderer); 118 | } 119 | 120 | @Test 121 | public void testArrayScan() throws Exception { 122 | Renderer renderer = new ArrayScan(); 123 | bench(renderer); 124 | memory(renderer); 125 | } 126 | 127 | private void bench(Renderer renderer) { 128 | String text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 129 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 130 | List> entitiesList = createEntriesList(); 131 | 132 | { 133 | for (int j = 0; j < 10; j++) { 134 | for (int i = 0; i < 10000; i++) { 135 | renderer.render(text, entitiesList.get(i % 1000)); 136 | } 137 | long start = System.currentTimeMillis(); 138 | for (int i = 0; i < 1000000; i++) { 139 | renderer.render(text, entitiesList.get(i % 1000)); 140 | } 141 | System.out.println(renderer.getClass().getSimpleName() + ": " + (System.currentTimeMillis() - start) + " ns/op"); 142 | } 143 | } 144 | } 145 | 146 | private void benchSorted(Renderer renderer) { 147 | String text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 148 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 149 | List> entitiesList = createEntriesListSorted(); 150 | 151 | { 152 | for (int j = 0; j < 5; j++) { 153 | for (int i = 0; i < 10000; i++) { 154 | renderer.render(text, entitiesList.get(i % 1000)); 155 | } 156 | long start = System.currentTimeMillis(); 157 | for (int i = 0; i < 1000000; i++) { 158 | renderer.render(text, entitiesList.get(i % 1000)); 159 | } 160 | System.out.println(renderer.getClass().getSimpleName() + ": " + (System.currentTimeMillis() - start) + " ns/op"); 161 | } 162 | } 163 | } 164 | 165 | private void memory(Renderer renderer) { 166 | System.gc(); 167 | MemoryMXBean mxbean = ManagementFactory.getMemoryMXBean(); 168 | { 169 | long total = 0; 170 | for (int i = 0; i < 1000000; i++) { 171 | long start = mxbean.getHeapMemoryUsage().getUsed(); 172 | renderer.render(text, entitiesList.get(i % 1000)); 173 | long end = mxbean.getHeapMemoryUsage().getUsed(); 174 | long diff = end - start; 175 | if (diff > 0) { 176 | total += diff; 177 | } 178 | } 179 | System.out.println("Memory: " + renderer.getClass().getSimpleName() + ": " + total / 1000000 + " bytes/op"); 180 | } 181 | 182 | } 183 | 184 | private static List> createEntriesList() { 185 | Random r = new Random(938471093847L); 186 | List> entitiesList = new ArrayList>(); 187 | for (int i = 0; i < 1000; i++) { 188 | Set entities = new HashSet(); 189 | int total = r.nextInt(10); 190 | List indices = new ArrayList(); 191 | for (int j = 0; j < total * 2; j++) { 192 | int next; 193 | while (indices.contains(next = r.nextInt(text.length()))) ; 194 | indices.add(next); 195 | } 196 | Collections.sort(indices); 197 | for (int j = 0; j < total * 2; j += 2) { 198 | int start = indices.get(j); 199 | int end = indices.get(j + 1); 200 | int length = end - start; 201 | StringBuilder sb = new StringBuilder(length * 2); 202 | for (int k = 0; k < length; k++) { 203 | sb.append("XX"); 204 | } 205 | entities.add(new Entity(start, end, sb.toString())); 206 | } 207 | entitiesList.add(entities); 208 | } 209 | return entitiesList; 210 | } 211 | 212 | private static List> createEntriesListSorted() { 213 | Random r = new Random(938471093847L); 214 | List> entitiesList = new ArrayList>(); 215 | for (int i = 0; i < 1000; i++) { 216 | Set entities = new TreeSet(); 217 | int total = r.nextInt(10); 218 | List indices = new ArrayList(); 219 | for (int j = 0; j < total * 2; j++) { 220 | int next; 221 | while (indices.contains(next = r.nextInt(text.length()))) ; 222 | indices.add(next); 223 | } 224 | Collections.sort(indices); 225 | for (int j = 0; j < total * 2; j += 2) { 226 | int start = indices.get(j); 227 | int end = indices.get(j + 1); 228 | int length = end - start; 229 | StringBuilder sb = new StringBuilder(length * 2); 230 | for (int k = 0; k < length; k++) { 231 | sb.append("XX"); 232 | } 233 | entities.add(new Entity(start, end, sb.toString())); 234 | } 235 | entitiesList.add(entities); 236 | } 237 | return entitiesList; 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /src/test/java/interview/RendererTest.java: -------------------------------------------------------------------------------- 1 | package interview; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | import static junit.framework.Assert.assertEquals; 9 | 10 | 11 | public class RendererTest { 12 | @Test 13 | public void testClassic() throws Exception { 14 | Renderer renderer = new Classic(); 15 | test(renderer); 16 | } 17 | 18 | @Test 19 | public void testOptimizedClassic() throws Exception { 20 | Renderer renderer = new OptimizedClassic(); 21 | test(renderer); 22 | } 23 | 24 | @Test 25 | public void testOptimizedClassicWithCodePoints() throws Exception { 26 | Renderer renderer = new OptimizedClassicWithCodePoints(); 27 | testMultibyte(renderer); 28 | } 29 | 30 | @Test 31 | public void testBinaryTree() throws Exception { 32 | Renderer renderer = new BinaryTree(); 33 | test(renderer); 34 | } 35 | 36 | @Test 37 | public void testInsertionSort() throws Exception { 38 | Renderer renderer = new InsertionSort(); 39 | test(renderer); 40 | } 41 | 42 | @Test 43 | public void testBinarySearchSort() throws Exception { 44 | Renderer renderer = new BinarySearchSort(); 45 | test(renderer); 46 | } 47 | 48 | @Test 49 | public void testTree() throws Exception { 50 | Renderer renderer = new Tree(); 51 | test(renderer); 52 | } 53 | 54 | @Test 55 | public void testStringReplacement() throws Exception { 56 | Renderer renderer = new StringReplacement(); 57 | test(renderer); 58 | } 59 | 60 | @Test 61 | public void testStringBuilderReplace() throws Exception { 62 | Renderer renderer = new StringBuilderReplace(); 63 | test(renderer); 64 | } 65 | 66 | @Test 67 | public void testLinearNodes() throws Exception { 68 | Renderer renderer = new LinkedListEntities(); 69 | test(renderer); 70 | } 71 | 72 | 73 | private void test(Renderer renderer) { 74 | String text = "Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 75 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 76 | assertEquals(text, renderer.render(text, new HashSet<>()).toString()); 77 | 78 | String result = "Attend to hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, " + 79 | " <@TiEcon> <@sv_entrepreneur> <@500>!"; 80 | Set entities = getEntities(); 81 | assertEquals(result, renderer.render(text, entities).toString()); 82 | } 83 | 84 | private void testMultibyte(Renderer renderer) { 85 | String text = "Attend \uD840\uDC00\uD840\uDC00 hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, " + 86 | "http://t.co/HtzEMgAC @TiEcon @sv_entrepreneur @500!"; 87 | assertEquals(text, renderer.render(text, new HashSet<>()).toString()); 88 | 89 | String result = "Attend \uD840\uDC00\uD840\uDC00 hear 6 stellar <#mobile> <#startups> at <#OF12> Entrepreneur Idol show 2day, " + 90 | " <@TiEcon> <@sv_entrepreneur> <@500>!"; 91 | Set entities = getEntities(); 92 | assertEquals(result, renderer.render(text, entities).toString()); 93 | } 94 | 95 | private Set getEntities() { 96 | return new HashSet() {{ 97 | add(new Entity(25, 32, "<#mobile>")); 98 | add(new Entity(33, 42, "<#startups>")); 99 | add(new Entity(46, 51, "<#OF12>")); 100 | add(new Entity(82, 102, "")); 101 | add(new Entity(103, 110, "<@TiEcon>")); 102 | add(new Entity(111, 127, "<@sv_entrepreneur>")); 103 | add(new Entity(128, 132, "<@500>")); 104 | }}; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/test/java/interview/example.json: -------------------------------------------------------------------------------- 1 | {"created_at":"Sat Jun 02 08:47:48 +0000 2012", "id":208842341547642882, "id_str":"208842341547642882", 2 | "text":"Attend to hear 6 stellar #mobile #startups at #OF12 Entrepreneur Idol show 2day, http:\/\/t.co\/HtzEMgAC @TiEcon @sv_entrepreneur @500", "source":"\u003ca href=\"http:\/\/www.tweetcaster.com\" rel=\"nofollow\"\u003eTweetCaster for Android\u003c\/a\u003e", "truncated":false, "in_reply_to_status_id":null, "in_reply_to_status_id_str":null, "in_reply_to_user_id":null, "in_reply_to_user_id_str":null, "in_reply_to_screen_name":null, "user":{ 3 | "id":154618002, 4 | "id_str":"154618002", 5 | "name":"Sabrina", 6 | "screen_name":"sailingship2day", 7 | "location":"", 8 | "description":"Semiconductor processing & Chip Design expert, currently exploring Mobile Health ventures. Engineer, Skier, Sailor, Artist, Pianist & Gourmet Chef.", 9 | "url":null, 10 | "protected":false, 11 | "followers_count":218, 12 | "friends_count":429, 13 | "listed_count":3, 14 | "created_at":"Fri Jun 11 18:57:14 +0000 2010", 15 | "favourites_count":4, 16 | "utc_offset":null, 17 | "time_zone":null, 18 | "geo_enabled":false, 19 | "verified":false, 20 | "statuses_count":2131, 21 | "lang":"en", 22 | "contributors_enabled":false, 23 | "is_translator":false, 24 | "profile_background_color":"B2DFDA", 25 | "profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme13\/bg.gif", 26 | "profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme13\/bg.gif", 27 | "profile_background_tile":false, 28 | "profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1291157737\/aishwarya-rai_normal.jpg", 29 | "profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1291157737\/aishwarya-rai_normal.jpg", 30 | "profile_link_color":"93A644", 31 | "profile_sidebar_border_color":"EEEEEE", 32 | "profile_sidebar_fill_color":"FFFFFF", 33 | "profile_text_color":"333333", 34 | "profile_use_background_image":true, 35 | "show_all_inline_media":false, 36 | "default_profile":false, 37 | "default_profile_image":false, 38 | "following":null, 39 | "follow_request_sent":null, 40 | "notifications":null 41 | }, "geo":null, "coordinates":null, "place":null, "contributors":null, "retweet_count":1, "entities":{ 42 | "hashtags":[ 43 | { 44 | "text":"mobile", 45 | "indices":[25, 32] 46 | }, 47 | { 48 | "text":"startups", 49 | "indices":[33, 42] 50 | }, 51 | { 52 | "text":"OF12", 53 | "indices":[46, 51] 54 | } 55 | ], 56 | "urls":[ 57 | { 58 | "url":"http:\/\/t.co\/HtzEMgAC", 59 | "expanded_url":"http:\/\/ow.ly\/beCEW", 60 | "display_url":"ow.ly\/beCEW", 61 | "indices":[82, 102] 62 | } 63 | ], 64 | "user_mentions":[ 65 | { 66 | "screen_name":"TiEcon", 67 | "name":"TiEcon 2012", 68 | "id":14045162, 69 | "id_str":"14045162", 70 | "indices":[103, 110] 71 | }, 72 | { 73 | "screen_name":"sv_entrepreneur", 74 | "name":"SV Entrepreneurs", 75 | "id":283347598, 76 | "id_str":"283347598", 77 | "indices":[111, 127] 78 | }, 79 | { 80 | "screen_name":"500", 81 | "name":"500 Startups", 82 | "id":168857946, 83 | "id_str":"168857946", 84 | "indices":[128, 132] 85 | } 86 | ] 87 | }, "favorited":false, "retweeted":false, "possibly_sensitive":false} --------------------------------------------------------------------------------