diff --git a/.classpath b/.classpath index ee32f6f5..a2f43c32 100644 --- a/.classpath +++ b/.classpath @@ -1,8 +1,8 @@ - - - - - - - - + + + + + + + + diff --git a/.gitignore b/.gitignore index 23842834..ba3d4bc6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -/bin/ -/build/ -/dist/ +/bin/ +/build/ +/dist/ diff --git a/.project b/.project index 3cd55b5c..e691fcf5 100644 --- a/.project +++ b/.project @@ -1,17 +1,17 @@ - - - JavaAlgorithmsImplementation - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - + + + JavaAlgorithmsImplementation + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/.travis.yml b/.travis.yml index 3a3703f6..14885042 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,34 +1,34 @@ -before_script: - - sudo apt-get install ant-optional - - export OPTS="-server -Xmx3072M" - - export JAVA_OPTS="${JAVA_OPTS} ${OPTS}" - - export ANT_OPTS="${ANT_OPTS} ${OPTS}" - - echo $JAVA_OPTS - - echo $ANT_OPTS - -dist: trusty - -language: java - -jdk: - - oraclejdk9 - - oraclejdk8 -# - oraclejdk7 -# - oraclejdk6 - -# - openjdk9 - - openjdk8 - - openjdk7 -# - openjdk6 - -env: - - TEST_SUITE=run_tests -# - TEST_SUITE=mathematics -# - TEST_SUITE=numbers -# - TEST_SUITE=search -# - TEST_SUITE=sequences -# - TEST_SUITE=strings -# - TEST_SUITE=data_structures -# - TEST_SUITE=sorts - -script: "ant $TEST_SUITE" +before_script: + - sudo apt-get install ant-optional + - export OPTS="-server -Xmx3072M" + - export JAVA_OPTS="${JAVA_OPTS} ${OPTS}" + - export ANT_OPTS="${ANT_OPTS} ${OPTS}" + - echo $JAVA_OPTS + - echo $ANT_OPTS + +dist: trusty + +language: java + +jdk: + - oraclejdk9 + - oraclejdk8 +# - oraclejdk7 +# - oraclejdk6 + +# - openjdk9 + - openjdk8 + - openjdk7 +# - openjdk6 + +env: + - TEST_SUITE=run_tests +# - TEST_SUITE=mathematics +# - TEST_SUITE=numbers +# - TEST_SUITE=search +# - TEST_SUITE=sequences +# - TEST_SUITE=strings +# - TEST_SUITE=data_structures +# - TEST_SUITE=sorts + +script: "ant $TEST_SUITE" diff --git a/DisjointSetTests.java b/DisjointSetTests.java new file mode 100644 index 00000000..4c32de1f --- /dev/null +++ b/DisjointSetTests.java @@ -0,0 +1,184 @@ +package com.jwetherell.algorithms.data_structures.test; + +import org.junit.Assert; +import org.junit.Test; + +import com.jwetherell.algorithms.data_structures.DisjointSet; + +@SuppressWarnings("unchecked") +public class DisjointSetTests { + + private static boolean DEBUG = false; + + @Test + public void testDisjointSet1() { + final int maximum = 10; + final int[] array = new int[maximum]; + for (int i = 0; i < array.length; i++) + array[i] = i + 1; + + final DisjointSet.Item[] items = new DisjointSet.Item[array.length]; + for (int i = 0; i < items.length; i++) { + final int v = array[i]; + final DisjointSet.Item s = DisjointSet.makeSet(v); + items[i] = s; + final DisjointSet.Item f = DisjointSet.find(s); + Assert.assertTrue(f != null); + Assert.assertTrue(f.getValue() == v); + } + if (DEBUG) + System.out.println(toString(items)); + + final int half = items.length / 2; + + // first half set + DisjointSet.Item first = items[0]; + for (int i = 1; i < half; i++) { + final DisjointSet.Item item = items[i]; + first = DisjointSet.union(first, item); + } + if (DEBUG) + System.out.println(toString(items)); + // second half set + DisjointSet.Item second = items[half]; + for (int i = half + 1; i < items.length; i++) { + final DisjointSet.Item item = items[i]; + second = DisjointSet.union(second, item); + } + if (DEBUG) + System.out.println(toString(items)); + + // Make sure all items in first set are actually in first set and vice versa + for (int i = 0; i < half; i++) { + final DisjointSet.Item item = items[i]; + final DisjointSet.Item result = DisjointSet.find(item); + Assert.assertTrue(result.equals(first)); + } + for (int i = half; i < items.length; i++) { + final DisjointSet.Item item = items[i]; + final DisjointSet.Item result = DisjointSet.find(item); + Assert.assertTrue(result.equals(second)); + } + + // merge second set and the first set and make sure the superset is created + DisjointSet.Item superSet = first; + for (int i = 0; i < items.length; i++) { + final DisjointSet.Item item = items[i]; + superSet = DisjointSet.union(superSet, item); + } + if (DEBUG) + System.out.println(toString(items)); + for (int i = 0; i < items.length; i++) { + final DisjointSet.Item item = items[i]; + final DisjointSet.Item result = DisjointSet.find(item); + Assert.assertTrue(result.equals(superSet)); + } + } + + @Test + public void testDisjointSet2() { + final int maximum = 10; + final int[] array = new int[maximum]; + for (int i = 0; i < array.length; i++) + array[i] = i + 1; + + final DisjointSet.Item[] items = new DisjointSet.Item[array.length]; + for (int i = 0; i < items.length; i++) { + final int v = array[i]; + final DisjointSet.Item s = DisjointSet.makeSet(v); + items[i] = s; + final DisjointSet.Item f = DisjointSet.find(s); + Assert.assertTrue(f != null); + Assert.assertTrue(f.getValue() == v); + } + if (DEBUG) + System.out.println(toString(items)); + + final int quarter = items.length / 4; + + DisjointSet.Item i1 = items[0]; + for (int i = 1; i < quarter; i++) { + final DisjointSet.Item item = items[i]; + i1 = DisjointSet.union(i1, item); + } + DisjointSet.Item i2 = items[quarter]; + for (int i = quarter + 1; i < 2 * quarter; i++) { + final DisjointSet.Item item = items[i]; + i2 = DisjointSet.union(i2, item); + } + DisjointSet.Item i3 = items[2 * quarter]; + for (int i = 2 * quarter + 1; i < 3 * quarter; i++) { + final DisjointSet.Item item = items[i]; + i3 = DisjointSet.union(i3, item); + } + DisjointSet.Item i4 = items[3 * quarter]; + for (int i = 3 * quarter + 1; i < array.length; i++) { + final DisjointSet.Item item = items[i]; + i4 = DisjointSet.union(i4, item); + } + if (DEBUG) + System.out.println(toString(items)); + + DisjointSet.Item s1 = DisjointSet.union(i1, i2); + DisjointSet.Item s2 = DisjointSet.union(i3, i4); + DisjointSet.Item s3 = DisjointSet.union(s1, s2); + Assert.assertTrue(s3.getValue() == 1 && s3.getRank() == 3); + if (DEBUG) + System.out.println(toString(items)); + } + + private static final String toString(DisjointSet.Item[] items) { + final StringBuilder builder = new StringBuilder(); + builder.append("{\n"); + for (DisjointSet.Item item : items) { + builder.append('\t').append(item.toString()).append('\n'); + } + builder.append("}\n"); + return builder.toString(); + } + + @Test + public void testDisjointSet3() { + final int maximum = 10; + final int[] arr = new int[maximum]; + for (int i = 0; i < arr.length; i++) + arr[i] = i + 1; + final DisjointSet.Item[] items = new DisjointSet.Item[arr.length]; + for (int i = 0; i < items.length; i++) { + final int v = arr[i]; + final DisjointSet.Item s = DisjointSet.makeSet(v); + items[i] = s; + } + DisjointSet.Item i1 = items[0]; + DisjointSet.Item i2 = items[1]; + DisjointSet.Item i3 = items[2]; + DisjointSet.Item i4 = items[3]; + + final DisjointSet.Item xRoot = DisjointSet.union(null, i1); + Assert.assertTrue(xRoot.getValue() == i1.getValue()); + + final DisjointSet.Item yRoot = DisjointSet.union(i2, null); + Assert.assertTrue(yRoot.getValue() == i2.getValue()); + + final DisjointSet.Item equalRoots = DisjointSet.union(i2, i2); + Assert.assertTrue(equalRoots.getValue() == i2.getValue()); + + Assert.assertNull(DisjointSet.find(null)); + + Assert.assertNull(DisjointSet.union(null, null)); + + DisjointSet.Item unequalIt1 = DisjointSet.union(i1, i2); + Assert.assertNotNull(unequalIt1); + DisjointSet.Item unequalIt2 = DisjointSet.union(i1, i3); + Assert.assertNotNull(unequalIt2); + DisjointSet.Item unequalIt3 = DisjointSet.union(i4, i1); + Assert.assertNotNull(unequalIt3); + + Assert.assertFalse(unequalIt1.equals("False")); + + String iString = i2.toString(); + String expected = "parent=1 value=2"; + Assert.assertTrue(iString.equals(expected)); + + } +} diff --git a/LICENSE b/LICENSE index e06d2081..7b216eb0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,202 +1,202 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 3c921d47..951fac42 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,15 +1,15 @@ - - - -#### By submitting this pull request I confirm I've read and complied with the below requirements. - -- [ ] I have read the [Contribution guidelines](CONTRIBUTING.md) and I am confident that my PR reflects them. -- [ ] I have followed the [coding guidelines](CONTRIBUTING.md#cs) for this project. -- [ ] My code follows the [skeleton code structure](CONTRIBUTING.md#sample). -- [ ] This pull request has a descriptive title. For example, `Added {Algorithm/DS name} [{Language}]`, not `Update README.md` or `Added new code`. + + + +#### By submitting this pull request I confirm I've read and complied with the below requirements. + +- [ ] I have read the [Contribution guidelines](CONTRIBUTING.md) and I am confident that my PR reflects them. +- [ ] I have followed the [coding guidelines](CONTRIBUTING.md#cs) for this project. +- [ ] My code follows the [skeleton code structure](CONTRIBUTING.md#sample). +- [ ] This pull request has a descriptive title. For example, `Added {Algorithm/DS name} [{Language}]`, not `Update README.md` or `Added new code`. diff --git a/README.md b/README.md index f4d8bf3a..91d14ac2 100644 --- a/README.md +++ b/README.md @@ -1,220 +1,220 @@ -Java : Algorithms and Data Structure ![alt tag](https://api.travis-ci.org/phishman3579/java-algorithms-implementation.svg?branch=master) -============================== - -The algorithms and data structures are implemented in Java. - -This is a collection of algorithms and data structures I've implemented in my academic and professional life. The code isn't optimized but is written to be correct and readable. The algorithms and data structures are tested and, unless noted, believed to be correct. - -## Created by Justin Wetherell - -* For questions use: http://groups.google.com/forum/#!forum/java-algorithms-implementation -* Google: http://code.google.com/p/java-algorithms-implementation -* Github: http://github.com/phishman3579/java-algorithms-implementation -* LinkedIn: http://www.linkedin.com/in/phishman3579 -* E-mail: phishman3579@gmail.com -* Twitter: http://twitter.com/phishman3579 - -## Support me with a donation - -Donate to this project - -# What's been implemented: - -## Table of Contents -- [Data Structures](#data-structures) -- [Mathematics](#mathematics) -- [Numbers](#numbers) -- [Graphs](#graphs) -- [Search](#search) -- [Sequences](#sequences) -- [Sorts](#sorts) -- [String Functions](#string-functions) - -## Data Structures -* [AVL Tree](src/com/jwetherell/algorithms/data_structures/AVLTree.java) -* [B-Tree](src/com/jwetherell/algorithms/data_structures/BTree.java) -* [Binary Heap (backed by an array or a tree)](src/com/jwetherell/algorithms/data_structures/BinaryHeap.java) -* [Binary Search Tree](src/com/jwetherell/algorithms/data_structures/BinarySearchTree.java) -* [Compact Suffix Trie (backed by a Patricia Trie)](src/com/jwetherell/algorithms/data_structures/CompactSuffixTrie.java) -* [Disjoint Set](src/com/jwetherell/algorithms/data_structures/DisjointSet.java) -* [Fenwick Tree {Binary Indexed Tree (BIT)}](src/com/jwetherell/algorithms/data_structures/FenwickTree.java) -* [Graph](src/com/jwetherell/algorithms/data_structures/Graph.java) - + Undirected - + Directed (Digraph) -* [Hash Array Mapped Trie (HAMT)](src/com/jwetherell/algorithms/data_structures/HashArrayMappedTrie.java) -* [Hash Map (associative array)](src/com/jwetherell/algorithms/data_structures/HashMap.java) -* [Interval Tree](src/com/jwetherell/algorithms/data_structures/IntervalTree.java) -* [Implicit Key Treap](src/com/jwetherell/algorithms/data_structures/ImplicitKeyTreap.java) -* [KD Tree (k-dimensional tree or k-d tree)](src/com/jwetherell/algorithms/data_structures/KdTree.java) -* [List [backed by an array or a linked list]](src/com/jwetherell/algorithms/data_structures/List.java) -* [LCP Array (Longest Common Prefix) [backed by a Suffix Array]](src/com/jwetherell/algorithms/data_structures/LCPArray.java) -* [Matrix](src/com/jwetherell/algorithms/data_structures/Matrix.java) -* [Patricia Trie](src/com/jwetherell/algorithms/data_structures/PatriciaTrie.java) -* [Quad-Tree (Point-Region or MX-CIF)](src/com/jwetherell/algorithms/data_structures/QuadTree.java) -* [Queue [backed by an array or a linked list]](src/com/jwetherell/algorithms/data_structures/Queue.java) -* [Radix Trie (associative array) [backed by a Patricia Trie]](src/com/jwetherell/algorithms/data_structures/RadixTrie.java) -* [Red-Black Tree](src/com/jwetherell/algorithms/data_structures/RedBlackTree.java) -* [Segment Tree](src/com/jwetherell/algorithms/data_structures/SegmentTree.java) -* [Skip List](src/com/jwetherell/algorithms/data_structures/SkipList.java) -* [Splay Tree](src/com/jwetherell/algorithms/data_structures/SplayTree.java) -* [Stack [backed by an array or a linked list]](src/com/jwetherell/algorithms/data_structures/Stack.java) -* [Suffix Array](src/com/jwetherell/algorithms/data_structures/SuffixArray.java) -* [Suffix Tree (Ukkonen's algorithm)](src/com/jwetherell/algorithms/data_structures/SuffixTree.java) -* [Suffix Trie [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/SuffixTrie.java) -* [Ternary Search Tree](src/com/jwetherell/algorithms/data_structures/TernarySearchTree.java) -* [Treap](src/com/jwetherell/algorithms/data_structures/Treap.java) -* [Tree](src/com/jwetherell/algorithms/data_structures/Tree.java) -* [Tree Map (associative array) [backed by an AVL Tree]](src/com/jwetherell/algorithms/data_structures/TreeMap.java) -* [Trie](src/com/jwetherell/algorithms/data_structures/Trie.java) -* [Trie Map (associative array) [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/TrieMap.java) - -## Mathematics -* [Distance](src/com/jwetherell/algorithms/mathematics/Distance.java) - + chebyshev - + euclidean -* [Division](src/com/jwetherell/algorithms/mathematics/Division.java) - + using a loop - + using recursion - + using shifts and multiplication - + using only shifts - + using logarithm -* [Multiplication](src/com/jwetherell/algorithms/mathematics/Multiplication.java) - + using a loop - + using recursion - + using only shifts - + using logarithms - + [Fast Fourier Transform](src/com/jwetherell/algorithms/mathematics/FastFourierTransform.java) -* [Exponentiation](src/com/jwetherell/algorithms/mathematics/Exponentiation.java) - + recursive exponentiation - + fast recursive exponentiation - + fast modular recursive exponentiation -* [Primes](src/com/jwetherell/algorithms/mathematics/Primes.java) - + is prime - + prime factorization - + sieve of eratosthenes - + Miller-Rabin test - + [Co-Primes (relatively prime, mutually prime)](src/com/jwetherell/algorithms/mathematics/Coprimes.java) - + [Greatest Common Divisor](src/com/jwetherell/algorithms/mathematics/GreatestCommonDivisor.java) - - using Euclid's algorithm - - using recursion -* [Permutations](src/com/jwetherell/algorithms/mathematics/Permutations.java) - + strings - + numbers -* [Modular arithmetic](src/com/jwetherell/algorithms/mathematics/Modular.java) - + add - + subtract - + multiply - + divide - + power -* [Knapsack](src/com/jwetherell/algorithms/mathematics/Knapsack.java) -* [Ramer Douglas Peucker](src/com/jwetherell/algorithms/mathematics/RamerDouglasPeucker.java) - -## Numbers -* [Integers](src/com/jwetherell/algorithms/numbers/Integers.java) - + to binary String - - using divide and modulus - - using right shift and modulus - - using BigDecimal - - using divide and double - + is a power of 2 - - using a loop - - using recursion - - using logarithm - - using bits - + to English (e.g. 1 would return "one") -* [Longs](src/com/jwetherell/algorithms/numbers/Longs.java) - + to binary String - - using divide and modulus - - using right shift and modulus - - using BigDecimal -* [Complex](src/com/jwetherell/algorithms/numbers/Complex.java) - + addition - + subtraction - + multiplication - + absolute value - + polar value - -## Graphs -* Find shortest path(s) in a Graph from a starting Vertex - - [Dijkstra's algorithm (non-negative weight graphs)](src/com/jwetherell/algorithms/graph/Dijkstra.java) - - [Bellman-Ford algorithm (negative and positive weight graphs)](src/com/jwetherell/algorithms/graph/BellmanFord.java) -* Find minimum spanning tree - - [Prim's (undirected graphs)](src/com/jwetherell/algorithms/graph/Prim.java) - - [Kruskal's (undirected graphs)](src/com/jwetherell/algorithms/graph/Kruskal.java) -* Find all pairs shortest path - - [Johnsons's algorithm (negative and positive weight graphs)](src/com/jwetherell/algorithms/graph/Johnsons.java) - - [Floyd-Warshall (negative and positive weight graphs)](src/com/jwetherell/algorithms/graph/FloydWarshall.java) -* [Cycle detection](src/com/jwetherell/algorithms/graph/CycleDetection.java) - - Depth first search while keeping track of visited Verticies - - [Connected Components](src/com/jwetherell/algorithms/graph/ConnectedComponents.java) -* [Topological sort](src/com/jwetherell/algorithms/graph/TopologicalSort.java) -* [A* path finding algorithm](src/com/jwetherell/algorithms/graph/AStar.java) -* Maximum flow - - [Push-Relabel](src/com/jwetherell/algorithms/graph/PushRelabel.java) -* Graph Traversal - - [Depth First Traversal](src/com/jwetherell/algorithms/graph/DepthFirstTraversal.java) - - [Breadth First Traversal](src/com/jwetherell/algorithms/graph/BreadthFirstTraversal.java) -* [Edmonds Karp](src/com/jwetherell/algorithms/graph/EdmondsKarp.java) -* Matching - - [Turbo Matching](src/com/jwetherell/algorithms/graph/TurboMatching.java) -* [Lowest common ancestor in tree](src/com/jwetherell/algorithms/data_structures/Tree.java) - - -## Search -* Get index of value in array - + [Linear](src/com/jwetherell/algorithms/search/LinearSearch.java) - + [Quickselect](src/com/jwetherell/algorithms/search/QuickSelect.java) - + [Binary [sorted array input only]](src/com/jwetherell/algorithms/search/BinarySearch.java) - + [Lower bound [sorted array input only]](src/com/jwetherell/algorithms/search/LowerBound.java) - + [Upper bound [sorted array input only]](src/com/jwetherell/algorithms/search/UpperBound.java) - + Optimized binary (binary until a threashold then linear) [sorted array input only] - + [Interpolation [sorted array input only]](src/com/jwetherell/algorithms/search/InterpolationSearch.java) - -## Sequences -* [Find longest common subsequence (dynamic programming)](src/com/jwetherell/algorithms/sequence/LongestCommonSubsequence.java) -* [Find longest increasing subsequence (dynamic programming)](src/com/jwetherell/algorithms/sequence/LongestIncreasingSubsequence.java) -* [Find number of times a subsequence occurs in a sequence (dynamic programming)](src/com/jwetherell/algorithms/sequence/SubsequenceCounter.java) -* [Find i-th element in a Fibonacci sequence](src/com/jwetherell/algorithms/sequence/FibonacciSequence.java) - + using a loop - + using recursion - + using matrix multiplication - + using Binet's formula -* [Find total of all elements in a sequence(Arithmetic Progression)](src/com/jwetherell/algorithms/sequence/ArithmeticProgression.java) - + using a loop - + using Triangular numbers -* [Largest sum of contiguous subarray (Kadane's algorithm)](src/com/jwetherell/algorithms/sequence/LargestSumContiguousSubarray.java) -* [Longest palin­dromic sub­se­quence (dynamic programming)](src/com/jwetherell/algorithms/sequence/LongestPalindromicSubsequence.java) - -## Sorts -* [American Flag Sort](src/com/jwetherell/algorithms/sorts/AmericanFlagSort.java) -* [Bubble Sort](src/com/jwetherell/algorithms/sorts/BubbleSort.java) -* [Counting Sort (Integers only)](src/com/jwetherell/algorithms/sorts/CountingSort.java) -* [Heap Sort](src/com/jwetherell/algorithms/sorts/HeapSort.java) -* [Insertion Sort](src/com/jwetherell/algorithms/sorts/InsertionSort.java) -* [Merge Sort](src/com/jwetherell/algorithms/sorts/MergeSort.java) -* [Quick Sort](src/com/jwetherell/algorithms/sorts/QuickSort.java) -* [Radix Sort (Integers only)](src/com/jwetherell/algorithms/sorts/RadixSort.java) -* [Shell's Sort](src/com/jwetherell/algorithms/sorts/ShellSort.java) - -## String Functions -### [String Functions](src/com/jwetherell/algorithms/strings/StringFunctions.java) -* Reverse characters in a string - + using additional storage (a String or StringBuilder) - + using in-place swaps - + using in-place XOR -* Reverse words in a string - + using char swaps and additional storage (a StringBuilder) - + using StringTokenizer and additional (a String) - + using split() method and additional storage (a StringBuilder and String[]) - + using in-place swaps -* Is Palindrome - + using additional storage (a StringBuilder) - + using in-place symetric element compares -* Subsets of characters in a String -* Edit (Levenshtein) Distance of two Strings (Recursive, Iterative) -### [Manacher's algorithm (Find the longest Palindrome)](src/com/jwetherell/algorithms/strings/Manacher.java) -### [KMP (Knuth–Morris–Pratt) Algorithm - Length of maximal prefix-suffix for each prefix](src/com/jwetherell/algorithms/strings/KnuthMorrisPratt.java) -### [String rotations](src/com/jwetherell/algorithms/strings/Rotation.java) - + Find in lexicographically minimal string rotation - + Find in lexicographically maximal string rotation - +Java : Algorithms and Data Structure ![alt tag](https://api.travis-ci.org/phishman3579/java-algorithms-implementation.svg?branch=master) +============================== + +The algorithms and data structures are implemented in Java. + +This is a collection of algorithms and data structures I've implemented in my academic and professional life. The code isn't optimized but is written to be correct and readable. The algorithms and data structures are tested and, unless noted, believed to be correct. + +## Created by Justin Wetherell + +* For questions use: http://groups.google.com/forum/#!forum/java-algorithms-implementation +* Google: http://code.google.com/p/java-algorithms-implementation +* Github: http://github.com/phishman3579/java-algorithms-implementation +* LinkedIn: http://www.linkedin.com/in/phishman3579 +* E-mail: phishman3579@gmail.com +* Twitter: http://twitter.com/phishman3579 + +## Support me with a donation + +Donate to this project + +# What's been implemented: + +## Table of Contents +- [Data Structures](#data-structures) +- [Mathematics](#mathematics) +- [Numbers](#numbers) +- [Graphs](#graphs) +- [Search](#search) +- [Sequences](#sequences) +- [Sorts](#sorts) +- [String Functions](#string-functions) + +## Data Structures +* [AVL Tree](src/com/jwetherell/algorithms/data_structures/AVLTree.java) +* [B-Tree](src/com/jwetherell/algorithms/data_structures/BTree.java) +* [Binary Heap (backed by an array or a tree)](src/com/jwetherell/algorithms/data_structures/BinaryHeap.java) +* [Binary Search Tree](src/com/jwetherell/algorithms/data_structures/BinarySearchTree.java) +* [Compact Suffix Trie (backed by a Patricia Trie)](src/com/jwetherell/algorithms/data_structures/CompactSuffixTrie.java) +* [Disjoint Set](src/com/jwetherell/algorithms/data_structures/DisjointSet.java) +* [Fenwick Tree {Binary Indexed Tree (BIT)}](src/com/jwetherell/algorithms/data_structures/FenwickTree.java) +* [Graph](src/com/jwetherell/algorithms/data_structures/Graph.java) + + Undirected + + Directed (Digraph) +* [Hash Array Mapped Trie (HAMT)](src/com/jwetherell/algorithms/data_structures/HashArrayMappedTrie.java) +* [Hash Map (associative array)](src/com/jwetherell/algorithms/data_structures/HashMap.java) +* [Interval Tree](src/com/jwetherell/algorithms/data_structures/IntervalTree.java) +* [Implicit Key Treap](src/com/jwetherell/algorithms/data_structures/ImplicitKeyTreap.java) +* [KD Tree (k-dimensional tree or k-d tree)](src/com/jwetherell/algorithms/data_structures/KdTree.java) +* [List [backed by an array or a linked list]](src/com/jwetherell/algorithms/data_structures/List.java) +* [LCP Array (Longest Common Prefix) [backed by a Suffix Array]](src/com/jwetherell/algorithms/data_structures/LCPArray.java) +* [Matrix](src/com/jwetherell/algorithms/data_structures/Matrix.java) +* [Patricia Trie](src/com/jwetherell/algorithms/data_structures/PatriciaTrie.java) +* [Quad-Tree (Point-Region or MX-CIF)](src/com/jwetherell/algorithms/data_structures/QuadTree.java) +* [Queue [backed by an array or a linked list]](src/com/jwetherell/algorithms/data_structures/Queue.java) +* [Radix Trie (associative array) [backed by a Patricia Trie]](src/com/jwetherell/algorithms/data_structures/RadixTrie.java) +* [Red-Black Tree](src/com/jwetherell/algorithms/data_structures/RedBlackTree.java) +* [Segment Tree](src/com/jwetherell/algorithms/data_structures/SegmentTree.java) +* [Skip List](src/com/jwetherell/algorithms/data_structures/SkipList.java) +* [Splay Tree](src/com/jwetherell/algorithms/data_structures/SplayTree.java) +* [Stack [backed by an array or a linked list]](src/com/jwetherell/algorithms/data_structures/Stack.java) +* [Suffix Array](src/com/jwetherell/algorithms/data_structures/SuffixArray.java) +* [Suffix Tree (Ukkonen's algorithm)](src/com/jwetherell/algorithms/data_structures/SuffixTree.java) +* [Suffix Trie [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/SuffixTrie.java) +* [Ternary Search Tree](src/com/jwetherell/algorithms/data_structures/TernarySearchTree.java) +* [Treap](src/com/jwetherell/algorithms/data_structures/Treap.java) +* [Tree](src/com/jwetherell/algorithms/data_structures/Tree.java) +* [Tree Map (associative array) [backed by an AVL Tree]](src/com/jwetherell/algorithms/data_structures/TreeMap.java) +* [Trie](src/com/jwetherell/algorithms/data_structures/Trie.java) +* [Trie Map (associative array) [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/TrieMap.java) + +## Mathematics +* [Distance](src/com/jwetherell/algorithms/mathematics/Distance.java) + + chebyshev + + euclidean +* [Division](src/com/jwetherell/algorithms/mathematics/Division.java) + + using a loop + + using recursion + + using shifts and multiplication + + using only shifts + + using logarithm +* [Multiplication](src/com/jwetherell/algorithms/mathematics/Multiplication.java) + + using a loop + + using recursion + + using only shifts + + using logarithms + + [Fast Fourier Transform](src/com/jwetherell/algorithms/mathematics/FastFourierTransform.java) +* [Exponentiation](src/com/jwetherell/algorithms/mathematics/Exponentiation.java) + + recursive exponentiation + + fast recursive exponentiation + + fast modular recursive exponentiation +* [Primes](src/com/jwetherell/algorithms/mathematics/Primes.java) + + is prime + + prime factorization + + sieve of eratosthenes + + Miller-Rabin test + + [Co-Primes (relatively prime, mutually prime)](src/com/jwetherell/algorithms/mathematics/Coprimes.java) + + [Greatest Common Divisor](src/com/jwetherell/algorithms/mathematics/GreatestCommonDivisor.java) + - using Euclid's algorithm + - using recursion +* [Permutations](src/com/jwetherell/algorithms/mathematics/Permutations.java) + + strings + + numbers +* [Modular arithmetic](src/com/jwetherell/algorithms/mathematics/Modular.java) + + add + + subtract + + multiply + + divide + + power +* [Knapsack](src/com/jwetherell/algorithms/mathematics/Knapsack.java) +* [Ramer Douglas Peucker](src/com/jwetherell/algorithms/mathematics/RamerDouglasPeucker.java) + +## Numbers +* [Integers](src/com/jwetherell/algorithms/numbers/Integers.java) + + to binary String + - using divide and modulus + - using right shift and modulus + - using BigDecimal + - using divide and double + + is a power of 2 + - using a loop + - using recursion + - using logarithm + - using bits + + to English (e.g. 1 would return "one") +* [Longs](src/com/jwetherell/algorithms/numbers/Longs.java) + + to binary String + - using divide and modulus + - using right shift and modulus + - using BigDecimal +* [Complex](src/com/jwetherell/algorithms/numbers/Complex.java) + + addition + + subtraction + + multiplication + + absolute value + + polar value + +## Graphs +* Find shortest path(s) in a Graph from a starting Vertex + - [Dijkstra's algorithm (non-negative weight graphs)](src/com/jwetherell/algorithms/graph/Dijkstra.java) + - [Bellman-Ford algorithm (negative and positive weight graphs)](src/com/jwetherell/algorithms/graph/BellmanFord.java) +* Find minimum spanning tree + - [Prim's (undirected graphs)](src/com/jwetherell/algorithms/graph/Prim.java) + - [Kruskal's (undirected graphs)](src/com/jwetherell/algorithms/graph/Kruskal.java) +* Find all pairs shortest path + - [Johnsons's algorithm (negative and positive weight graphs)](src/com/jwetherell/algorithms/graph/Johnsons.java) + - [Floyd-Warshall (negative and positive weight graphs)](src/com/jwetherell/algorithms/graph/FloydWarshall.java) +* [Cycle detection](src/com/jwetherell/algorithms/graph/CycleDetection.java) + - Depth first search while keeping track of visited Verticies + - [Connected Components](src/com/jwetherell/algorithms/graph/ConnectedComponents.java) +* [Topological sort](src/com/jwetherell/algorithms/graph/TopologicalSort.java) +* [A* path finding algorithm](src/com/jwetherell/algorithms/graph/AStar.java) +* Maximum flow + - [Push-Relabel](src/com/jwetherell/algorithms/graph/PushRelabel.java) +* Graph Traversal + - [Depth First Traversal](src/com/jwetherell/algorithms/graph/DepthFirstTraversal.java) + - [Breadth First Traversal](src/com/jwetherell/algorithms/graph/BreadthFirstTraversal.java) +* [Edmonds Karp](src/com/jwetherell/algorithms/graph/EdmondsKarp.java) +* Matching + - [Turbo Matching](src/com/jwetherell/algorithms/graph/TurboMatching.java) +* [Lowest common ancestor in tree](src/com/jwetherell/algorithms/data_structures/Tree.java) + + +## Search +* Get index of value in array + + [Linear](src/com/jwetherell/algorithms/search/LinearSearch.java) + + [Quickselect](src/com/jwetherell/algorithms/search/QuickSelect.java) + + [Binary [sorted array input only]](src/com/jwetherell/algorithms/search/BinarySearch.java) + + [Lower bound [sorted array input only]](src/com/jwetherell/algorithms/search/LowerBound.java) + + [Upper bound [sorted array input only]](src/com/jwetherell/algorithms/search/UpperBound.java) + + Optimized binary (binary until a threashold then linear) [sorted array input only] + + [Interpolation [sorted array input only]](src/com/jwetherell/algorithms/search/InterpolationSearch.java) + +## Sequences +* [Find longest common subsequence (dynamic programming)](src/com/jwetherell/algorithms/sequence/LongestCommonSubsequence.java) +* [Find longest increasing subsequence (dynamic programming)](src/com/jwetherell/algorithms/sequence/LongestIncreasingSubsequence.java) +* [Find number of times a subsequence occurs in a sequence (dynamic programming)](src/com/jwetherell/algorithms/sequence/SubsequenceCounter.java) +* [Find i-th element in a Fibonacci sequence](src/com/jwetherell/algorithms/sequence/FibonacciSequence.java) + + using a loop + + using recursion + + using matrix multiplication + + using Binet's formula +* [Find total of all elements in a sequence(Arithmetic Progression)](src/com/jwetherell/algorithms/sequence/ArithmeticProgression.java) + + using a loop + + using Triangular numbers +* [Largest sum of contiguous subarray (Kadane's algorithm)](src/com/jwetherell/algorithms/sequence/LargestSumContiguousSubarray.java) +* [Longest palin­dromic sub­se­quence (dynamic programming)](src/com/jwetherell/algorithms/sequence/LongestPalindromicSubsequence.java) + +## Sorts +* [American Flag Sort](src/com/jwetherell/algorithms/sorts/AmericanFlagSort.java) +* [Bubble Sort](src/com/jwetherell/algorithms/sorts/BubbleSort.java) +* [Counting Sort (Integers only)](src/com/jwetherell/algorithms/sorts/CountingSort.java) +* [Heap Sort](src/com/jwetherell/algorithms/sorts/HeapSort.java) +* [Insertion Sort](src/com/jwetherell/algorithms/sorts/InsertionSort.java) +* [Merge Sort](src/com/jwetherell/algorithms/sorts/MergeSort.java) +* [Quick Sort](src/com/jwetherell/algorithms/sorts/QuickSort.java) +* [Radix Sort (Integers only)](src/com/jwetherell/algorithms/sorts/RadixSort.java) +* [Shell's Sort](src/com/jwetherell/algorithms/sorts/ShellSort.java) + +## String Functions +### [String Functions](src/com/jwetherell/algorithms/strings/StringFunctions.java) +* Reverse characters in a string + + using additional storage (a String or StringBuilder) + + using in-place swaps + + using in-place XOR +* Reverse words in a string + + using char swaps and additional storage (a StringBuilder) + + using StringTokenizer and additional (a String) + + using split() method and additional storage (a StringBuilder and String[]) + + using in-place swaps +* Is Palindrome + + using additional storage (a StringBuilder) + + using in-place symetric element compares +* Subsets of characters in a String +* Edit (Levenshtein) Distance of two Strings (Recursive, Iterative) +### [Manacher's algorithm (Find the longest Palindrome)](src/com/jwetherell/algorithms/strings/Manacher.java) +### [KMP (Knuth–Morris–Pratt) Algorithm - Length of maximal prefix-suffix for each prefix](src/com/jwetherell/algorithms/strings/KnuthMorrisPratt.java) +### [String rotations](src/com/jwetherell/algorithms/strings/Rotation.java) + + Find in lexicographically minimal string rotation + + Find in lexicographically maximal string rotation + diff --git a/SkipListMapTests.java b/SkipListMapTests.java new file mode 100644 index 00000000..1ff22038 --- /dev/null +++ b/SkipListMapTests.java @@ -0,0 +1,70 @@ +package com.jwetherell.algorithms.data_structures.test; + +import static org.junit.Assert.assertTrue; + +import static org.junit.Assert.*; +import org.junit.Test; + +import com.jwetherell.algorithms.data_structures.List; +import com.jwetherell.algorithms.data_structures.SkipListMap; +import com.jwetherell.algorithms.data_structures.test.common.JavaMapTest; +import com.jwetherell.algorithms.data_structures.test.common.MapTest; +import com.jwetherell.algorithms.data_structures.test.common.Utils; +import com.jwetherell.algorithms.data_structures.test.common.Utils.TestData; + +public class SkipListMapTests { + + @Test + public void testSkipListMap() { + TestData data = Utils.generateTestData(1000); + + String mname = "SkipListMap"; + SkipListMap map = new SkipListMap(); + java.util.Map jMap = map.toMap(); + + assertTrue(MapTest.testMap(map, String.class, mname, + data.unsorted, data.invalid)); + assertTrue(JavaMapTest.testJavaMap(jMap, Integer.class, mname, + data.unsorted, data.sorted, data.invalid)); + } + + @Test + public void testPutAndGet() { + SkipListMap map1 = new SkipListMap(); + SkipListMap map2 = new SkipListMap(); + map1.put("Green", 3); + map2.put("Green", 3); + assertTrue(map1.contains("Green")); + assertNotNull(map1.get("Green")); + assertNull(map1.get("Blue")); + assertEquals("Green=3", map1.toString()); + } + + @Test + public void testListFunctions() { + List.ArrayList list = new List.ArrayList(); + SkipListMap skipListTest = new SkipListMap(); + java.util.Map jMap = skipListTest.toMap(); + list.add(1); + list.clear(); + skipListTest.clear(); + jMap.clear(); + assertNotNull(skipListTest.toString()); + assertNotNull(jMap.toString()); + } + + @Test + public void testToString() { + StringBuilder sb = new StringBuilder(); + sb.append("sb"); + } + + @Test + public void testValidate() { + SkipListMap map3 = new SkipListMap(); + map3.put("Yellow", null); + map3.validate(); + assertTrue(!map3.validate()); + } + +} diff --git a/SuffixTrieTests.java b/SuffixTrieTests.java new file mode 100644 index 00000000..177756a5 --- /dev/null +++ b/SuffixTrieTests.java @@ -0,0 +1,36 @@ +package com.jwetherell.algorithms.data_structures.test; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.util.Set; +import java.util.TreeSet; + +import com.jwetherell.algorithms.data_structures.SuffixTrie; +import com.jwetherell.algorithms.data_structures.test.common.SuffixTreeTest; + +public class SuffixTrieTests { + + @Test + public void testSuffixTrie() { + String bookkeeper = "bookkeeper"; + SuffixTrie trie = new SuffixTrie(bookkeeper); + assertTrue(SuffixTreeTest.suffixTreeTest(trie, bookkeeper)); + } + + @Test + public void testAdd() { + SuffixTrie suffixTrieTest = new SuffixTrie("book"); + String part = "pen"; + assertTrue(suffixTrieTest.add(part)); + assertNotNull(suffixTrieTest.getSuffixes()); + } + + @Test + public void testString() { + SuffixTrie suffixTrieTest2 = new SuffixTrie("paper"); + assertNotNull(suffixTrieTest2.toString()); + } +} diff --git a/TrieMapTests.java b/TrieMapTests.java new file mode 100644 index 00000000..c64ab26d --- /dev/null +++ b/TrieMapTests.java @@ -0,0 +1,75 @@ +package com.jwetherell.algorithms.data_structures.test; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.jwetherell.algorithms.data_structures.List; +import com.jwetherell.algorithms.data_structures.TrieMap; +import com.jwetherell.algorithms.data_structures.test.common.JavaMapTest; +import com.jwetherell.algorithms.data_structures.test.common.MapTest; +import com.jwetherell.algorithms.data_structures.test.common.Utils; +import com.jwetherell.algorithms.data_structures.test.common.Utils.TestData; + +public class TrieMapTests { + + @Test + public void testTrieMap() { + TestData data = Utils.generateTestData(1000); + + String mapName = "TrieMap"; + TrieMap map = new TrieMap(); + java.util.Map jMap = map.toMap(); + + assertTrue(MapTest.testMap(map, String.class, mapName, + data.unsorted, data.invalid)); + assertTrue(JavaMapTest.testJavaMap(jMap, String.class, mapName, + data.unsorted, data.sorted, data.invalid)); + } + + @Test + public void testPutAndGet() { + TrieMap testTrieMap1 = new TrieMap(); + TrieMap testTrieMap2 = new TrieMap(); + String key = "Blue"; + Integer value = 2; + testTrieMap1.put(key,value); + testTrieMap2.put(key,value); + assertTrue(testTrieMap1.contains(key)); + assertNotNull(testTrieMap2.get(key)); + assertNull(testTrieMap1.get("Red")); + assertEquals(testTrieMap1.toString(),testTrieMap2.toString()); + + } + + @Test + public void testClear() { + + List.ArrayList list = new List.ArrayList(); + TrieMap testTrieMap3 = new TrieMap(); + java.util.Map map = testTrieMap3.toMap(); + list.add(1); + list.clear(); + testTrieMap3.clear(); + map.clear(); + assertNotNull(map.toString()); + + } + + @Test + public void testToString() { + StringBuilder sb = new StringBuilder(); + sb.append("sb"); + } + + @Test + public void testValidate() { + TrieMap testTrieMap4 = new TrieMap(); + String key = "a"; + String val = null; + testTrieMap4.put(key, val); + assertTrue(!testTrieMap4.validate()); + } + +} diff --git a/build.xml b/build.xml index b926ead8..683b2d2d 100644 --- a/build.xml +++ b/build.xml @@ -1,148 +1,148 @@ - - - java-algorithms-implementation build file - - - - - - - - - - - - - - - - - - - - - - - - - - CLASSPATH='${env_vars.CLASSPATH}' - JAVA_HOME='${env_vars.JAVA_HOME}' - JAVA_OPTS='${env_vars.JAVA_OPTS}' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + java-algorithms-implementation build file + + + + + + + + + + + + + + + + + + + + + + + + + + CLASSPATH='${env_vars.CLASSPATH}' + JAVA_HOME='${env_vars.JAVA_HOME}' + JAVA_OPTS='${env_vars.JAVA_OPTS}' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +