├── .classpath ├── .project ├── .settings └── org.eclipse.jdt.core.prefs ├── LICENSE ├── README.md ├── bin ├── Section_1 │ ├── ArraySorter.class │ ├── LinkedList$EmptyList.class │ ├── LinkedList.class │ ├── NoValueException.class │ ├── OneArgumentExpression.class │ ├── OneArgumentStatement.class │ └── TwoArgumentExpression.class ├── Section_2 │ ├── BinaryTree$1StackFrame.class │ ├── BinaryTree$2StackFrame.class │ ├── BinaryTree$3StackFrame.class │ ├── BinaryTree$DepthFirstTraversalType.class │ ├── BinaryTree$Node.class │ ├── BinaryTree.class │ ├── FunctionalTree.class │ ├── LinkedList$ListIterator.class │ ├── LinkedList$Node.class │ ├── LinkedList.class │ ├── OrderedStore.class │ ├── Queue.class │ ├── QueueImplLinkedList.class │ ├── Stack.class │ ├── StackImplLinkedList.class │ ├── Tree$Node.class │ └── Tree.class ├── Section_3 │ ├── AVLTree$Node.class │ ├── AVLTree.class │ ├── BinarySearchTree.class │ ├── HashTable.class │ ├── RedBlackTree$Node.class │ └── RedBlackTree.class ├── Section_4 │ ├── ArrayHeap.class │ ├── BinomialForest$BinomialTree.class │ ├── BinomialForest.class │ ├── DoublyLinkedList$DoublyLinkedNode.class │ ├── DoublyLinkedList$ReverseListIterator.class │ ├── DoublyLinkedList.class │ ├── LinkedHeap$Node.class │ ├── LinkedHeap.class │ ├── LinkedList$ListIterator.class │ ├── LinkedList$Node.class │ ├── LinkedList.class │ ├── NoSpaceException.class │ ├── OrderedPair.class │ ├── PriorityQueue.class │ └── SortableLinkedList.class ├── Section_5 │ ├── AdjacencyListGraphWithDenseVertex$Edge.class │ ├── AdjacencyListGraphWithDenseVertex$Vertex.class │ ├── AdjacencyListGraphWithDenseVertex.class │ ├── AdjacencyListGraphWithSparseVertex$Edge.class │ ├── AdjacencyListGraphWithSparseVertex$Vertex.class │ ├── AdjacencyListGraphWithSparseVertex.class │ ├── AdjacencyMatrixGraphWithDenseVertex$NullValue.class │ ├── AdjacencyMatrixGraphWithDenseVertex$Vertex.class │ ├── AdjacencyMatrixGraphWithDenseVertex.class │ ├── AdjacencyMatrixGraphWithSparseVertex$NullEdgeValue.class │ ├── AdjacencyMatrixGraphWithSparseVertex.class │ ├── Graph.class │ └── GraphVertex.class └── Section_6 │ ├── ArraySearcher.class │ ├── Consumer.class │ ├── EventConsumer$1.class │ ├── EventConsumer$ConsumerCodeContainer.class │ ├── EventConsumer$StreamEvent.class │ ├── EventConsumer.class │ ├── EventStream$1.class │ ├── EventStream$2.class │ ├── EventStream$3.class │ ├── EventStream.class │ ├── FileReader.class │ ├── FilterTask.class │ ├── FriendCountProblem.class │ ├── MapperTask.class │ ├── OneArgumentExpressionWithException.class │ ├── OneArgumentStatementWithException.class │ ├── PerfectNumberTest$1.class │ ├── PerfectNumberTest.class │ ├── ProcessorTask.class │ ├── ProducerConsumerQueue$Event.class │ ├── ProducerConsumerQueue$EventType.class │ ├── ProducerConsumerQueue.class │ ├── SemaphoreExample.class │ ├── Task.class │ ├── ThreadSafeCounter.class │ ├── ThreadSafeFixedLengthBlockingQueue.class │ ├── ThreadSafeFixedLengthSpinlockQueue.class │ ├── output.txt │ ├── output1.txt │ └── ulist.txt ├── code_files.txt └── src ├── Section_1 ├── ArraySorter.java ├── LinkedList.java ├── NoValueException.java ├── OneArgumentExpression.java ├── OneArgumentStatement.java └── TwoArgumentExpression.java ├── Section_2 ├── BinaryTree.java ├── FunctionalTree.java ├── LinkedList.java ├── OrderedStore.java ├── Queue.java ├── QueueImplLinkedList.java ├── Stack.java ├── StackImplLinkedList.java └── Tree.java ├── Section_3 ├── AVLTree.java ├── BinarySearchTree.java ├── HashTable.java └── RedBlackTree.java ├── Section_4 ├── ArrayHeap.java ├── BinomialForest.java ├── DoublyLinkedList.java ├── LinkedHeap.java ├── LinkedList.java ├── NoSpaceException.java ├── OrderedPair.java ├── PriorityQueue.java └── SortableLinkedList.java ├── Section_5 ├── AdjacencyListGraphWithDenseVertex.java ├── AdjacencyListGraphWithSparseVertex.java ├── AdjacencyMatrixGraphWithDenseVertex.java ├── AdjacencyMatrixGraphWithSparseVertex.java ├── Graph.java └── GraphVertex.java └── Section_6 ├── ArraySearcher.java ├── Consumer.java ├── EventConsumer.java ├── EventStream.java ├── FileReader.java ├── FilterTask.java ├── FriendCountProblem.java ├── MapperTask.java ├── OneArgumentExpressionWithException.java ├── OneArgumentStatementWithException.java ├── PerfectNumberTest.java ├── ProcessorTask.java ├── ProducerConsumerQueue.java ├── SemaphoreExample.java ├── Task.java ├── ThreadSafeCounter.java ├── ThreadSafeFixedLengthBlockingQueue.java ├── ThreadSafeFixedLengthSpinlockQueue.java ├── output.txt ├── output1.txt └── ulist.txt /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Advanced Data Structures And Algorithms In Java 9 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=9 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=9 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=9 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Advanced Data Structures and Algorithms in Java 9 [Video] 2 | This is the code repository for [Advanced Data Structures and Algorithms in Java 9 [Video]](https://www.packtpub.com/application-development/advanced-data-structures-and-algorithms-java-9-video?utm_source=github&utm_medium=repository&utm_campaign=9781788624213), published by [Packt](https://www.packtpub.com/?utm_source=github). It contains all the supporting project files necessary to work through the video course from start to finish. 3 | ## About the Video Course 4 | Advanced Data Structures and Algorithms in Java 9 covers classical, functional, and reactive data structures, giving you the ability to understand computational complexity, solve problems, and write efficient code. This video is based on the Zero Bug Bounce milestone of Java 9.We start off with the basics of algorithms and data structures, helping you understand the fundamentals and measure complexity. You will also get a clear picture of reactive programming, binary searches, sorting, search trees, undirected graphs, and a whole lot more! 5 | 6 |

What You Will Learn

7 |
8 |
14 | 15 | ## Instructions and Navigation 16 | ### Assumed Knowledge 17 | To fully benefit from the coverage included in this course, you will need:
18 | This video is for Java developers who want to learn about data structures and algorithms. A basic knowledge of Java is assumed. 19 | ### Technical Requirements 20 | This course has the following software requirements:
21 | Java 9 22 | 23 | ## Related Products 24 | * [Troubleshooting Vue.js [Video]](https://www.packtpub.com/application-development/troubleshooting-vuejs-video?utm_source=github&utm_medium=repository&utm_campaign=9781788993531) 25 | 26 | * [Angular 7 New Features [Video]](https://www.packtpub.com/web-development/angular-7-new-features-video?utm_source=github&utm_medium=repository&utm_campaign=9781789619683) 27 | 28 | * [Microservices Development on Azure with Java [Video]](https://www.packtpub.com/virtualization-and-cloud/microservices-development-azure-java-video?utm_source=github&utm_medium=repository&utm_campaign=9781789808858) 29 | 30 | -------------------------------------------------------------------------------- /bin/Section_1/ArraySorter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/ArraySorter.class -------------------------------------------------------------------------------- /bin/Section_1/LinkedList$EmptyList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/LinkedList$EmptyList.class -------------------------------------------------------------------------------- /bin/Section_1/LinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/LinkedList.class -------------------------------------------------------------------------------- /bin/Section_1/NoValueException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/NoValueException.class -------------------------------------------------------------------------------- /bin/Section_1/OneArgumentExpression.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/OneArgumentExpression.class -------------------------------------------------------------------------------- /bin/Section_1/OneArgumentStatement.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/OneArgumentStatement.class -------------------------------------------------------------------------------- /bin/Section_1/TwoArgumentExpression.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_1/TwoArgumentExpression.class -------------------------------------------------------------------------------- /bin/Section_2/BinaryTree$1StackFrame.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/BinaryTree$1StackFrame.class -------------------------------------------------------------------------------- /bin/Section_2/BinaryTree$2StackFrame.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/BinaryTree$2StackFrame.class -------------------------------------------------------------------------------- /bin/Section_2/BinaryTree$3StackFrame.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/BinaryTree$3StackFrame.class -------------------------------------------------------------------------------- /bin/Section_2/BinaryTree$DepthFirstTraversalType.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/BinaryTree$DepthFirstTraversalType.class -------------------------------------------------------------------------------- /bin/Section_2/BinaryTree$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/BinaryTree$Node.class -------------------------------------------------------------------------------- /bin/Section_2/BinaryTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/BinaryTree.class -------------------------------------------------------------------------------- /bin/Section_2/FunctionalTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/FunctionalTree.class -------------------------------------------------------------------------------- /bin/Section_2/LinkedList$ListIterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/LinkedList$ListIterator.class -------------------------------------------------------------------------------- /bin/Section_2/LinkedList$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/LinkedList$Node.class -------------------------------------------------------------------------------- /bin/Section_2/LinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/LinkedList.class -------------------------------------------------------------------------------- /bin/Section_2/OrderedStore.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/OrderedStore.class -------------------------------------------------------------------------------- /bin/Section_2/Queue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/Queue.class -------------------------------------------------------------------------------- /bin/Section_2/QueueImplLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/QueueImplLinkedList.class -------------------------------------------------------------------------------- /bin/Section_2/Stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/Stack.class -------------------------------------------------------------------------------- /bin/Section_2/StackImplLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/StackImplLinkedList.class -------------------------------------------------------------------------------- /bin/Section_2/Tree$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/Tree$Node.class -------------------------------------------------------------------------------- /bin/Section_2/Tree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_2/Tree.class -------------------------------------------------------------------------------- /bin/Section_3/AVLTree$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_3/AVLTree$Node.class -------------------------------------------------------------------------------- /bin/Section_3/AVLTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_3/AVLTree.class -------------------------------------------------------------------------------- /bin/Section_3/BinarySearchTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_3/BinarySearchTree.class -------------------------------------------------------------------------------- /bin/Section_3/HashTable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_3/HashTable.class -------------------------------------------------------------------------------- /bin/Section_3/RedBlackTree$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_3/RedBlackTree$Node.class -------------------------------------------------------------------------------- /bin/Section_3/RedBlackTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_3/RedBlackTree.class -------------------------------------------------------------------------------- /bin/Section_4/ArrayHeap.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/ArrayHeap.class -------------------------------------------------------------------------------- /bin/Section_4/BinomialForest$BinomialTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/BinomialForest$BinomialTree.class -------------------------------------------------------------------------------- /bin/Section_4/BinomialForest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/BinomialForest.class -------------------------------------------------------------------------------- /bin/Section_4/DoublyLinkedList$DoublyLinkedNode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/DoublyLinkedList$DoublyLinkedNode.class -------------------------------------------------------------------------------- /bin/Section_4/DoublyLinkedList$ReverseListIterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/DoublyLinkedList$ReverseListIterator.class -------------------------------------------------------------------------------- /bin/Section_4/DoublyLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/DoublyLinkedList.class -------------------------------------------------------------------------------- /bin/Section_4/LinkedHeap$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/LinkedHeap$Node.class -------------------------------------------------------------------------------- /bin/Section_4/LinkedHeap.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/LinkedHeap.class -------------------------------------------------------------------------------- /bin/Section_4/LinkedList$ListIterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/LinkedList$ListIterator.class -------------------------------------------------------------------------------- /bin/Section_4/LinkedList$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/LinkedList$Node.class -------------------------------------------------------------------------------- /bin/Section_4/LinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/LinkedList.class -------------------------------------------------------------------------------- /bin/Section_4/NoSpaceException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/NoSpaceException.class -------------------------------------------------------------------------------- /bin/Section_4/OrderedPair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/OrderedPair.class -------------------------------------------------------------------------------- /bin/Section_4/PriorityQueue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/PriorityQueue.class -------------------------------------------------------------------------------- /bin/Section_4/SortableLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_4/SortableLinkedList.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyListGraphWithDenseVertex$Edge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyListGraphWithDenseVertex$Edge.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyListGraphWithDenseVertex$Vertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyListGraphWithDenseVertex$Vertex.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyListGraphWithDenseVertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyListGraphWithDenseVertex.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyListGraphWithSparseVertex$Edge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyListGraphWithSparseVertex$Edge.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyListGraphWithSparseVertex$Vertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyListGraphWithSparseVertex$Vertex.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyListGraphWithSparseVertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyListGraphWithSparseVertex.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyMatrixGraphWithDenseVertex$NullValue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyMatrixGraphWithDenseVertex$NullValue.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyMatrixGraphWithDenseVertex$Vertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyMatrixGraphWithDenseVertex$Vertex.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyMatrixGraphWithDenseVertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyMatrixGraphWithDenseVertex.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyMatrixGraphWithSparseVertex$NullEdgeValue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyMatrixGraphWithSparseVertex$NullEdgeValue.class -------------------------------------------------------------------------------- /bin/Section_5/AdjacencyMatrixGraphWithSparseVertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/AdjacencyMatrixGraphWithSparseVertex.class -------------------------------------------------------------------------------- /bin/Section_5/Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/Graph.class -------------------------------------------------------------------------------- /bin/Section_5/GraphVertex.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_5/GraphVertex.class -------------------------------------------------------------------------------- /bin/Section_6/ArraySearcher.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ArraySearcher.class -------------------------------------------------------------------------------- /bin/Section_6/Consumer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/Consumer.class -------------------------------------------------------------------------------- /bin/Section_6/EventConsumer$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventConsumer$1.class -------------------------------------------------------------------------------- /bin/Section_6/EventConsumer$ConsumerCodeContainer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventConsumer$ConsumerCodeContainer.class -------------------------------------------------------------------------------- /bin/Section_6/EventConsumer$StreamEvent.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventConsumer$StreamEvent.class -------------------------------------------------------------------------------- /bin/Section_6/EventConsumer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventConsumer.class -------------------------------------------------------------------------------- /bin/Section_6/EventStream$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventStream$1.class -------------------------------------------------------------------------------- /bin/Section_6/EventStream$2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventStream$2.class -------------------------------------------------------------------------------- /bin/Section_6/EventStream$3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventStream$3.class -------------------------------------------------------------------------------- /bin/Section_6/EventStream.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/EventStream.class -------------------------------------------------------------------------------- /bin/Section_6/FileReader.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/FileReader.class -------------------------------------------------------------------------------- /bin/Section_6/FilterTask.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/FilterTask.class -------------------------------------------------------------------------------- /bin/Section_6/FriendCountProblem.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/FriendCountProblem.class -------------------------------------------------------------------------------- /bin/Section_6/MapperTask.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/MapperTask.class -------------------------------------------------------------------------------- /bin/Section_6/OneArgumentExpressionWithException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/OneArgumentExpressionWithException.class -------------------------------------------------------------------------------- /bin/Section_6/OneArgumentStatementWithException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/OneArgumentStatementWithException.class -------------------------------------------------------------------------------- /bin/Section_6/PerfectNumberTest$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/PerfectNumberTest$1.class -------------------------------------------------------------------------------- /bin/Section_6/PerfectNumberTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/PerfectNumberTest.class -------------------------------------------------------------------------------- /bin/Section_6/ProcessorTask.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ProcessorTask.class -------------------------------------------------------------------------------- /bin/Section_6/ProducerConsumerQueue$Event.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ProducerConsumerQueue$Event.class -------------------------------------------------------------------------------- /bin/Section_6/ProducerConsumerQueue$EventType.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ProducerConsumerQueue$EventType.class -------------------------------------------------------------------------------- /bin/Section_6/ProducerConsumerQueue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ProducerConsumerQueue.class -------------------------------------------------------------------------------- /bin/Section_6/SemaphoreExample.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/SemaphoreExample.class -------------------------------------------------------------------------------- /bin/Section_6/Task.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/Task.class -------------------------------------------------------------------------------- /bin/Section_6/ThreadSafeCounter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ThreadSafeCounter.class -------------------------------------------------------------------------------- /bin/Section_6/ThreadSafeFixedLengthBlockingQueue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ThreadSafeFixedLengthBlockingQueue.class -------------------------------------------------------------------------------- /bin/Section_6/ThreadSafeFixedLengthSpinlockQueue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Advanced-Data-Structures-and-Algorithms-in-Java-9/55ae8fe61cd2370f7ea03a980e4e4f2cc86947e1/bin/Section_6/ThreadSafeFixedLengthSpinlockQueue.class -------------------------------------------------------------------------------- /bin/Section_6/output.txt: -------------------------------------------------------------------------------- 1 | 2508972 : 0 2 | -------------------------------------------------------------------------------- /bin/Section_6/ulist.txt: -------------------------------------------------------------------------------- 1 | 2508972 2 | 1081826 3 | 2022585 4 | 141678 5 | 709419 6 | 877187 7 | 1592426 8 | 1013109 9 | 1490560 10 | 623595 -------------------------------------------------------------------------------- /code_files.txt: -------------------------------------------------------------------------------- 1 | https://drive.google.com/drive/folders/1RmTsmcXLu2Bta-ge8VtoCsJK9_SlD4K9?usp=sharing 2 | -------------------------------------------------------------------------------- /src/Section_1/ArraySorter.java: -------------------------------------------------------------------------------- 1 | package Section_1; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | public class ArraySorter { 7 | 8 | private static void merge(E[] arrayL, E[] arrayR,int start, int mid, int end,E[] targetArray,Comparator comparator) { 9 | int i = start; 10 | int j = mid; 11 | int k = start; 12 | while (k < end) { 13 | if (i == mid) { 14 | targetArray[k] = arrayR[j]; 15 | j++; 16 | } else if (j == end) { 17 | targetArray[k] = arrayL[i]; 18 | i++; 19 | } else if (comparator.compare(arrayL[i], arrayR[j]) > 0) { 20 | targetArray[k] = arrayR[j]; 21 | j++; 22 | } else { 23 | targetArray[k] = arrayL[i]; 24 | i++; 25 | } 26 | k++; 27 | } 28 | } 29 | 30 | private static void merge(E[] array,int start, int mid, int end,E[] targetArray,Comparator comparator) { 31 | merge(array, array, start, mid, end,targetArray, comparator); 32 | } 33 | 34 | public static E[] mergeSortNoCopy(E[] sourceArray, int start,int end,E[] tempArray,Comparator comparator) { 35 | if (start >= end - 1) { 36 | return sourceArray; 37 | } 38 | int mid = (start + end) / 2; 39 | E[] sortedPart1 =mergeSortNoCopy(sourceArray, start, mid, tempArray,comparator); 40 | E[] sortedPart2 =mergeSortNoCopy(sourceArray, mid, end, tempArray,comparator); 41 | 42 | if (sortedPart2 == sortedPart1) { 43 | if (sortedPart1 == sourceArray) { 44 | merge(sortedPart1, sortedPart2, start, mid, end,tempArray, comparator); 45 | return tempArray; 46 | } else { 47 | merge(sortedPart1, sortedPart2, start, mid, end,sourceArray, comparator); 48 | return sourceArray; 49 | } 50 | } else { 51 | merge(sortedPart1, sortedPart2, start, mid, end,sortedPart2, comparator); 52 | return sortedPart2; 53 | } 54 | } 55 | 56 | public static void mergeSort(E[] sourceArray, int start,int end,E[] tempArray,Comparator comparator) { 57 | if (start >= end - 1) { 58 | return; 59 | } 60 | int mid = (start + end) / 2; 61 | mergeSort(sourceArray, start, mid, tempArray, comparator); 62 | mergeSort(sourceArray, mid, end, tempArray, comparator); 63 | 64 | merge(sourceArray, start, mid, end, tempArray, comparator); 65 | System.arraycopy(tempArray, start, sourceArray, start,end - start); 66 | } 67 | 68 | public static void quicksort(E[] array,int start,int end,Comparator comparator) { 69 | 70 | if (end - start <= 0) { 71 | return; 72 | } 73 | int pivotIndex=(int)((end-start)*Math.random())+start; 74 | swap(array,pivotIndex,end-1); 75 | int i = start; 76 | int j = end - 1; 77 | boolean movingI = true; 78 | 79 | while (i < j) { 80 | if (comparator.compare(array[i], array[j]) > 0) { 81 | swap(array, i, j); 82 | movingI = !movingI; 83 | } 84 | else { 85 | if (movingI) { 86 | i++; 87 | } 88 | else { 89 | j--; 90 | } 91 | } 92 | } 93 | quicksort(array, start, i, comparator); 94 | quicksort(array, i + 1, end, comparator); 95 | } 96 | 97 | public static void quicksort(E[] array,Comparator comparator) { 98 | quicksort(array, 0, array.length, comparator); 99 | } 100 | 101 | public static void swap(E[] array, int i, int j) { 102 | if (i == j) 103 | return; 104 | E temp = array[i]; 105 | array[i] = array[j]; 106 | array[j] = temp; 107 | } 108 | 109 | public static void main(String[] args) { 110 | Integer[] array =new Integer[]{10, 5, 2, 3, 78, 53, 3, 1, 1, 24, 1, 35,35, 2, 67, 4, 33, 30}; 111 | quicksort(array, (a, b) -> a - b); 112 | System.out.println(Arrays.toString(array)); 113 | 114 | Integer[] anotherArray=new Integer[array.length]; 115 | array = mergeSortNoCopy(array, 0, array.length, anotherArray,(a, b) -> a - b); 116 | System.out.println(Arrays.toString(array)); 117 | 118 | mergeSort(array, 0, array.length, anotherArray,(a, b) -> a - b); 119 | System.out.println(Arrays.toString(array)); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/Section_1/LinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_1; 2 | 3 | public class LinkedList { 4 | private E head; 5 | private LinkedList tail; 6 | private int length; 7 | 8 | protected LinkedList(){ 9 | 10 | } 11 | 12 | protected LinkedList(E head, LinkedList tail){ 13 | this.head = head; 14 | this.tail = tail; 15 | this.length = tail.getLength()+1; 16 | } 17 | 18 | public static class EmptyList extends LinkedList{ 19 | @Override 20 | public E head() { 21 | throw new NoValueException("head() invoked on empty list"); 22 | } 23 | 24 | @Override 25 | public LinkedList tail() { 26 | throw new NoValueException("tail() invoked on empty list"); 27 | } 28 | 29 | @Override 30 | public void forEach(OneArgumentStatement processor) {} 31 | 32 | @Override 33 | public LinkedList map(OneArgumentExpression transformer) { 34 | return LinkedList.emptyList(); 35 | } 36 | 37 | @Override 38 | public R foldLeft(R initialValue, TwoArgumentExpression computer) { 39 | return initialValue; 40 | } 41 | 42 | @Override 43 | public R foldRight(TwoArgumentExpression computer, R initialValue) { 44 | return initialValue; 45 | } 46 | 47 | @Override 48 | public LinkedList filter(OneArgumentExpression selector) { 49 | return this; 50 | } 51 | 52 | @Override 53 | public LinkedList flatMap(OneArgumentExpression> transformer) { 54 | return LinkedList.emptyList(); 55 | } 56 | 57 | @Override 58 | public boolean isEmpty() { 59 | return true; 60 | } 61 | 62 | @Override 63 | public int getLength() { 64 | return 0; 65 | } 66 | } 67 | 68 | public static LinkedList emptyList(){ 69 | return new EmptyList<>(); 70 | } 71 | public E head(){ 72 | return head; 73 | } 74 | public LinkedList tail(){ 75 | return tail; 76 | } 77 | public LinkedList add(E value){ 78 | return new LinkedList<>(value,this); 79 | } 80 | public void forEach(OneArgumentStatement processor){ 81 | processor.doSomething(head()); 82 | tail().forEach(processor); 83 | } 84 | 85 | public LinkedList map(OneArgumentExpression transformer){ 86 | return new LinkedList<>(transformer.compute(head()), tail.map(transformer)); 87 | } 88 | 89 | public LinkedList append(LinkedList rhs){ 90 | return this.foldRight((x,l)->l.add(x),rhs); 91 | } 92 | 93 | public LinkedList flatMap(OneArgumentExpression> transformer){ 94 | return transformer.compute(head()).append(tail().flatMap(transformer)); 95 | } 96 | 97 | public R foldLeft(R initialValue, TwoArgumentExpression computer){ 98 | R newInitialValue = computer.compute(initialValue, head()); 99 | return tail().foldLeft(newInitialValue, computer); 100 | } 101 | 102 | public R foldRight(TwoArgumentExpression computer, R initialValue){ 103 | R computedValue = tail().foldRight(computer, initialValue); 104 | return computer.compute(head(), computedValue); 105 | } 106 | 107 | public LinkedList filter(OneArgumentExpression selector){ 108 | if(selector.compute(head())){ 109 | return new LinkedList(head(), tail().filter(selector)); 110 | }else{ 111 | return tail().filter(selector); 112 | } 113 | } 114 | public boolean isEmpty(){ 115 | return false; 116 | } 117 | 118 | private static LinkedList ofRange(int start, int end, LinkedList tailList){ 119 | if(start>=end){ 120 | return tailList; 121 | }else{ 122 | return ofRange(start+1, end, tailList).add(start); 123 | } 124 | } 125 | 126 | public static LinkedList ofRange(int start, int end){ 127 | return ofRange(start,end, LinkedList.emptyList()); 128 | } 129 | 130 | public int getLength(){ 131 | return length; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/Section_1/NoValueException.java: -------------------------------------------------------------------------------- 1 | package Section_1; 2 | 3 | /** 4 | * Created by debasishc on 28/8/16. 5 | */ 6 | public class NoValueException extends RuntimeException { 7 | public NoValueException(String message){ 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Section_1/OneArgumentExpression.java: -------------------------------------------------------------------------------- 1 | package Section_1; 2 | 3 | @FunctionalInterface 4 | public interface OneArgumentExpression { 5 | R compute(A a); 6 | } 7 | -------------------------------------------------------------------------------- /src/Section_1/OneArgumentStatement.java: -------------------------------------------------------------------------------- 1 | package Section_1; 2 | 3 | 4 | @FunctionalInterface 5 | public interface OneArgumentStatement { 6 | void doSomething(E argument); 7 | } 8 | -------------------------------------------------------------------------------- /src/Section_1/TwoArgumentExpression.java: -------------------------------------------------------------------------------- 1 | package Section_1; 2 | 3 | @FunctionalInterface 4 | public interface TwoArgumentExpression { 5 | R compute(A lhs, B rhs); 6 | } 7 | -------------------------------------------------------------------------------- /src/Section_2/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | import Section_1.OneArgumentStatement; 4 | 5 | public class BinaryTree { 6 | 7 | public static class Node{ 8 | protected E value; 9 | protected Node left; 10 | protected Node right; 11 | protected Node parent; 12 | protected BinaryTree containerTree; 13 | 14 | protected Node(Node parent,BinaryTree containerTree, E value) { 15 | this.value = value; 16 | this.parent = parent; 17 | this.containerTree = containerTree; 18 | } 19 | 20 | public E getValue(){ 21 | return value; 22 | } 23 | 24 | public Node getRight() { 25 | return right; 26 | } 27 | 28 | public Node getParent() { 29 | return parent; 30 | } 31 | 32 | public Node getLeft() { 33 | return left; 34 | } 35 | 36 | public BinaryTree getContainerTree() { 37 | return containerTree; 38 | } 39 | } 40 | protected Node root; 41 | 42 | public void addRoot(E value){ 43 | if(root==null){ 44 | root = newNode(null, this, value); 45 | }else{ 46 | throw new IllegalStateException("Root already exists"); 47 | } 48 | } 49 | 50 | public Node getRoot(){ 51 | return root; 52 | } 53 | 54 | public Node addChild(Node parent, E value, boolean left){ 55 | if(parent == null){ 56 | throw new NullPointerException("Cannot add node to null parent"); 57 | }else if(parent.containerTree != this){ 58 | throw new IllegalArgumentException("Parent does not belong to this tree"); 59 | }else { 60 | Node child = newNode(parent, this, value); 61 | if(left){ 62 | parent.left = child; 63 | }else{ 64 | parent.right = child; 65 | } 66 | return child; 67 | } 68 | } 69 | 70 | public Node addChildLeft(Node parent, E value){ 71 | return addChild(parent, value, true); 72 | } 73 | 74 | public Node addChildRight(Node parent, E value){ 75 | return addChild(parent, value, false); 76 | } 77 | 78 | protected Node newNode(Node parent,BinaryTree containerTree, E value){ 79 | return new Node<>(parent, containerTree, value); 80 | } 81 | 82 | public static enum DepthFirstTraversalType{ 83 | PREORDER, INORDER, POSTORDER 84 | } 85 | 86 | public void traverseDepthFirst(OneArgumentStatement processor, Node current, DepthFirstTraversalType tOrder){ 87 | if(current==null){ 88 | return; 89 | } 90 | if(tOrder == DepthFirstTraversalType.PREORDER){ 91 | processor.doSomething(current.value); 92 | } 93 | traverseDepthFirst(processor, current.left, tOrder); 94 | if(tOrder == DepthFirstTraversalType.INORDER){ 95 | processor.doSomething(current.value); 96 | } 97 | traverseDepthFirst(processor, current.right, tOrder); 98 | if(tOrder == DepthFirstTraversalType.POSTORDER){ 99 | processor.doSomething(current.value); 100 | } 101 | } 102 | 103 | public void traversePreOrderNonRecursive(OneArgumentStatement processor) { 104 | Stack> stack = new StackImplLinkedList<>(); 105 | stack.push(getRoot()); 106 | while (stack.peek()!=null){ 107 | Node current = stack.pop(); 108 | processor.doSomething(current.value); 109 | if(current.right!=null) 110 | stack.push(current.right); 111 | if(current.left!=null) 112 | stack.push(current.left); 113 | } 114 | } 115 | 116 | public void traverseInOrderNonRecursive(OneArgumentStatement processor) { 117 | class StackFrame{ 118 | Node node; 119 | boolean childrenPushed = false; 120 | 121 | public StackFrame(Node node, boolean childrenPushed) { 122 | this.node = node; 123 | this.childrenPushed = childrenPushed; 124 | } 125 | } 126 | Stack stack = new StackImplLinkedList<>(); 127 | stack.push(new StackFrame(getRoot(), false)); 128 | while (stack.peek()!=null){ 129 | StackFrame current = stack.pop(); 130 | if(current.childrenPushed){ 131 | processor.doSomething(current.node.value); 132 | }else{ 133 | if(current.node.right!=null) 134 | stack.push(new StackFrame(current.node.right, false)); 135 | stack.push(new StackFrame(current.node, true)); 136 | if(current.node.left!=null) 137 | stack.push(new StackFrame(current.node.left, false)); 138 | } 139 | } 140 | } 141 | 142 | public void traverseDepthFirstNonRecursive(OneArgumentStatement processor, DepthFirstTraversalType tOrder) { 143 | class StackFrame { 144 | Node node; 145 | int state; 146 | 147 | public StackFrame(Node node, int state) { 148 | this.node = node; 149 | this.state = state; 150 | } 151 | } 152 | 153 | Stack stack = 154 | new StackImplLinkedList(); 155 | stack.push(new StackFrame(root, 0)); 156 | stackLoop:while (stack.peek() != null){ 157 | StackFrame frame = stack.pop(); 158 | int state = frame.state; 159 | Node currentNode = frame.node; 160 | start:while(true) { 161 | if(currentNode==null){ 162 | continue stackLoop; 163 | } 164 | switch (state) { 165 | case 0: 166 | if (tOrder == 167 | DepthFirstTraversalType.PREORDER) { 168 | processor.doSomething(currentNode.value); 169 | } 170 | stack.push(new StackFrame(currentNode, 1)); 171 | state = 0; 172 | currentNode = currentNode.left; 173 | continue start; 174 | case 1: 175 | if (tOrder == 176 | DepthFirstTraversalType.INORDER) { 177 | processor.doSomething(currentNode.value); 178 | } 179 | stack.push(new StackFrame(currentNode, 2)); 180 | state = 0; 181 | currentNode = currentNode.right; 182 | continue start; 183 | case 2: 184 | if (tOrder == 185 | DepthFirstTraversalType.POSTORDER) { 186 | processor.doSomething(currentNode.value); 187 | } 188 | break start; 189 | 190 | } 191 | 192 | } 193 | } 194 | } 195 | 196 | public void traversePostOrderNonRecursive(OneArgumentStatement processor) { 197 | class StackFrame{ 198 | Node node; 199 | boolean childrenPushed = false; 200 | 201 | public StackFrame(Node node, boolean childrenPushed) { 202 | this.node = node; 203 | this.childrenPushed = childrenPushed; 204 | } 205 | } 206 | Stack stack = new StackImplLinkedList<>(); 207 | stack.push(new StackFrame(getRoot(), false)); 208 | while (stack.peek()!=null){ 209 | StackFrame current = stack.pop(); 210 | if(current.childrenPushed){ 211 | processor.doSomething(current.node.value); 212 | }else{ 213 | stack.push(new StackFrame(current.node, true)); 214 | if(current.node.right!=null) 215 | stack.push(new StackFrame(current.node.right, false)); 216 | 217 | if(current.node.left!=null) 218 | stack.push(new StackFrame(current.node.left, false)); 219 | } 220 | } 221 | } 222 | 223 | protected void displayText(Node parent, int depth){ 224 | 225 | for(int i=0;i node){ 242 | if(node == null){ 243 | throw new NullPointerException("Cannot delete to null parent"); 244 | }else if(node.containerTree != this){ 245 | throw new IllegalArgumentException("Node does not belong to this tree"); 246 | }else { 247 | if(node==getRoot()){ 248 | root=null; 249 | return; 250 | }else{ 251 | Node parent = node.getParent(); 252 | if(parent.getLeft()==node){ 253 | parent.left = null; 254 | }else{ 255 | parent.right = null; 256 | } 257 | } 258 | } 259 | } 260 | 261 | public void setValue(Node node, E value){ 262 | if(node == null){ 263 | throw new NullPointerException("Cannot add node to null parent"); 264 | }else if(node.containerTree != this){ 265 | throw new IllegalArgumentException("Parent does not belong to this tree"); 266 | }else { 267 | node.value = value; 268 | } 269 | } 270 | 271 | public Node setChild(Node parent, Node child, boolean left){ 272 | if(parent == null){ 273 | throw new NullPointerException("Cannot set node to null parent"); 274 | }else if(parent.containerTree != this){ 275 | throw new IllegalArgumentException("Parent does not belong to this tree"); 276 | }else { 277 | if(left){ 278 | parent.left = child; 279 | }else{ 280 | parent.right = child; 281 | } 282 | if(child!=null) { 283 | child.parent = parent; 284 | } 285 | return child; 286 | } 287 | } 288 | 289 | protected void rotate(Node node, boolean left){ 290 | if(node == null){ 291 | throw new IllegalArgumentException("Cannot rotate null node"); 292 | }else if(node.containerTree != this){ 293 | throw new IllegalArgumentException("Node does not belong to the current tree"); 294 | } 295 | Node child = null; 296 | Node grandchild = null; 297 | Node parent = node.getParent(); 298 | boolean parentDirection; 299 | if(left){ 300 | child = node.getRight(); 301 | if(child!=null){ 302 | grandchild = child.getLeft(); 303 | } 304 | 305 | }else{ 306 | child = node.getLeft(); 307 | if(child!=null){ 308 | grandchild = child.getRight(); 309 | } 310 | } 311 | 312 | if(node != getRoot()){ 313 | if(parent.getLeft()==node){ 314 | parentDirection = true; 315 | }else{ 316 | parentDirection = false; 317 | } 318 | if(grandchild!=null) 319 | deleteNodeWithSubtree(grandchild); 320 | if(child!=null) 321 | deleteNodeWithSubtree(child); 322 | deleteNodeWithSubtree(node); 323 | if(child!=null) { 324 | setChild(parent, child, parentDirection); 325 | setChild(child, node, left); 326 | } 327 | if(grandchild!=null) 328 | setChild(node, grandchild, !left); 329 | }else{ 330 | if(grandchild!=null) 331 | deleteNodeWithSubtree(grandchild); 332 | if(child!=null) 333 | deleteNodeWithSubtree(child); 334 | deleteNodeWithSubtree(node); 335 | if(child!=null) { 336 | root = child; 337 | setChild(child, node, left); 338 | } 339 | if(grandchild!=null) 340 | setChild(node, grandchild, !left); 341 | root.parent = null; 342 | } 343 | } 344 | 345 | public static void main(String[] args) { 346 | BinaryTree tree = new BinaryTree<>(); 347 | tree.addRoot(1); 348 | Node n1 = tree.getRoot(); 349 | Node n2 = tree.addChild(n1, 2, true); 350 | Node n3 = tree.addChild(n1, 3, false); 351 | Node n4 = tree.addChild(n2, 4, true); 352 | Node n5 = tree.addChild(n2, 5, false); 353 | Node n6 = tree.addChild(n3, 6, true); 354 | Node n7 = tree.addChild(n3, 7, false); 355 | Node n8 = tree.addChild(n4, 8, true); 356 | Node n9 = tree.addChild(n4, 9, false); 357 | Node n10 = tree.addChild(n5, 10, true); 358 | 359 | tree.traverseDepthFirst((x)->System.out.print(" "+x), tree.getRoot(), DepthFirstTraversalType.PREORDER); 360 | System.out.println(); 361 | tree.traverseDepthFirst((x)->System.out.print(" "+x), tree.getRoot(), DepthFirstTraversalType.INORDER); 362 | System.out.println(); 363 | tree.traverseDepthFirst((x)->System.out.print(" "+x), tree.getRoot(), DepthFirstTraversalType.POSTORDER); 364 | System.out.println(); 365 | 366 | System.out.println(); 367 | tree.traversePreOrderNonRecursive((x)->System.out.print(" "+x)); 368 | System.out.println(); 369 | tree.traverseInOrderNonRecursive((x)->System.out.print(" "+x)); 370 | System.out.println(); 371 | tree.traversePostOrderNonRecursive((x)->System.out.print(" "+x)); 372 | System.out.println(); 373 | System.out.println(); 374 | System.out.println("=============================================="); 375 | tree.displayText(); 376 | } 377 | } -------------------------------------------------------------------------------- /src/Section_2/FunctionalTree.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | public class FunctionalTree { 4 | 5 | private E value; 6 | private Section_1.LinkedList> children; 7 | 8 | public FunctionalTree(E value, Section_1.LinkedList> children) { 9 | this.children = children; 10 | this.value = value; 11 | } 12 | 13 | public Section_1.LinkedList> getChildren() { 14 | return children; 15 | } 16 | 17 | public E getValue() { 18 | return value; 19 | } 20 | 21 | public void traverseDepthFirst(Section_1.OneArgumentStatement processor){ 22 | processor.doSomething(value); 23 | children.forEach((n)-> n.traverseDepthFirst(processor)); 24 | } 25 | 26 | public static void main(String[] args) { 27 | Section_1.LinkedList> emptyList = Section_1.LinkedList.emptyList(); 28 | 29 | FunctionalTree t1 = new FunctionalTree<>(5, emptyList); 30 | FunctionalTree t2 = new FunctionalTree<>(9, emptyList); 31 | FunctionalTree t3 = new FunctionalTree<>(6, emptyList); 32 | 33 | FunctionalTree t4 = new FunctionalTree<>(2, emptyList); 34 | FunctionalTree t5 = new FunctionalTree<>(5, emptyList.add(t1)); 35 | FunctionalTree t6 = new FunctionalTree<>(9, emptyList.add(t3).add(t2)); 36 | FunctionalTree t7 = new FunctionalTree<>(6, emptyList); 37 | FunctionalTree t8 = new FunctionalTree<>(2, emptyList); 38 | 39 | FunctionalTree t9 = new FunctionalTree<>(5, emptyList.add(t6).add(t5).add(t4)); 40 | FunctionalTree t10 = new FunctionalTree<>(1, emptyList.add(t8).add(t7)); 41 | 42 | FunctionalTree tree = new FunctionalTree<>(1, emptyList.add(t10).add(t9)); 43 | 44 | tree.traverseDepthFirst(System.out::print); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Section_2/LinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | import java.util.Comparator; 4 | import java.util.Iterator; 5 | import java.util.NoSuchElementException; 6 | 7 | /** 8 | * Created by debasishc on 21/7/16. 9 | */ 10 | public class LinkedList implements Iterable { 11 | protected int length = 0; 12 | protected Node[] lastModifiedNode; 13 | protected Node first; 14 | protected Node last; 15 | 16 | public int getLength(){ 17 | return length; 18 | } 19 | 20 | public void appendAllLast(LinkedList anotherList){ 21 | if(first == null){ 22 | first = anotherList.first; 23 | last = anotherList.last; 24 | }else{ 25 | last.next = anotherList.first; 26 | last = anotherList.last; 27 | } 28 | length += anotherList.length; 29 | 30 | } 31 | 32 | public static void main(String[] args) { 33 | // LinkedList linkedList = new LinkedList<>(); 34 | // linkedList.appendFirst(4); 35 | // linkedList.appendFirst(1); 36 | // linkedList.appendFirst(2); 37 | // linkedList.appendFirst(3); 38 | // linkedList.appendLast(8); 39 | // linkedList.appendLast(7); 40 | // linkedList.appendLast(18); 41 | // linkedList.appendFirst(50); 42 | // linkedList.insert(5, 500); 43 | // linkedList.insert(9, 501); 44 | // linkedList.removeAtIndex(8); 45 | // linkedList.insert(8, 502); 46 | // linkedList.removeAtIndex(1); 47 | 48 | LinkedList anotherList = new LinkedList<>(); 49 | anotherList.appendFirst(4); 50 | anotherList.appendFirst(1); 51 | anotherList.appendFirst(2); 52 | anotherList.appendFirst(3); 53 | anotherList.appendLast(8); 54 | anotherList.appendLast(7); 55 | anotherList.appendLast(1); 56 | anotherList.appendLast(2); 57 | anotherList.appendLast(3); 58 | anotherList.appendLast(18); 59 | // linkedList.appendAllLast(anotherList); 60 | // 61 | // // linkedList.visualize(visualizer); 62 | // 63 | // 64 | // while(anotherList.getLength()>0){ 65 | // anotherList.removeLast(); 66 | // } 67 | 68 | //linkedList.zip(anotherList).visualize(visualizer); 69 | // Iterator iter = anotherList.iterator(); 70 | // while (iter.hasNext()){ 71 | // int val = iter.next(); 72 | // System.out.println(); 73 | // if(val<=4) 74 | // iter.remove(); 75 | // anotherList.visualize(visualizer); 76 | // } 77 | } 78 | 79 | @Override 80 | public Iterator iterator() { 81 | return new ListIterator(); 82 | } 83 | 84 | protected Node getNewNode() { 85 | Node node = new Node<>(); 86 | lastModifiedNode = new Node[]{node}; 87 | return node; 88 | } 89 | 90 | public Node appendFirst(E value) { 91 | Node node = getNewNode(); 92 | node.value = value; 93 | node.next = first; 94 | first = node; 95 | if (length == 0) 96 | last = node; 97 | length++; 98 | return node; 99 | } 100 | 101 | public Node appendLast(E value) { 102 | Node node = getNewNode(); 103 | node.value = value; 104 | if (last != null) 105 | last.next = node; 106 | last = node; 107 | if (first == null) { 108 | first = node; 109 | } 110 | 111 | length++; 112 | return node; 113 | } 114 | 115 | public Node insert(int index, E value) { 116 | Node node = getNewNode(); 117 | if (index < 0 || index > length) { 118 | throw new IllegalArgumentException("Invalid index for insertion"); 119 | } else if (index == length) { 120 | return appendLast(value); 121 | } else if (index == 0) { 122 | return appendFirst(value); 123 | } else { 124 | Node prev = first; 125 | while (index > 1) { 126 | index--; 127 | prev = prev.next; 128 | } 129 | node.value = value; 130 | node.next = prev.next; 131 | prev.next = node; 132 | length++; 133 | return node; 134 | } 135 | } 136 | 137 | public E getFirst() { 138 | if (length == 0) { 139 | throw new NoSuchElementException(); 140 | } 141 | return first.value; 142 | } 143 | 144 | public E getLast() { 145 | if (length == 0) { 146 | throw new NoSuchElementException(); 147 | } 148 | return last.value; 149 | } 150 | 151 | public Node removeFirst() { 152 | if (length == 0) { 153 | throw new NoSuchElementException(); 154 | } 155 | Node origFirst = first; 156 | first = first.next; 157 | length--; 158 | if (length == 0) { 159 | last = null; 160 | } 161 | return origFirst; 162 | } 163 | 164 | 165 | public E findAtIndex(int index) { 166 | Node result = first; 167 | while (index >= 0) { 168 | if (result == null) { 169 | throw new NoSuchElementException(); 170 | } else if (index == 0) { 171 | return result.value; 172 | } else { 173 | index--; 174 | result = result.next; 175 | } 176 | } 177 | return null; 178 | } 179 | 180 | protected Node removeAtIndex(int index) { 181 | if (index >= length || index < 0) { 182 | throw new NoSuchElementException(); 183 | } 184 | 185 | if (index == 0) { 186 | Node nodeRemoved = first; 187 | removeFirst(); 188 | return nodeRemoved; 189 | } 190 | 191 | Node justBeforeIt = first; 192 | while (--index > 0) { 193 | justBeforeIt = justBeforeIt.next; 194 | } 195 | 196 | Node nodeRemoved = justBeforeIt.next; 197 | if (justBeforeIt.next == last) { 198 | last = justBeforeIt.next.next; 199 | } 200 | justBeforeIt.next = justBeforeIt.next.next; 201 | 202 | length--; 203 | 204 | return nodeRemoved; 205 | 206 | } 207 | 208 | public void setValueAtIndex(int index, E value){ 209 | Node result = first; 210 | while (index >= 0) { 211 | if (result == null) { 212 | throw new NoSuchElementException(); 213 | } else if (index == 0) { 214 | result.value = value; 215 | return; 216 | } else { 217 | index--; 218 | result = result.next; 219 | } 220 | } 221 | } 222 | 223 | 224 | public Node removeLast() { 225 | return removeAtIndex(length - 1); 226 | } 227 | 228 | public static class Node { 229 | protected E value; 230 | protected Node next; 231 | 232 | public String toString() { 233 | return value.toString(); 234 | } 235 | 236 | public Node getNext() { 237 | return next; 238 | } 239 | 240 | public E getValue() { 241 | return value; 242 | } 243 | } 244 | 245 | public class ListIterator implements Iterator { 246 | protected Node nextNode = first; 247 | protected Node currentNode = null; 248 | protected Node prevNode = null; 249 | 250 | @Override 251 | public boolean hasNext() { 252 | return nextNode != null; 253 | } 254 | 255 | @Override 256 | public E next() { 257 | if (!hasNext()) { 258 | throw new IllegalStateException(); 259 | } 260 | prevNode = currentNode; 261 | currentNode = nextNode; 262 | nextNode = nextNode.next; 263 | return currentNode.value; 264 | } 265 | 266 | @Override 267 | public void remove() { 268 | if(currentNode==null || currentNode == prevNode){ 269 | throw new IllegalStateException(); 270 | } 271 | if(currentNode==first){ 272 | first = nextNode; 273 | }else{ 274 | prevNode.next = nextNode; 275 | } 276 | currentNode=prevNode; 277 | 278 | } 279 | 280 | public void setValue(E value){ 281 | currentNode.value = value; 282 | } 283 | 284 | } 285 | 286 | public String toString(){ 287 | StringBuilder sb = new StringBuilder("["); 288 | Node node = first; 289 | while(node!=null){ 290 | if(node.value==null){ 291 | sb.append("null"); 292 | }else{ 293 | sb.append(node.value.toString()+", "); 294 | } 295 | node=node.next; 296 | } 297 | sb.append("]"); 298 | return sb.toString(); 299 | } 300 | } 301 | 302 | -------------------------------------------------------------------------------- /src/Section_2/OrderedStore.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | public interface OrderedStore extends Iterable { 4 | void insert(E value); 5 | E pickFirst(); 6 | E checkFirst(); 7 | } 8 | -------------------------------------------------------------------------------- /src/Section_2/Queue.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | public interface Queue extends OrderedStore 4 | { 5 | void enqueue(E value); 6 | E dequeue(); 7 | E peek(); 8 | 9 | @Override 10 | default E checkFirst(){ 11 | return peek(); 12 | } 13 | 14 | @Override 15 | default void insert(E value){ 16 | enqueue(value); 17 | } 18 | 19 | @Override 20 | default E pickFirst(){ 21 | return dequeue(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Section_2/QueueImplLinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | import java.util.Iterator; 4 | 5 | /** 6 | * Created by debasishc on 12/8/16. 7 | */ 8 | public class QueueImplLinkedList implements Queue{ 9 | protected LinkedList list = getNewLinkedList(); 10 | 11 | protected LinkedList getNewLinkedList(){ 12 | return new LinkedList<>(); 13 | } 14 | 15 | @Override 16 | public void enqueue(E value) { 17 | list.appendLast(value); 18 | } 19 | 20 | @Override 21 | public E dequeue() { 22 | if(list.getLength()==0){ 23 | return null; 24 | } 25 | E value = list.getFirst(); 26 | list.removeFirst(); 27 | return value; 28 | } 29 | 30 | @Override 31 | public E peek() { 32 | if(list.getLength()==0){ 33 | return null; 34 | } 35 | return list.getFirst(); 36 | } 37 | 38 | public static void main(String [] args){ 39 | Queue store = new QueueImplLinkedList<>(); 40 | store.enqueue(4); 41 | store.enqueue(3); 42 | store.enqueue(2); 43 | System.out.println(store.dequeue()); 44 | System.out.println(store.dequeue()); 45 | System.out.println(store.dequeue()); 46 | System.out.println(store.dequeue()); 47 | store.enqueue(4); 48 | store.enqueue(3); 49 | store.enqueue(2); 50 | System.out.println(store.dequeue()); 51 | System.out.println(store.dequeue()); 52 | System.out.println(store.dequeue()); 53 | System.out.println(store.dequeue()); 54 | store.enqueue(4); 55 | store.enqueue(3); 56 | store.enqueue(2); 57 | System.out.println(store.dequeue()); 58 | System.out.println(store.dequeue()); 59 | System.out.println(store.dequeue()); 60 | System.out.println(store.dequeue()); 61 | 62 | } 63 | 64 | @Override 65 | public Iterator iterator() { 66 | return list.iterator(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/Section_2/Stack.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | public interface Stack extends OrderedStore 4 | { 5 | void push(E value); 6 | E pop(); 7 | E peek(); 8 | 9 | @Override 10 | default E checkFirst(){ 11 | return peek(); 12 | } 13 | 14 | @Override 15 | default void insert(E value){ 16 | push(value); 17 | } 18 | 19 | @Override 20 | default E pickFirst(){ 21 | return pop(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Section_2/StackImplLinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | 4 | 5 | import java.util.Iterator; 6 | 7 | /** 8 | * Created by debasishc on 12/8/16. 9 | */ 10 | public class StackImplLinkedList implements Stack { 11 | protected LinkedList list = getNewLinkedList(); 12 | 13 | protected LinkedList getNewLinkedList(){ 14 | return new LinkedList<>(); 15 | } 16 | 17 | @Override 18 | public void push(E value) { 19 | list.appendFirst(value); 20 | } 21 | 22 | @Override 23 | public E pop() { 24 | if(list.getLength()==0){ 25 | return null; 26 | } 27 | E value = list.getFirst(); 28 | list.removeFirst(); 29 | return value; 30 | } 31 | 32 | @Override 33 | public E peek() { 34 | if(list.getLength()==0){ 35 | return null; 36 | } 37 | return list.getFirst(); 38 | } 39 | 40 | public static void main(String [] args){ 41 | Stack store = new StackImplLinkedList<>(); 42 | store.push(4); 43 | store.push(3); 44 | store.push(2); 45 | System.out.println(store.pop()); 46 | System.out.println(store.pop()); 47 | System.out.println(store.pop()); 48 | System.out.println(store.pop()); 49 | 50 | } 51 | 52 | @Override 53 | public Iterator iterator() { 54 | return list.iterator(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Section_2/Tree.java: -------------------------------------------------------------------------------- 1 | package Section_2; 2 | 3 | import Section_1.OneArgumentStatement; 4 | 5 | public class Tree { 6 | 7 | public static class Node{ 8 | private E value; 9 | private LinkedList> children; 10 | private Tree hostTree; 11 | private Node parent; 12 | 13 | public E getValue() { 14 | return value; 15 | } 16 | public LinkedList> getChildren() { 17 | return children; 18 | } 19 | 20 | private Node(LinkedList> children, Tree hostTree, E value, Node parent) { 21 | this.children = children; 22 | this.hostTree = hostTree; 23 | this.value = value; 24 | this.parent = parent; 25 | } 26 | } 27 | private Node root; 28 | 29 | public void addRoot(E value){ 30 | if(root == null){ 31 | root = new Node<>(new LinkedList<>(), this, value, null ); 32 | }else{ 33 | throw new IllegalStateException("Trying to add new node to a non empty tree"); 34 | } 35 | } 36 | 37 | public Node addNode(Node parent, E value){ 38 | if(parent==null){ 39 | throw new NullPointerException("Cannot add child to null parent"); 40 | }else if(parent.hostTree != this){ 41 | throw new IllegalArgumentException("Parent node not a part of this tree"); 42 | }else{ 43 | Node newNode = new Node<>(new LinkedList<>(), this, value, parent); 44 | parent.getChildren().appendLast(newNode); 45 | return newNode; 46 | } 47 | } 48 | 49 | public Node getRoot() { 50 | return root; 51 | } 52 | 53 | protected void traverseDepthFirst(OneArgumentStatement processor, Node current){ 54 | processor.doSomething(current.value); 55 | current.children.forEach((n)-> traverseDepthFirst(processor, n)); 56 | } 57 | 58 | public void traverseDepthFirst(OneArgumentStatement processor){ 59 | traverseDepthFirst(processor, getRoot()); 60 | } 61 | 62 | public void traverseDepthFirstUsingStack(OneArgumentStatement processor){ 63 | Stack> stack = new StackImplLinkedList<>(); 64 | stack.push(getRoot()); 65 | while(stack.peek()!=null){ 66 | Node current = stack.pop(); 67 | processor.doSomething(current.value); 68 | LinkedList> reverseList = new LinkedList<>(); 69 | current.children.forEach((n)->reverseList.appendFirst(n)); 70 | reverseList.forEach((n)->stack.push(n)); 71 | } 72 | } 73 | 74 | public void traverseBreadthFirst(OneArgumentStatement processor){ 75 | Queue> queue = new QueueImplLinkedList<>(); 76 | queue.enqueue(getRoot()); 77 | while(queue.peek()!=null){ 78 | Node current = queue.dequeue(); 79 | processor.doSomething(current.value); 80 | current.children.forEach((n)->queue.enqueue(n)); 81 | } 82 | } 83 | 84 | public static void main(String [] args){ 85 | Tree tree = new Tree<>(); 86 | tree.addRoot(1); 87 | Node node1 = tree.getRoot(); 88 | Node node2 = tree.addNode(node1, 5); 89 | Node node3 = tree.addNode(node1, 1); 90 | Node node4 = tree.addNode(node2, 2); 91 | Node node5 = tree.addNode(node2, 5); 92 | Node node6 = tree.addNode(node2, 9); 93 | Node node7 = tree.addNode(node3, 6); 94 | Node node8 = tree.addNode(node3, 2); 95 | Node node9 = tree.addNode(node5, 5); 96 | Node node10 = tree.addNode(node6, 9); 97 | Node node11 = tree.addNode(node6, 6); 98 | 99 | tree.traverseDepthFirst(System.out::print); 100 | System.out.println(); 101 | tree.traverseDepthFirstUsingStack(System.out::print); 102 | System.out.println(); 103 | tree.traverseBreadthFirst(System.out::print); 104 | System.out.println(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/Section_3/AVLTree.java: -------------------------------------------------------------------------------- 1 | package Section_3; 2 | 3 | import Section_2.BinaryTree; 4 | 5 | public class AVLTree> extends BinarySearchTree{ 6 | public static class Node> extends BinaryTree.Node{ 7 | protected int height = 0; 8 | public Node(BinaryTree.Node parent, 9 | BinaryTree containerTree, E value) { 10 | super(parent, containerTree, value); 11 | } 12 | } 13 | @Override 14 | protected BinaryTree.Node newNode(BinaryTree.Node parent, BinaryTree containerTree,E value) { 15 | return new Node(parent, containerTree, value); 16 | } 17 | 18 | private int nullSafeHeight(Node node){ 19 | if(node==null){ 20 | return 0; 21 | }else{ 22 | return node.height; 23 | } 24 | } 25 | 26 | private void nullSafeComputeHeight(Node node){ 27 | Node left = (Node) node.getLeft(); 28 | Node right = (Node) node.getRight(); 29 | int leftHeight = left==null? 0 : left.height; 30 | int rightHeight = right==null? 0 :right.height; 31 | node.height = Math.max(leftHeight, rightHeight)+1; 32 | } 33 | 34 | @Override 35 | protected void rotate(BinaryTree.Node node, boolean left) { 36 | Node n = (Node) node; 37 | Node child; 38 | if(left){ 39 | child = (Node) n.getRight(); 40 | }else{ 41 | child = (Node) n.getLeft(); 42 | } 43 | super.rotate(node, left); 44 | if(node!=null){ 45 | nullSafeComputeHeight(n); 46 | } 47 | if(child!=null){ 48 | nullSafeComputeHeight(child); 49 | } 50 | } 51 | 52 | protected void rebalance(Node node){ 53 | if(node==null){ 54 | return; 55 | } 56 | 57 | nullSafeComputeHeight(node); 58 | int leftHeight = nullSafeHeight((Node) node.getLeft()); 59 | int rightHeight = nullSafeHeight((Node) node.getRight()); 60 | 61 | switch (leftHeight-rightHeight){ 62 | case -1: 63 | case 0: 64 | case 1: 65 | rebalance((Node) node.getParent()); 66 | break; 67 | case 2: 68 | int childLeftHeight = nullSafeHeight( 69 | (Node) node.getLeft().getLeft()); 70 | int childRightHeight = nullSafeHeight( 71 | (Node) node.getLeft().getRight()); 72 | if(childRightHeight > childLeftHeight){ 73 | rotate(node.getLeft(), true); 74 | } 75 | Node oldParent = (Node) node.getParent(); 76 | rotate(node, false); 77 | rebalance(oldParent); 78 | break; 79 | case -2: 80 | childLeftHeight = nullSafeHeight( 81 | (Node) node.getRight().getLeft()); 82 | childRightHeight = nullSafeHeight( 83 | (Node) node.getRight().getRight()); 84 | if(childLeftHeight > childRightHeight){ 85 | rotate(node.getRight(), false); 86 | } 87 | oldParent = (Node) node.getParent(); 88 | rotate(node, true); 89 | rebalance(oldParent); 90 | break; 91 | } 92 | } 93 | 94 | @Override 95 | public BinaryTree.Node insertValue(E value) { 96 | Node node = (Node) super.insertValue(value); 97 | if(node!=null) 98 | rebalance(node); 99 | return node; 100 | } 101 | 102 | @Override 103 | public BinaryTree.Node deleteValue(E value) { 104 | Node node = (Node) super.deleteValue(value); 105 | if(node==null){ 106 | return null; 107 | } 108 | Node parentNode = (Node) node.getParent(); 109 | rebalance(parentNode); 110 | return node; 111 | } 112 | 113 | public static void main(String [] args){ 114 | AVLTree tree = new AVLTree<>(); 115 | for(int i=0;i<20;i++){ 116 | tree.insertValue(i); 117 | } 118 | tree.insertValue(9); 119 | tree.deleteValue(12); 120 | tree.deleteValue(14); 121 | tree.displayText(); 122 | } 123 | } -------------------------------------------------------------------------------- /src/Section_3/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package Section_3; 2 | 3 | import Section_2.BinaryTree; 4 | 5 | public class BinarySearchTree> extends BinaryTree { 6 | 7 | protected Node searchValue(E value, Node root){ 8 | if(root==null){ 9 | return null; 10 | } 11 | int comp = root.getValue().compareTo(value); 12 | if(comp == 0){ 13 | return root; 14 | }else if(comp>0){ 15 | return searchValue(value, root.getLeft()); 16 | }else{ 17 | return searchValue(value, root.getRight()); 18 | } 19 | } 20 | 21 | public Node searchValue(E value){ 22 | if(getRoot()==null){ 23 | return null; 24 | }else{ 25 | return searchValue(value, getRoot()); 26 | } 27 | } 28 | 29 | protected Node insertValue(E value, Node node){ 30 | int comp = node.getValue().compareTo(value); 31 | Node child; 32 | if(comp<0){ 33 | child = node.getRight(); 34 | if(child==null){ 35 | return addChild(node,value,false); 36 | }else{ 37 | return insertValue(value, child); 38 | } 39 | }else if(comp>0){ 40 | child = node.getLeft(); 41 | if(child==null){ 42 | return addChild(node,value,true); 43 | }else{ 44 | return insertValue(value, child); 45 | } 46 | }else{ 47 | return null; 48 | } 49 | } 50 | 51 | public Node insertValue(E value){ 52 | if(getRoot()==null){ 53 | addRoot(value); 54 | return getRoot(); 55 | }else{ 56 | return insertValue(value, getRoot()); 57 | } 58 | } 59 | 60 | protected Node getLeftMost(Node node){ 61 | if(node==null){ 62 | return null; 63 | }else if(node.getLeft()==null){ 64 | return node; 65 | }else{ 66 | return getLeftMost(node.getLeft()); 67 | } 68 | } 69 | 70 | private Node deleteNode(Node nodeToBeDeleted){ 71 | boolean direction; 72 | if(nodeToBeDeleted.getParent()!=null 73 | && nodeToBeDeleted.getParent().getLeft()==nodeToBeDeleted){ 74 | direction = true; 75 | }else{ 76 | direction = false; 77 | } 78 | if(nodeToBeDeleted.getLeft()==null && nodeToBeDeleted.getRight()==null){ 79 | deleteNodeWithSubtree(nodeToBeDeleted); 80 | return nodeToBeDeleted; 81 | }else if(nodeToBeDeleted.getLeft()==null){ 82 | if(nodeToBeDeleted.getParent() == null){ 83 | root = nodeToBeDeleted.getRight(); 84 | }else { 85 | setChild(nodeToBeDeleted.getParent(), 86 | nodeToBeDeleted.getRight(), direction); 87 | } 88 | return nodeToBeDeleted; 89 | }else if(nodeToBeDeleted.getRight()==null){ 90 | if(nodeToBeDeleted.getParent() == null){ 91 | root = nodeToBeDeleted.getLeft(); 92 | }else { 93 | setChild(nodeToBeDeleted.getParent(), 94 | nodeToBeDeleted.getLeft(), direction); 95 | } 96 | return nodeToBeDeleted; 97 | }else{ 98 | Node nodeToBeReplaced = getLeftMost(nodeToBeDeleted.getRight()); 99 | setValue(nodeToBeDeleted, nodeToBeReplaced.getValue()); 100 | deleteNode(nodeToBeReplaced); 101 | return nodeToBeReplaced; 102 | } 103 | } 104 | 105 | public Node deleteValue(E value){ 106 | Node nodeToBeDeleted = searchValue(value); 107 | if(nodeToBeDeleted==null){ 108 | return null; 109 | }else{ 110 | 111 | return deleteNode(nodeToBeDeleted); 112 | } 113 | } 114 | 115 | public static void main(String[] args) { 116 | BinarySearchTree tree = new BinarySearchTree<>(); 117 | int stored = -1; 118 | for(int i=0;i<20;i++){ 119 | int value = (int) (100*Math.random()); 120 | tree.insertValue(value); 121 | if(stored == -1 && (Math.random()>0.7 || i == 19)){ 122 | stored = value; 123 | } 124 | } 125 | tree.traverseDepthFirst((x)-> 126 | System.out.print(" "+x), tree.getRoot(), DepthFirstTraversalType.INORDER); 127 | System.out.println(); 128 | System.out.println("=========================================="); 129 | tree.displayText(); 130 | } 131 | } -------------------------------------------------------------------------------- /src/Section_3/HashTable.java: -------------------------------------------------------------------------------- 1 | package Section_3; 2 | 3 | import Section_2.LinkedList; 4 | 5 | public class HashTable { 6 | protected LinkedList [] buckets; 7 | protected double maximumLoadFactor; 8 | protected int totalValues; 9 | 10 | public HashTable(int initialSize, double maximumLoadFactor){ 11 | buckets = new LinkedList[initialSize]; 12 | this.maximumLoadFactor = maximumLoadFactor; 13 | } 14 | 15 | protected boolean insert(E value, int arrayLength,LinkedList[] array) { 16 | int hashCode = value.hashCode(); 17 | int arrayIndex = hashCode % arrayLength; 18 | LinkedList bucket = array[arrayIndex]; 19 | if(bucket == null){ 20 | bucket = new LinkedList<>(); 21 | array[arrayIndex] = bucket; 22 | } 23 | for(E element: bucket){ 24 | if(element.equals(value)){ 25 | return false; 26 | } 27 | } 28 | bucket.appendLast(value); 29 | totalValues++; 30 | return true; 31 | } 32 | 33 | protected void rehash(){ 34 | double loadFactor = ((double)(totalValues))/buckets.length; 35 | if(loadFactor>maximumLoadFactor){ 36 | LinkedList [] newBuckets = new LinkedList[buckets.length*2]; 37 | totalValues = 0; 38 | for(LinkedList bucket:buckets){ 39 | if(bucket!=null) { 40 | for (E element : bucket) { 41 | insert(element, newBuckets.length,newBuckets); 42 | } 43 | } 44 | } 45 | this.buckets = newBuckets; 46 | } 47 | } 48 | 49 | public boolean insert(E value){ 50 | int arrayLength = buckets.length; 51 | LinkedList[] array = buckets; 52 | boolean inserted = insert(value, arrayLength, array); 53 | if(inserted) 54 | rehash(); 55 | return inserted; 56 | } 57 | 58 | public E search(E value){ 59 | int hash = value.hashCode(); 60 | int index = hash % buckets.length; 61 | LinkedList bucket = buckets[index]; 62 | if(bucket==null){ 63 | return null; 64 | }else{ 65 | for(E element: bucket){ 66 | if(element.equals(value)){ 67 | return element; 68 | } 69 | } 70 | return null; 71 | } 72 | } 73 | 74 | public static void main(String [] args){ 75 | HashTable hashTable = new HashTable<>(2, 3); 76 | for (int i = 0; i < 200; i++) { 77 | hashTable.insert(String.valueOf((int)(Math.random()*200))); 78 | } 79 | 80 | for(LinkedList bucket:hashTable.buckets){ 81 | if(bucket!=null) 82 | for(String x:bucket){ 83 | System.out.print(x+","); 84 | } 85 | System.out.println(); 86 | } 87 | 88 | for (int i = 0; i < 200; i++) { 89 | String searchedValue = String.valueOf((int)(Math.random()*200)); 90 | System.out.println(searchedValue + ":" + hashTable.search(searchedValue)); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/Section_3/RedBlackTree.java: -------------------------------------------------------------------------------- 1 | package Section_3; 2 | 3 | import Section_2.BinaryTree; 4 | 5 | public class RedBlackTree> extends BinarySearchTree { 6 | public static class Node extends BinaryTree.Node{ 7 | protected int blackHeight = 0; 8 | protected boolean black = false; 9 | public Node(BinaryTree.Node parent,BinaryTree containerTree, E value) { 10 | super(parent, containerTree, value); 11 | } 12 | } 13 | 14 | @Override 15 | protected BinaryTree.Node newNode(BinaryTree.Node parent, BinaryTree containerTree,E value) { 16 | return new Node(parent, containerTree, value); 17 | } 18 | 19 | protected boolean nullSafeBlack(Node node){ 20 | if(node == null){ 21 | return true; 22 | }else{ 23 | return node.black; 24 | } 25 | } 26 | 27 | protected void rebalanceForInsert(Node node){ 28 | if(node.getParent() == null){ 29 | node.black = true; 30 | }else{ 31 | Node parent = (Node) node.getParent(); 32 | if(parent.black){ 33 | return; 34 | }else{ 35 | Node grandParent = (Node) parent.getParent(); 36 | boolean nodeLeftGrandChild = grandParent.getLeft()== parent; 37 | Node uncle 38 | = nodeLeftGrandChild? 39 | (Node) grandParent.getRight(): (Node) grandParent.getLeft(); 40 | if(!nullSafeBlack(uncle)){ 41 | if(grandParent!=root) 42 | grandParent.black = false; 43 | uncle.black = true; 44 | parent.black = true; 45 | rebalanceForInsert(grandParent); 46 | }else{ 47 | boolean middleChild 48 | = nodeLeftGrandChild? 49 | parent.getRight() == node:parent.getLeft() == node; 50 | if (middleChild){ 51 | rotate(parent, nodeLeftGrandChild); 52 | node = parent; 53 | parent = (Node) node.getParent(); 54 | } 55 | parent.black = true; 56 | grandParent.black = false; 57 | rotate(grandParent, !nodeLeftGrandChild); 58 | } 59 | } 60 | } 61 | } 62 | 63 | @Override 64 | public BinaryTree.Node insertValue(E value) { 65 | Node node = (Node) super.insertValue(value); 66 | if(node!=null) 67 | rebalanceForInsert(node); 68 | return node; 69 | } 70 | 71 | protected void rebalanceForDelete(Node parent,boolean nodeDirectionLeft) { 72 | if(parent==null){ 73 | return; 74 | } 75 | Node node = 76 | (Node) (nodeDirectionLeft? parent.getLeft(): parent.getRight()); 77 | if(!nullSafeBlack(node)){ 78 | node.black = true; 79 | return; 80 | } 81 | Node sibling = 82 | (Node) (nodeDirectionLeft? parent.getRight(): parent.getLeft()); 83 | Node nearNephew = 84 | (Node) (nodeDirectionLeft?sibling.getLeft():sibling.getRight()); 85 | Node awayNephew = 86 | (Node) (nodeDirectionLeft?sibling.getRight():sibling.getLeft()); 87 | if(parent.black){ 88 | if(sibling.black){ 89 | if(nullSafeBlack(nearNephew) && nullSafeBlack(awayNephew)){ 90 | sibling.black = false; 91 | if(parent.getParent()!=null){ 92 | rebalanceForDelete ( 93 | (Node) parent.getParent(), parent.getParent() 94 | .getLeft() == parent); 95 | } 96 | }else if(!nullSafeBlack(awayNephew)){ 97 | awayNephew.black = true; 98 | rotate(parent, nodeDirectionLeft); 99 | }else{ 100 | nearNephew.black = true; 101 | rotate(sibling, !nodeDirectionLeft); 102 | rotate(parent, nodeDirectionLeft); 103 | } 104 | }else{ 105 | parent.black = false; 106 | sibling.black = true; 107 | rotate(parent, nodeDirectionLeft); 108 | rebalanceForDelete(parent, nodeDirectionLeft); 109 | } 110 | }else{ 111 | if(nullSafeBlack(nearNephew)){ 112 | rotate(parent, nodeDirectionLeft); 113 | }else{ 114 | parent.black = true; 115 | rotate(sibling, !nodeDirectionLeft); 116 | rotate(parent, nodeDirectionLeft); 117 | } 118 | } 119 | } 120 | 121 | @Override 122 | public BinaryTree.Node deleteValue(E value) { 123 | Node node = (Node) super.deleteValue(value); 124 | 125 | if(node !=null && node.black && node.getParent()!=null){ 126 | Node parentsCurrentChild = 127 | (Node) (node.getLeft() == null ? node.getRight(): node.getLeft()); 128 | if(parentsCurrentChild!=null){ 129 | boolean isLeftChild 130 | = parentsCurrentChild.getParent().getLeft() == parentsCurrentChild; 131 | rebalanceForDelete( 132 | (Node) node.getParent(), isLeftChild); 133 | }else{ 134 | boolean isLeftChild 135 | = node.getParent().getRight()!=null; 136 | rebalanceForDelete( 137 | (Node) node.getParent(), isLeftChild); 138 | } 139 | 140 | } 141 | return node; 142 | } 143 | 144 | protected void displayText(BinaryTree.Node parent, int depth){ 145 | 146 | for(int i=0;i)parent).black){ 154 | System.out.print("B"); 155 | }else{ 156 | System.out.print("R"); 157 | } 158 | System.out.println(parent.getValue()); 159 | displayText(parent.getLeft(),depth+1); 160 | displayText(parent.getRight(),depth+1); 161 | } 162 | 163 | public static void main(String [] args) { 164 | RedBlackTree tree = new RedBlackTree<>(); 165 | for (int i = 0; i < 20; i++) { 166 | tree.insertValue((int)(Math.random()*1000000)); 167 | } 168 | tree.deleteValue(7); 169 | System.out.println(7); 170 | System.out.println("============================================"); 171 | tree.displayText(); 172 | } 173 | } -------------------------------------------------------------------------------- /src/Section_4/ArrayHeap.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.Iterator; 6 | 7 | public class ArrayHeap implements PriorityQueue { 8 | protected E[] store; 9 | protected Comparator comparator; 10 | int numElements = 0; 11 | 12 | public ArrayHeap(int size, Comparator comparator){ 13 | store = (E[]) new Object[size]; 14 | this.comparator = comparator; 15 | } 16 | 17 | protected int parentIndex(int nodeIndex){ 18 | return ((nodeIndex+1)/2)-1; 19 | } 20 | 21 | protected int leftChildIndex(int nodeIndex){ 22 | return (nodeIndex+1)*2 -1; 23 | } 24 | 25 | protected int rightChildIndex(int nodeIndex){ 26 | return (nodeIndex+1)*2; 27 | } 28 | 29 | protected void swap(int index1, int index2){ 30 | E temp = store[index1]; 31 | store[index1] = store[index2]; 32 | store[index2] = temp; 33 | } 34 | 35 | protected void trickleUp(int position){ 36 | int parentIndex = parentIndex(position); 37 | if(position> 0 && comparator.compare(store[parentIndex], store[position])>0){ 38 | swap(position, parentIndex); 39 | trickleUp(parentIndex); 40 | } 41 | } 42 | 43 | public void insert(E value){ 44 | if(numElements == store.length){ 45 | throw new NoSpaceException("Insertion in a full heap"); 46 | } 47 | store[numElements] = value; 48 | numElements++; 49 | trickleUp(numElements-1); 50 | } 51 | 52 | protected void trickleDown(int position){ 53 | int leftChild = leftChildIndex(position); 54 | int rightChild = leftChild+1; 55 | if(rightChild=numElements){ 112 | System.out.println("*"); 113 | return; 114 | } 115 | System.out.println(store[parent]); 116 | displayText(leftChildIndex(parent),depth+1); 117 | displayText(rightChildIndex(parent),depth+1); 118 | } 119 | 120 | protected void displayText(){ 121 | displayText(0, 0); 122 | } 123 | 124 | public static void heapSort(E[] array, Comparator comparator){ 125 | ArrayHeap arrayHeap = new ArrayHeap(0, (a,b) -> comparator.compare(b,a)); 126 | arrayHeap.store = array; 127 | for(int i=0;i=0;i--){ 131 | array[i] = arrayHeap.removeMin(); 132 | } 133 | } 134 | 135 | public static void main(String [] args){ 136 | ArrayHeap heap = new ArrayHeap<>(200, (a,b)-> b-a); 137 | 138 | 139 | Integer[] array = new Integer[200]; 140 | for(int i=0;i<200;i++){ 141 | array[i] = (int)(Math.random()*1000); 142 | } 143 | System.out.println(Arrays.toString(array)); 144 | ArrayHeap.heapSort(array, (a,b)->a-b); 145 | System.out.println(Arrays.toString(array)); 146 | } 147 | } -------------------------------------------------------------------------------- /src/Section_4/BinomialForest.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Comparator; 4 | import java.util.Iterator; 5 | 6 | public class BinomialForest implements PriorityQueue { 7 | protected Comparator comparator; 8 | 9 | protected static class BinomialTree{ 10 | E value; 11 | LinkedList> subTrees = new LinkedList<>(); 12 | 13 | public BinomialTree(E value){ 14 | this.value = value; 15 | } 16 | 17 | public void displayTree(int depth){ 18 | for(int i=0;i subTree: subTrees){ 23 | subTree.displayTree(depth+1); 24 | } 25 | System.out.println(); 26 | } 27 | } 28 | public BinomialForest(Comparator comparator){ 29 | this.comparator = comparator; 30 | } 31 | 32 | DoublyLinkedList> allTrees = new DoublyLinkedList<>(); 33 | 34 | protected BinomialTree merge(BinomialTree left, BinomialTree right){ 35 | if(left==null){ 36 | return right; 37 | }else if(right==null){ 38 | return left; 39 | } 40 | if(left.subTrees.getLength() != right.subTrees.getLength()){ 41 | throw new IllegalArgumentException("Trying to merge two unequal trees of sizes " + 42 | left.subTrees.getLength() + " and " + right.subTrees.getLength()); 43 | } 44 | if(comparator.compare(left.value, right.value)<0){ 45 | left.subTrees.appendLast(right); 46 | return left; 47 | }else{ 48 | right.subTrees.appendLast(left); 49 | return right; 50 | } 51 | } 52 | 53 | BinomialTree minTree = null; 54 | int minTreeIndex = -1; 55 | 56 | protected void updateMinTree(){ 57 | if(allTrees.getLength()==0){ 58 | minTree = null; 59 | minTreeIndex = -1; 60 | } 61 | E min = null; 62 | int index = 0; 63 | for(BinomialTree tree:allTrees){ 64 | if(tree==null){ 65 | index++; 66 | continue; 67 | } 68 | if(min == null || comparator.compare(min, tree.value)>0){ 69 | min = tree.value; 70 | minTree = tree; 71 | minTreeIndex = index; 72 | } 73 | index++; 74 | } 75 | } 76 | 77 | protected BinomialTree computeOutputWithoutCarry(BinomialTree lhs, BinomialTree rhs, BinomialTree carry){ 78 | if(carry==null){ 79 | if(lhs==null){ 80 | return rhs; 81 | }else if(rhs==null){ 82 | return lhs; 83 | }else{ 84 | return null; 85 | } 86 | }else{ 87 | if(lhs==null && rhs==null){ 88 | return carry; 89 | }else if(lhs == null){ 90 | return null; 91 | }else if(rhs == null){ 92 | return null; 93 | }else{ 94 | return carry; 95 | } 96 | } 97 | } 98 | 99 | protected BinomialTree computeCarry(BinomialTree lhs, BinomialTree rhs, BinomialTree carry){ 100 | if(carry==null){ 101 | if(lhs!=null && rhs!=null){ 102 | return merge(lhs, rhs); 103 | }else{ 104 | return null; 105 | } 106 | }else{ 107 | if(lhs==null && rhs==null){ 108 | return null; 109 | }else if(lhs == null){ 110 | return merge(carry, rhs); 111 | }else if(rhs == null){ 112 | return merge(carry, lhs); 113 | }else{ 114 | return merge(lhs, rhs); 115 | } 116 | } 117 | } 118 | 119 | protected void merge(LinkedList> rhs){ 120 | LinkedList>.ListIterator lhsIter 121 | = (LinkedList>.ListIterator)allTrees.iterator(); 122 | Iterator> rhsIter = rhs.iterator(); 123 | BinomialTree carry = null; 124 | while(lhsIter.hasNext() || rhsIter.hasNext()){ 125 | boolean lhsHasValue = lhsIter.hasNext(); 126 | BinomialTree lhsTree = lhsHasValue? lhsIter.next():null; 127 | BinomialTree rhsTree = rhsIter.hasNext()? rhsIter.next():null; 128 | BinomialTree entry = computeOutputWithoutCarry(lhsTree, rhsTree, carry); 129 | carry = computeCarry(lhsTree, rhsTree, carry); 130 | if(lhsHasValue) { 131 | lhsIter.setValue(entry); 132 | }else{ 133 | this.allTrees.appendLast(entry); 134 | } 135 | } 136 | if(carry!=null){ 137 | this.allTrees.appendLast(carry); 138 | } 139 | updateMinTree(); 140 | } 141 | 142 | public void insert(E value){ 143 | BinomialTree newTree = new BinomialTree(value); 144 | DoublyLinkedList> newList = new DoublyLinkedList<>(); 145 | newList.appendLast(newTree); 146 | merge(newList); 147 | } 148 | 149 | public E removeMin(){ 150 | if(allTrees.getLength()==0){ 151 | return null; 152 | } 153 | E min = minTree.value; 154 | if(minTreeIndex==allTrees.getLength()-1){ 155 | allTrees.removeLast(); 156 | }else { 157 | allTrees.setValueAtIndex(minTreeIndex, null); 158 | } 159 | merge(minTree.subTrees); 160 | return min; 161 | } 162 | 163 | @Override 164 | public E dequeueMinimum() { 165 | return removeMin(); 166 | } 167 | 168 | @Override 169 | public void enqueue(E value) { 170 | insert(value); 171 | } 172 | 173 | @Override 174 | public E checkMinimum(){ 175 | return minTree==null? null:minTree.value; 176 | } 177 | 178 | public static void main(String [] args){ 179 | BinomialForest binomialForest = new BinomialForest<>((a,b)->a-b); 180 | for(int i=1;i<100;i++){ 181 | binomialForest.insert((int)(Math.random()*1000)); 182 | } 183 | for(BinomialTree tree: binomialForest.allTrees){ 184 | if(tree!=null) 185 | tree.displayTree(0); 186 | System.out.println("=================="); 187 | } 188 | System.out.println(binomialForest.checkMinimum()); 189 | while (binomialForest.checkMinimum()!=null){ 190 | Integer min = binomialForest.removeMin(); 191 | if(min==null){ 192 | break; 193 | } 194 | System.out.print(" "+min+","); 195 | } 196 | System.out.println(); 197 | } 198 | } -------------------------------------------------------------------------------- /src/Section_4/DoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Iterator; 4 | import java.util.NoSuchElementException; 5 | 6 | /** 7 | * Created by debasishc on 21/7/16. 8 | */ 9 | public class DoublyLinkedList extends LinkedList { 10 | 11 | public static class DoublyLinkedNode extends Node { 12 | protected DoublyLinkedNode prev; 13 | } 14 | 15 | 16 | @Override 17 | protected Node getNewNode() { 18 | return new DoublyLinkedNode<>(); 19 | } 20 | 21 | @Override 22 | public Node appendFirst(E value) { 23 | Node node = super.appendFirst(value); 24 | if (first.next != null) 25 | ((DoublyLinkedNode) first.next).prev = (DoublyLinkedNode) first; 26 | return node; 27 | } 28 | 29 | @Override 30 | public Node insert(int index, E value) { 31 | DoublyLinkedNode inserted = (DoublyLinkedNode) super.insert(index, value); 32 | if(index!=0 && index!=length) { 33 | if (inserted.next != null) { 34 | inserted.prev = ((DoublyLinkedNode) inserted.next).prev; 35 | ((DoublyLinkedNode) inserted.next).prev = inserted; 36 | } 37 | } 38 | return inserted; 39 | } 40 | 41 | @Override 42 | public Node appendLast(E value) { 43 | DoublyLinkedNode origLast = (DoublyLinkedNode) this.last; 44 | Node node = super.appendLast(value); 45 | ((DoublyLinkedNode) this.last).prev = origLast; 46 | return node; 47 | } 48 | 49 | @Override 50 | public Node removeAtIndex(int index) { 51 | if(index<0||index>=length){ 52 | throw new NoSuchElementException("index = "+index); 53 | } 54 | if(index==length-1){ 55 | return removeLast(); 56 | } 57 | DoublyLinkedNode nodeRemoved = (DoublyLinkedNode) super.removeAtIndex(index); 58 | if ((DoublyLinkedNode) nodeRemoved.next != null) 59 | ((DoublyLinkedNode) nodeRemoved.next).prev = nodeRemoved.prev; 60 | 61 | return nodeRemoved; 62 | } 63 | 64 | 65 | @Override 66 | public Node removeFirst() { 67 | super.removeFirst(); 68 | if (first != null) { 69 | ((DoublyLinkedNode) first).prev = null; 70 | } 71 | return first; 72 | } 73 | 74 | public void removeNode(DoublyLinkedNode node){ 75 | if(node==last){ 76 | removeLast(); 77 | }else if(node==first){ 78 | removeFirst(); 79 | }else{ 80 | node.prev.next = node.next; 81 | length--; 82 | } 83 | } 84 | 85 | @Override 86 | public Node removeLast() { 87 | Node origLast = last; 88 | if(last==null){ 89 | throw new IllegalStateException("Removing element from an empty list"); 90 | } 91 | 92 | last = ((DoublyLinkedNode)last).prev; 93 | if(last!=null){ 94 | last.next = null; 95 | }else{ 96 | first = null; 97 | } 98 | length--; 99 | return origLast; 100 | } 101 | 102 | protected class ReverseListIterator extends ListIterator{ 103 | public ReverseListIterator(){ 104 | nextNode = last; 105 | } 106 | 107 | @Override 108 | public E next() { 109 | if(nextNode == null) 110 | throw new IllegalStateException(); 111 | DoublyLinkedNode nodeToReturn = (DoublyLinkedNode) nextNode; 112 | nextNode = nodeToReturn.prev; 113 | return nodeToReturn.value; 114 | } 115 | } 116 | 117 | public Iterator reverseIterator(){ 118 | return new ReverseListIterator(); 119 | } 120 | 121 | public static void main(String [] args){ 122 | DoublyLinkedList doublyLinkedList = new DoublyLinkedList<>(); 123 | doublyLinkedList.appendFirst(4); 124 | doublyLinkedList.appendFirst(1); 125 | doublyLinkedList.appendFirst(2); 126 | doublyLinkedList.appendFirst(3); 127 | doublyLinkedList.appendLast(8); 128 | doublyLinkedList.appendLast(7); 129 | doublyLinkedList.appendLast(18); 130 | doublyLinkedList.appendFirst(3); 131 | doublyLinkedList.appendLast(8); 132 | doublyLinkedList.appendLast(7); 133 | doublyLinkedList.appendLast(18); 134 | doublyLinkedList.insert(2, 51); 135 | doublyLinkedList.insert(0, 510); 136 | 137 | while (doublyLinkedList.getLength()>0) 138 | { 139 | doublyLinkedList.removeLast(); 140 | } 141 | 142 | 143 | Iterator reverseIterator = doublyLinkedList.reverseIterator(); 144 | while(reverseIterator.hasNext()){ 145 | System.out.println(reverseIterator.next()); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/Section_4/LinkedHeap.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Comparator; 4 | import java.util.Iterator; 5 | 6 | public class LinkedHeap implements PriorityQueue { 7 | protected static class Node{ 8 | protected E value; 9 | protected Node left; 10 | protected Node right; 11 | protected Node parent; 12 | 13 | public Node(E value, Node parent){ 14 | this.value = value; 15 | this.parent = parent; 16 | } 17 | } 18 | 19 | protected Node root; 20 | protected int numElements; 21 | 22 | protected Node findNodeAtPostion(int position){ 23 | if(position == 1){ 24 | return root; 25 | }else{ 26 | int side = position % 2; 27 | int parentPosition = position / 2; 28 | Node parent = findNodeAtPostion(parentPosition); 29 | switch (side){ 30 | case 0: 31 | return parent.left; 32 | case 1: 33 | return parent.right; 34 | } 35 | } 36 | return null; 37 | } 38 | 39 | protected void swapWithParent(Node parent,boolean left) { 40 | Node node = left? parent.left:parent.right; 41 | Node leftChild = node.left; 42 | Node rightChild = node.right; 43 | Node sibling = left? parent.right:parent.left; 44 | Node grandParent = parent.parent; 45 | parent.left = leftChild; 46 | if(leftChild!=null){ 47 | leftChild.parent = parent; 48 | } 49 | parent.right = rightChild; 50 | if(rightChild!=null){ 51 | rightChild.parent = parent; 52 | } 53 | parent.parent = node; 54 | if(left){ 55 | node.right = sibling; 56 | node.left = parent; 57 | }else{ 58 | node.left = sibling; 59 | node.right = parent; 60 | } 61 | node.parent = grandParent; 62 | if(sibling!=null) 63 | sibling.parent = node; 64 | 65 | if(parent == root){ 66 | root = node; 67 | }else{ 68 | boolean parentLeft = grandParent.left==parent; 69 | if(parentLeft){ 70 | grandParent.left = node; 71 | }else{ 72 | grandParent.right = node; 73 | } 74 | } 75 | } 76 | 77 | protected Comparator comparator; 78 | 79 | protected void trickleUp(Node node){ 80 | if(node==root){ 81 | return; 82 | }else if(comparator.compare(node.value, node.parent.value)<0){ 83 | swapWithParent(node.parent, node.parent.left == node); 84 | trickleUp(node); 85 | } 86 | } 87 | 88 | public void insert(E value){ 89 | if(root==null){ 90 | root = new Node<>(value, null); 91 | }else{ 92 | Node parent = findNodeAtPostion((numElements+1)/2); 93 | int side = (numElements+1)%2; 94 | Node newNode = new Node<>(value, parent); 95 | switch (side){ 96 | case 0: 97 | parent.left = newNode; 98 | break; 99 | case 1: 100 | parent.right = newNode; 101 | break; 102 | } 103 | trickleUp(newNode); 104 | } 105 | numElements++; 106 | } 107 | 108 | protected void trickleDown(Node node){ 109 | if(node==null){ 110 | return; 111 | } 112 | if(node.left == null){ 113 | return; 114 | }else if(node.right == null){ 115 | if(comparator.compare(node.left.value, node.value)<0){ 116 | swapWithParent(node, true); 117 | trickleDown(node); 118 | } 119 | }else{ 120 | if(comparator.compare(node.left.value, node.right.value)<0){ 121 | if(comparator.compare(node.left.value, node.value)<0){ 122 | swapWithParent(node, true); 123 | trickleDown(node); 124 | } 125 | }else{ 126 | if(comparator.compare(node.right.value, node.value)<0){ 127 | swapWithParent(node, false); 128 | trickleDown(node); 129 | } 130 | } 131 | } 132 | } 133 | 134 | public E removeMin(){ 135 | if(root==null){ 136 | return null; 137 | } 138 | Node lastElement = findNodeAtPostion(numElements); 139 | if(lastElement==root){ 140 | root = null; 141 | numElements--; 142 | return lastElement.value; 143 | } 144 | E value = root.value; 145 | root.value = lastElement.value; 146 | Node parent = lastElement.parent; 147 | if(parent.left==lastElement){ 148 | parent.left = null; 149 | }else{ 150 | parent.right=null; 151 | } 152 | numElements--; 153 | trickleDown(root); 154 | return value; 155 | } 156 | 157 | @Override 158 | public E checkMinimum() { 159 | return root==null? null : root.value; 160 | } 161 | 162 | @Override 163 | public E dequeueMinimum() { 164 | return removeMin(); 165 | } 166 | 167 | @Override 168 | public void enqueue(E value) { 169 | insert(value); 170 | } 171 | 172 | protected void displayText(Node parent, int depth){ 173 | 174 | for(int i=0;i comparator){ 191 | this.comparator = comparator; 192 | } 193 | 194 | public static void main(String [] args){ 195 | LinkedHeap heap = new LinkedHeap<>((a,b)-> b-a); 196 | for(int i=1;i<=100;i++){ 197 | heap.insert((int)(Math.random()*1000)); 198 | } 199 | System.out.println(heap.numElements); 200 | Integer value = null; 201 | while((value = heap.removeMin())!=null){ 202 | System.out.print(value+", "); 203 | } 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/Section_4/LinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Comparator; 4 | import java.util.Iterator; 5 | import java.util.NoSuchElementException; 6 | 7 | public class LinkedList implements Iterable { 8 | protected int length = 0; 9 | protected Node[] lastModifiedNode; 10 | protected Node first; 11 | protected Node last; 12 | 13 | public int getLength(){ 14 | return length; 15 | } 16 | 17 | public void appendAllLast(LinkedList anotherList){ 18 | if(first == null){ 19 | first = anotherList.first; 20 | last = anotherList.last; 21 | }else{ 22 | last.next = anotherList.first; 23 | last = anotherList.last; 24 | } 25 | length += anotherList.length; 26 | 27 | } 28 | 29 | public static void main(String[] args) { 30 | // LinkedList linkedList = new LinkedList<>(); 31 | // linkedList.appendFirst(4); 32 | // linkedList.appendFirst(1); 33 | // linkedList.appendFirst(2); 34 | // linkedList.appendFirst(3); 35 | // linkedList.appendLast(8); 36 | // linkedList.appendLast(7); 37 | // linkedList.appendLast(18); 38 | // linkedList.appendFirst(50); 39 | // linkedList.insert(5, 500); 40 | // linkedList.insert(9, 501); 41 | // linkedList.removeAtIndex(8); 42 | // linkedList.insert(8, 502); 43 | // linkedList.removeAtIndex(1); 44 | 45 | LinkedList anotherList = new LinkedList<>(); 46 | anotherList.appendFirst(4); 47 | anotherList.appendFirst(1); 48 | anotherList.appendFirst(2); 49 | anotherList.appendFirst(3); 50 | anotherList.appendLast(8); 51 | anotherList.appendLast(7); 52 | anotherList.appendLast(1); 53 | anotherList.appendLast(2); 54 | anotherList.appendLast(3); 55 | anotherList.appendLast(18); 56 | // linkedList.appendAllLast(anotherList); 57 | // 58 | // // linkedList.visualize(visualizer); 59 | // 60 | // 61 | // while(anotherList.getLength()>0){ 62 | // anotherList.removeLast(); 63 | // } 64 | 65 | //linkedList.zip(anotherList).visualize(visualizer); 66 | // Iterator iter = anotherList.iterator(); 67 | // while (iter.hasNext()){ 68 | // int val = iter.next(); 69 | // System.out.println(); 70 | // if(val<=4) 71 | // iter.remove(); 72 | // anotherList.visualize(visualizer); 73 | // } 74 | } 75 | 76 | @Override 77 | public Iterator iterator() { 78 | return new ListIterator(); 79 | } 80 | 81 | protected Node getNewNode() { 82 | Node node = new Node<>(); 83 | lastModifiedNode = new Node[]{node}; 84 | return node; 85 | } 86 | 87 | public Node appendFirst(E value) { 88 | Node node = getNewNode(); 89 | node.value = value; 90 | node.next = first; 91 | first = node; 92 | if (length == 0) 93 | last = node; 94 | length++; 95 | return node; 96 | } 97 | 98 | public Node appendLast(E value) { 99 | Node node = getNewNode(); 100 | node.value = value; 101 | if (last != null) 102 | last.next = node; 103 | last = node; 104 | if (first == null) { 105 | first = node; 106 | } 107 | 108 | length++; 109 | return node; 110 | } 111 | 112 | public Node insert(int index, E value) { 113 | Node node = getNewNode(); 114 | if (index < 0 || index > length) { 115 | throw new IllegalArgumentException("Invalid index for insertion"); 116 | } else if (index == length) { 117 | return appendLast(value); 118 | } else if (index == 0) { 119 | return appendFirst(value); 120 | } else { 121 | Node prev = first; 122 | while (index > 1) { 123 | index--; 124 | prev = prev.next; 125 | } 126 | node.value = value; 127 | node.next = prev.next; 128 | prev.next = node; 129 | length++; 130 | return node; 131 | } 132 | } 133 | 134 | public E getFirst() { 135 | if (length == 0) { 136 | throw new NoSuchElementException(); 137 | } 138 | return first.value; 139 | } 140 | 141 | public E getLast() { 142 | if (length == 0) { 143 | throw new NoSuchElementException(); 144 | } 145 | return last.value; 146 | } 147 | 148 | public Node removeFirst() { 149 | if (length == 0) { 150 | throw new NoSuchElementException(); 151 | } 152 | Node origFirst = first; 153 | first = first.next; 154 | length--; 155 | if (length == 0) { 156 | last = null; 157 | } 158 | return origFirst; 159 | } 160 | 161 | 162 | public E findAtIndex(int index) { 163 | Node result = first; 164 | while (index >= 0) { 165 | if (result == null) { 166 | throw new NoSuchElementException(); 167 | } else if (index == 0) { 168 | return result.value; 169 | } else { 170 | index--; 171 | result = result.next; 172 | } 173 | } 174 | return null; 175 | } 176 | 177 | protected Node removeAtIndex(int index) { 178 | if (index >= length || index < 0) { 179 | throw new NoSuchElementException(); 180 | } 181 | 182 | if (index == 0) { 183 | Node nodeRemoved = first; 184 | removeFirst(); 185 | return nodeRemoved; 186 | } 187 | 188 | Node justBeforeIt = first; 189 | while (--index > 0) { 190 | justBeforeIt = justBeforeIt.next; 191 | } 192 | 193 | Node nodeRemoved = justBeforeIt.next; 194 | if (justBeforeIt.next == last) { 195 | last = justBeforeIt.next.next; 196 | } 197 | justBeforeIt.next = justBeforeIt.next.next; 198 | 199 | length--; 200 | 201 | return nodeRemoved; 202 | 203 | } 204 | 205 | public void setValueAtIndex(int index, E value){ 206 | Node result = first; 207 | while (index >= 0) { 208 | if (result == null) { 209 | throw new NoSuchElementException(); 210 | } else if (index == 0) { 211 | result.value = value; 212 | return; 213 | } else { 214 | index--; 215 | result = result.next; 216 | } 217 | } 218 | } 219 | 220 | 221 | public Node removeLast() { 222 | return removeAtIndex(length - 1); 223 | } 224 | 225 | public static class Node { 226 | protected E value; 227 | protected Node next; 228 | 229 | public String toString() { 230 | return value.toString(); 231 | } 232 | 233 | public Node getNext() { 234 | return next; 235 | } 236 | 237 | public E getValue() { 238 | return value; 239 | } 240 | } 241 | 242 | public class ListIterator implements Iterator { 243 | protected Node nextNode = first; 244 | protected Node currentNode = null; 245 | protected Node prevNode = null; 246 | 247 | @Override 248 | public boolean hasNext() { 249 | return nextNode != null; 250 | } 251 | 252 | @Override 253 | public E next() { 254 | if (!hasNext()) { 255 | throw new IllegalStateException(); 256 | } 257 | prevNode = currentNode; 258 | currentNode = nextNode; 259 | nextNode = nextNode.next; 260 | return currentNode.value; 261 | } 262 | 263 | @Override 264 | public void remove() { 265 | if(currentNode==null || currentNode == prevNode){ 266 | throw new IllegalStateException(); 267 | } 268 | if(currentNode==first){ 269 | first = nextNode; 270 | }else{ 271 | prevNode.next = nextNode; 272 | } 273 | currentNode=prevNode; 274 | 275 | } 276 | 277 | public void setValue(E value){ 278 | currentNode.value = value; 279 | } 280 | 281 | } 282 | /* 283 | public void sort(Comparator comparator){ 284 | PriorityQueue priorityQueue = new LinkedHeap(comparator); 285 | while (first!=null){ 286 | priorityQueue.enqueue(getFirst()); 287 | removeFirst(); 288 | } 289 | while (priorityQueue.checkMinimum()!=null){ 290 | appendLast(priorityQueue.dequeueMinimum()); 291 | } 292 | 293 | } 294 | 295 | */ 296 | public LinkedList> zip(LinkedList rhs){ 297 | Iterator lhsIter = this.iterator(); 298 | Iterator rhsIter = rhs.iterator(); 299 | LinkedList> newList = new LinkedList<>(); 300 | while(true){ 301 | if(lhsIter.hasNext() && rhsIter.hasNext()){ 302 | newList.appendLast(new OrderedPair(lhsIter.next(), rhsIter.next())); 303 | }else if(lhsIter.hasNext()){ 304 | newList.appendLast(new OrderedPair(lhsIter.next(), null)); 305 | }else if(rhsIter.hasNext()){ 306 | newList.appendLast(new OrderedPair(null, rhsIter.next())); 307 | }else { 308 | break; 309 | } 310 | } 311 | return newList; 312 | } 313 | 314 | public String toString(){ 315 | StringBuilder sb = new StringBuilder("["); 316 | Node node = first; 317 | while(node!=null){ 318 | if(node.value==null){ 319 | sb.append("null"); 320 | }else{ 321 | sb.append(node.value.toString()+", "); 322 | } 323 | node=node.next; 324 | } 325 | sb.append("]"); 326 | return sb.toString(); 327 | } 328 | } 329 | 330 | -------------------------------------------------------------------------------- /src/Section_4/NoSpaceException.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | /** 4 | * Created by debasishc on 12/8/16. 5 | */ 6 | public class NoSpaceException extends RuntimeException{ 7 | public NoSpaceException(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Section_4/OrderedPair.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | /** 4 | * Created by debasishc on 4/10/16. 5 | */ 6 | public class OrderedPair { 7 | public E _1; 8 | public F _2; 9 | 10 | public OrderedPair(E _1, F _2) { 11 | this._1 = _1; 12 | this._2 = _2; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Section_4/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Iterator; 4 | 5 | public interface PriorityQueue{ 6 | E checkMinimum(); 7 | E dequeueMinimum(); 8 | void enqueue(E value); 9 | } 10 | -------------------------------------------------------------------------------- /src/Section_4/SortableLinkedList.java: -------------------------------------------------------------------------------- 1 | package Section_4; 2 | 3 | import java.util.Comparator; 4 | import java.util.Iterator; 5 | import java.util.NoSuchElementException; 6 | 7 | public class SortableLinkedList extends LinkedList{ 8 | public void sort(Comparator comparator){ 9 | PriorityQueue priorityQueue = new LinkedHeap(comparator); 10 | while (first!=null){ 11 | priorityQueue.enqueue(getFirst()); 12 | removeFirst(); 13 | } 14 | while (priorityQueue.checkMinimum()!=null){ 15 | appendLast(priorityQueue.dequeueMinimum()); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | SortableLinkedList anotherList = new SortableLinkedList<>(); 21 | anotherList.appendFirst(4); 22 | anotherList.appendFirst(1); 23 | anotherList.appendFirst(2); 24 | anotherList.appendFirst(3); 25 | anotherList.appendLast(8); 26 | anotherList.appendLast(7); 27 | anotherList.appendLast(1); 28 | anotherList.appendLast(2); 29 | anotherList.appendLast(3); 30 | anotherList.appendLast(18); 31 | anotherList.sort((a,b)->a-b); 32 | System.out.println(anotherList); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Section_5/AdjacencyListGraphWithDenseVertex.java: -------------------------------------------------------------------------------- 1 | package Section_5; 2 | 3 | import Section_4.DoublyLinkedList; 4 | import Section_2.LinkedList; 5 | import Section_3.BinarySearchTree; 6 | import Section_3.RedBlackTree; 7 | import Section_2.BinaryTree; 8 | 9 | public class AdjacencyListGraphWithDenseVertex implements Graph { 10 | 11 | int nextId; 12 | boolean undirected; 13 | 14 | class Edge implements Comparable{ 15 | E value; 16 | int target; 17 | 18 | DoublyLinkedList.DoublyLinkedNode targetNode; 19 | 20 | public Edge(int target) { 21 | this.target = target; 22 | } 23 | 24 | @Override 25 | public boolean equals(Object o) { 26 | if (this == o) return true; 27 | if (o == null || getClass() != o.getClass()) return false; 28 | Edge edge = (Edge) o; 29 | return target == edge.target; 30 | } 31 | 32 | @Override 33 | public int hashCode() { 34 | return target; 35 | } 36 | 37 | @Override 38 | public int compareTo(Edge o) { 39 | return target - o.target; 40 | } 41 | } 42 | 43 | class Vertex extends GraphVertex{ 44 | RedBlackTree edges = new RedBlackTree(); 45 | DoublyLinkedList neighbors = new DoublyLinkedList<>(); 46 | 47 | public Vertex(int id, V value) { 48 | super(id, value); 49 | } 50 | } 51 | 52 | public AdjacencyListGraphWithDenseVertex(boolean undirected) { 53 | this.undirected = undirected; 54 | } 55 | 56 | RedBlackTree> vertices = new RedBlackTree<>(); 57 | 58 | @Override 59 | public int addVertex() { 60 | vertices.insertValue(new Vertex(nextId++, null)); 61 | return nextId; 62 | } 63 | 64 | @Override 65 | public void removeVertex(int id) { 66 | vertices.deleteValue(new GraphVertex(id, null)); 67 | vertices.traverseDepthFirstNonRecursive((gv)->{ 68 | BinaryTree.Node edgeNode = 69 | ((Vertex) gv).edges.deleteValue(new Edge(id)); 70 | if(edgeNode!=null){ 71 | Edge edge = edgeNode.getValue(); 72 | ((Vertex) gv).neighbors.removeNode(edge.targetNode); 73 | } 74 | }, 75 | BinaryTree.DepthFirstTraversalType.INORDER); 76 | } 77 | 78 | @Override 79 | public void addEdge(int source, int target) { 80 | BinaryTree.Node> sNode =vertices.searchValue(new GraphVertex(source, null)); 81 | BinaryTree.Node> tNode =vertices.searchValue(new GraphVertex(target, null)); 82 | if(sNode == null){ 83 | throw new IllegalArgumentException("Vertex ID "+source+" does not exist"); 84 | }else if(tNode == null){ 85 | throw new IllegalArgumentException("Vertex ID "+target+" does not exist"); 86 | }else{ 87 | Vertex sVertex = (Vertex) sNode.getValue(); 88 | Vertex tVertex = (Vertex) tNode.getValue(); 89 | Edge tEdge = new Edge(target); 90 | sVertex.edges.insertValue(tEdge); 91 | tEdge.targetNode = 92 | (DoublyLinkedList.DoublyLinkedNode) sVertex.neighbors 93 | .appendLast(tVertex.getId()); 94 | if(undirected) { 95 | Edge sEdge = new Edge(source); 96 | tVertex.edges.insertValue(sEdge); 97 | sEdge.targetNode = 98 | (DoublyLinkedList.DoublyLinkedNode) tVertex.neighbors 99 | .appendLast(sVertex.getId()); 100 | } 101 | } 102 | } 103 | 104 | @Override 105 | public void removeEdge(int source, int target) { 106 | BinaryTree.Node> sNode =vertices.searchValue(new GraphVertex(source, null)); 107 | BinaryTree.Node> tNode =vertices.searchValue(new GraphVertex(target, null)); 108 | if(sNode == null){ 109 | throw new IllegalArgumentException("Vertex ID "+source+" does not exist"); 110 | }else if(tNode == null){ 111 | throw new IllegalArgumentException("Vertex ID "+target+" does not exist"); 112 | }else{ 113 | Vertex sVertex = (Vertex) sNode.getValue(); 114 | Edge deletedEdge = sVertex.edges.deleteValue(new Edge(target)).getValue(); 115 | sVertex.neighbors.removeNode(deletedEdge.targetNode); 116 | if(undirected) { 117 | Vertex tVertex = (Vertex) tNode.getValue(); 118 | deletedEdge = tVertex.edges.deleteValue(new Edge(source)).getValue(); 119 | tVertex.neighbors.removeNode(deletedEdge.targetNode); 120 | } 121 | } 122 | } 123 | 124 | @Override 125 | public boolean isAdjacent(int source, int target) { 126 | BinaryTree.Node> sNode =vertices.searchValue(new GraphVertex(source, null)); 127 | BinaryTree.Node> tNode =vertices.searchValue(new GraphVertex(target, null)); 128 | if(sNode == null){ 129 | throw new IllegalArgumentException("Vertex ID "+source+" does not exist"); 130 | }else if(tNode == null){ 131 | throw new IllegalArgumentException("Vertex ID "+target+" does not exist"); 132 | }else{ 133 | Vertex sVertex = (Vertex) sNode.getValue(); 134 | return sVertex.edges.searchValue(new Edge(target)) != null; 135 | } 136 | } 137 | 138 | @Override 139 | public DoublyLinkedList getNeighbors(int source) { 140 | BinaryTree.Node> sNode =vertices.searchValue(new GraphVertex(source, null)); 141 | if(sNode == null){ 142 | throw new IllegalArgumentException("Vertex ID "+source+" does not exist"); 143 | }else{ 144 | Vertex sVertex = (Vertex) sNode.getValue(); 145 | return sVertex.neighbors; 146 | } 147 | } 148 | 149 | @Override 150 | public void setVertexValue(int vertex, V value) { 151 | BinaryTree.Node> sNode = 152 | vertices.searchValue( 153 | new GraphVertex(vertex, null)); 154 | if(sNode == null){ 155 | throw new IllegalArgumentException("Vertex ID "+vertex+" does not exist"); 156 | }else{ 157 | Vertex sVertex = (Vertex) sNode.getValue(); 158 | sVertex.setValue(value); 159 | } 160 | } 161 | 162 | @Override 163 | public V getVertexValue(int vertex) { 164 | BinaryTree.Node> sNode = 165 | vertices.searchValue( 166 | new GraphVertex(vertex, null)); 167 | if(sNode == null){ 168 | throw new IllegalArgumentException("Vertex ID "+vertex+" does not exist"); 169 | }else{ 170 | Vertex sVertex = (Vertex) sNode.getValue(); 171 | return sVertex.getValue(); 172 | } 173 | } 174 | 175 | @Override 176 | public void setEdgeValue(int source, int target, E value) { 177 | BinaryTree.Node> sNode =vertices.searchValue(new GraphVertex(source, null)); 178 | BinaryTree.Node> tNode =vertices.searchValue(new GraphVertex(target, null)); 179 | if(sNode == null){ 180 | throw new IllegalArgumentException("Vertex ID "+source+" does not exist"); 181 | }else if(tNode == null){ 182 | throw new IllegalArgumentException("Vertex ID "+target+" does not exist"); 183 | }else{ 184 | Vertex sVertex = (Vertex) sNode.getValue(); 185 | BinaryTree.Node edgeNode =sVertex.edges.searchValue(new Edge(target)); 186 | if(edgeNode!=null) { 187 | edgeNode.getValue().value = value; 188 | if (undirected) { 189 | Vertex tVertex = (Vertex) tNode.getValue(); 190 | edgeNode = tVertex.edges.searchValue(new Edge(source)); 191 | edgeNode.getValue().value = value; 192 | } 193 | }else{ 194 | throw new IllegalArgumentException("No edge exists between the vertices "+ source + " and " + target); 195 | } 196 | } 197 | } 198 | 199 | @Override 200 | public E getEdgeValue(int source, int target) { 201 | BinaryTree.Node> sNode =vertices.searchValue(new GraphVertex(source, null)); 202 | BinaryTree.Node> tNode =vertices.searchValue(new GraphVertex(target, null)); 203 | if(sNode == null){ 204 | throw new IllegalArgumentException("Vertex ID "+source+" does not exist"); 205 | }else if(tNode == null){ 206 | throw new IllegalArgumentException("Vertex ID "+target+" does not exist"); 207 | }else{ 208 | Vertex sVertex = (Vertex) sNode.getValue(); 209 | BinaryTree.Node edgeNode = 210 | sVertex.edges.searchValue(new Edge(target)); 211 | if(edgeNode!=null) { 212 | return edgeNode.getValue().value; 213 | }else{ 214 | throw new IllegalArgumentException("No edge exists between the vertices "+ source + " and " + target); 215 | } 216 | } 217 | } 218 | 219 | @Override 220 | public boolean isUndirected() { 221 | return undirected; 222 | } 223 | 224 | @Override 225 | public BinarySearchTree getAllVertices() { 226 | BinarySearchTree allVertices = new RedBlackTree<>(); 227 | vertices.traverseDepthFirstNonRecursive((v) -> allVertices.insertValue(v.getId()), 228 | BinaryTree.DepthFirstTraversalType.PREORDER); 229 | return allVertices; 230 | } 231 | 232 | @Override 233 | public int maxVertexID() { 234 | return nextId -1; 235 | } 236 | 237 | public static void main(String [] args){ 238 | AdjacencyListGraphWithDenseVertex graph = 239 | new AdjacencyListGraphWithDenseVertex<>(true); 240 | for(int i=0;i<10;i++){ 241 | graph.addVertex(); 242 | } 243 | graph.addEdge(0,1); graph.setEdgeValue(0,1, 1); 244 | graph.addEdge(1,2); graph.setEdgeValue(1,2, 2); 245 | graph.addEdge(1,3); graph.setEdgeValue(1,3, 0); 246 | graph.addEdge(2,3); graph.setEdgeValue(2,3, 3); 247 | graph.addEdge(2,4); graph.setEdgeValue(2,4, 1); 248 | graph.addEdge(3,4); graph.setEdgeValue(3,4, 2); 249 | 250 | System.out.println(graph.isAdjacent(2,1)); 251 | System.out.println(graph.isAdjacent(2,5)); 252 | graph.getNeighbors(1).forEach(System.out::println); 253 | 254 | graph.removeVertex(1); 255 | System.out.println(graph.isAdjacent(3,2)); 256 | System.out.println(graph.isAdjacent(2,5)); 257 | graph.getNeighbors(2).forEach(System.out::println); 258 | 259 | graph.removeVertex(3); 260 | graph.getNeighbors(2).forEach(System.out::println); 261 | } 262 | } -------------------------------------------------------------------------------- /src/Section_5/AdjacencyListGraphWithSparseVertex.java: -------------------------------------------------------------------------------- 1 | package Section_5; 2 | 3 | import Section_4.DoublyLinkedList; 4 | import Section_2.LinkedList; 5 | import Section_3.BinarySearchTree; 6 | import Section_3.RedBlackTree; 7 | import Section_2.BinaryTree; 8 | 9 | public class AdjacencyListGraphWithSparseVertex implements Graph { 10 | boolean undirected; 11 | 12 | public AdjacencyListGraphWithSparseVertex(boolean undirected) { 13 | this.undirected = undirected; 14 | } 15 | 16 | class Edge implements Comparable{ 17 | E value; 18 | int target; 19 | DoublyLinkedList.DoublyLinkedNode targetNode; 20 | 21 | public Edge(int target) { 22 | this.target = target; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object o) { 27 | if (this == o) return true; 28 | if (o == null || getClass() != o.getClass()) return false; 29 | 30 | Edge edge = (Edge) o; 31 | 32 | return target == edge.target; 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | return target; 38 | } 39 | 40 | @Override 41 | public int compareTo(Edge o) { 42 | return target - o.target; 43 | } 44 | } 45 | 46 | class Vertex extends GraphVertex{ 47 | RedBlackTree edges=new RedBlackTree<>(); 48 | DoublyLinkedList neighbors=new DoublyLinkedList<>(); 49 | 50 | public Vertex(int id, V value) { 51 | super(id, value); 52 | } 53 | } 54 | 55 | Object[] vertices = new Object[0]; 56 | 57 | @Override 58 | public int addVertex() { 59 | Object[] newVertices = new Object[vertices.length+1]; 60 | System.arraycopy(vertices, 0, newVertices, 0, vertices.length); 61 | newVertices[vertices.length] = new Vertex(vertices.length, null); 62 | vertices=newVertices; 63 | return newVertices.length-1; 64 | } 65 | 66 | @Override 67 | public void removeVertex(int id) { 68 | Vertex sVertex = (Vertex) vertices[id]; 69 | if(sVertex==null){ 70 | throw new IllegalArgumentException("Vertex "+ id +" does not exist"); 71 | } 72 | DoublyLinkedList neighbors = getNeighbors(id); 73 | Edge dummyEdgeForId = new Edge(id); 74 | for(int t:neighbors){ 75 | Edge e = ((Vertex)vertices[t]).edges.deleteValue(dummyEdgeForId).getValue(); 76 | ((Vertex)vertices[t]).neighbors.removeNode(e.targetNode); 77 | } 78 | vertices[id] = null; 79 | } 80 | 81 | @Override 82 | public void addEdge(int source, int target) { 83 | Vertex sVertex = (Vertex) vertices[source]; 84 | Edge sEdge = sVertex.edges.insertValue(new Edge(target)).getValue(); 85 | sEdge.targetNode = 86 | (DoublyLinkedList.DoublyLinkedNode) sVertex.neighbors.appendLast(sEdge.target); 87 | if(undirected){ 88 | Vertex tVertex = (Vertex) vertices[target]; 89 | Edge tEdge = tVertex.edges.insertValue(new Edge(source)).getValue(); 90 | tEdge.targetNode = 91 | (DoublyLinkedList.DoublyLinkedNode) tVertex.neighbors.appendLast(tEdge.target); 92 | } 93 | } 94 | 95 | @Override 96 | public void removeEdge(int source, int target) { 97 | Vertex sVertex = (Vertex) vertices[source]; 98 | Edge deletedEdge = sVertex.edges.deleteValue(new Edge(target)).getValue(); 99 | sVertex.neighbors.removeNode(deletedEdge.targetNode); 100 | if(undirected){ 101 | Vertex tVertex = (Vertex) vertices[target]; 102 | deletedEdge = tVertex.edges.deleteValue(new Edge(source)).getValue(); 103 | tVertex.neighbors.removeNode(deletedEdge.targetNode); 104 | } 105 | } 106 | 107 | @Override 108 | public boolean isAdjacent(int source, int target) { 109 | Vertex sVertex = (Vertex) vertices[source]; 110 | return sVertex.edges.searchValue(new Edge(target))!=null; 111 | } 112 | 113 | @Override 114 | public DoublyLinkedList getNeighbors(int source) { 115 | Vertex sVertex = (Vertex) vertices[source]; 116 | return sVertex.neighbors; 117 | } 118 | 119 | @Override 120 | public void setVertexValue(int vertex, V value) { 121 | Vertex sVertex = (Vertex) vertices[vertex]; 122 | if(sVertex==null){ 123 | throw new IllegalArgumentException("Vertex "+ vertex + "does not exist"); 124 | }else{ 125 | sVertex.setValue(value); 126 | } 127 | } 128 | 129 | @Override 130 | public V getVertexValue(int vertex) { 131 | Vertex sVertex = (Vertex) vertices[vertex]; 132 | if(sVertex==null){ 133 | throw new IllegalArgumentException("Vertex "+ vertex + "does not exist"); 134 | }else{ 135 | return sVertex.getValue(); 136 | } 137 | } 138 | 139 | @Override 140 | public void setEdgeValue(int source, int target, E value) { 141 | Vertex sVertex = (Vertex) vertices[source]; 142 | Vertex tVertex = (Vertex) vertices[target]; 143 | if(sVertex==null){ 144 | throw new IllegalArgumentException("Vertex "+ source + "does not exist"); 145 | }else if(tVertex==null){ 146 | throw new IllegalArgumentException("Vertex "+ target + "does not exist"); 147 | }else{ 148 | BinaryTree.Node node = 149 | sVertex.edges.searchValue(new Edge(target)); 150 | if(node==null){ 151 | throw new IllegalArgumentException("Edge between "+ source + "and" 152 | + target + "does not exist"); 153 | }else{ 154 | node.getValue().value = value; 155 | } 156 | } 157 | } 158 | 159 | @Override 160 | public E getEdgeValue(int source, int target) { 161 | Vertex sVertex = (Vertex) vertices[source]; 162 | Vertex tVertex = (Vertex) vertices[target]; 163 | if(sVertex==null){ 164 | throw new IllegalArgumentException("Vertex "+ source + "does not exist"); 165 | }else if(tVertex==null){ 166 | throw new IllegalArgumentException("Vertex "+ target + "does not exist"); 167 | }else{ 168 | BinaryTree.Node node = 169 | sVertex.edges.searchValue(new Edge(target)); 170 | if(node==null){ 171 | throw new IllegalArgumentException("Edge between "+ source + "and" 172 | + target + "does not exist"); 173 | }else{ 174 | return node.getValue().value; 175 | } 176 | } 177 | } 178 | 179 | @Override 180 | public boolean isUndirected() { 181 | return undirected; 182 | } 183 | 184 | @Override 185 | public BinarySearchTree getAllVertices() { 186 | BinarySearchTree allVertices = new RedBlackTree<>(); 187 | for(int i=0;i graph = 202 | new AdjacencyListGraphWithSparseVertex<>(true); 203 | for(int i=0;i<10;i++){ 204 | graph.addVertex(); 205 | } 206 | graph.addEdge(0,1); 207 | graph.addEdge(1,2); 208 | graph.addEdge(1,3); 209 | graph.addEdge(2,3); 210 | graph.addEdge(2,4); 211 | graph.addEdge(3,4); 212 | 213 | System.out.println(graph.isAdjacent(2,1)); 214 | System.out.println(graph.isAdjacent(2,5)); 215 | graph.getNeighbors(1).forEach(System.out::println); 216 | 217 | graph.removeVertex(1); 218 | System.out.println(graph.isAdjacent(3,2)); 219 | 220 | System.out.println(graph.isAdjacent(2,5)); 221 | graph.getNeighbors(2).forEach(System.out::println); 222 | 223 | graph.removeVertex(3); 224 | graph.getNeighbors(2).forEach(System.out::println); 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/Section_5/AdjacencyMatrixGraphWithDenseVertex.java: -------------------------------------------------------------------------------- 1 | package Section_5; 2 | 3 | import Section_2.LinkedList; 4 | import Section_3.BinarySearchTree; 5 | import Section_3.RedBlackTree; 6 | import Section_4.DoublyLinkedList; 7 | import Section_2.BinaryTree; 8 | 9 | public class AdjacencyMatrixGraphWithDenseVertex implements Graph { 10 | 11 | class Vertex extends GraphVertex{ 12 | int internalIndex; 13 | 14 | public Vertex(int id, V value, int internalIndex) { 15 | super(id, value); 16 | this.internalIndex = internalIndex; 17 | } 18 | 19 | public int getInternalIndex() { 20 | return internalIndex; 21 | } 22 | 23 | public void setInternalIndex(int internalIndex) { 24 | this.internalIndex = internalIndex; 25 | } 26 | } 27 | 28 | private static class NullValue{}; 29 | 30 | private int nextId; 31 | 32 | private NullValue nullEdge = new NullValue(); 33 | Object [][] adjacencyMatrix = new Object[0][]; 34 | RedBlackTree> vertices = new RedBlackTree<>(); 35 | boolean undirected; 36 | 37 | public AdjacencyMatrixGraphWithDenseVertex(boolean undirected){ 38 | this.undirected = undirected; 39 | } 40 | 41 | @Override 42 | public int addVertex() { 43 | int id = nextId++; 44 | int numVertices = adjacencyMatrix.length; 45 | Object [][] newAdjacencyMatrix = new Object[numVertices+1][]; 46 | for(int i=0;i> node =vertices.searchValue(new GraphVertex(id, null)); 61 | if(node!=null){ 62 | int internalId = ((Vertex)(node.getValue())).getInternalIndex(); 63 | int numVertices = adjacencyMatrix.length; 64 | Object [][] newAdjacencyMatrix = new Object[numVertices-1][]; 65 | for(int i=0;i{ 77 | if(((Vertex)gv).getInternalIndex()>internalId) 78 | ((Vertex)gv).setInternalIndex(((Vertex)gv).getInternalIndex()-1); 79 | }, BinaryTree.DepthFirstTraversalType.PREORDER); 80 | vertices.deleteValue(new GraphVertex<>(id, null)); 81 | }else{ 82 | throw new IllegalArgumentException("Vertex with id "+id+" does not exist"); 83 | } 84 | } 85 | 86 | @Override 87 | public void addEdge(int source, int target) { 88 | BinaryTree.Node> sNode = vertices.searchValue( 89 | new GraphVertex(source, null)); 90 | BinaryTree.Node> tNode = vertices.searchValue( 91 | new GraphVertex(target, null)); 92 | if(sNode!=null && tNode!=null) { 93 | int s = ((Vertex)(sNode.getValue())).getInternalIndex(); 94 | int t = ((Vertex)(tNode.getValue())).getInternalIndex(); 95 | if(adjacencyMatrix[s][t] == null){ 96 | adjacencyMatrix[s][t] = nullEdge; 97 | if(undirected){ 98 | adjacencyMatrix[t][s] = nullEdge; 99 | } 100 | }else{ 101 | throw new IllegalArgumentException("Edge already exists"); 102 | } 103 | }else{ 104 | throw new IllegalArgumentException("Non-existent ID"); 105 | } 106 | } 107 | 108 | @Override 109 | public void removeEdge(int source, int target) { 110 | BinaryTree.Node> sNode = vertices.searchValue( 111 | new GraphVertex(source, null)); 112 | BinaryTree.Node> tNode = vertices.searchValue( 113 | new GraphVertex(target, null)); 114 | if(sNode!=null && tNode!=null) { 115 | int s = ((Vertex)(sNode.getValue())).getInternalIndex(); 116 | int t = ((Vertex)(tNode.getValue())).getInternalIndex(); 117 | adjacencyMatrix[s][t] = null; 118 | }else{ 119 | throw new IllegalArgumentException("Non-existent ID"); 120 | } 121 | } 122 | 123 | @Override 124 | public boolean isAdjacent(int source, int target) { 125 | BinaryTree.Node> sNode = vertices.searchValue( 126 | new GraphVertex(source, null)); 127 | BinaryTree.Node> tNode = vertices.searchValue( 128 | new GraphVertex(target, null)); 129 | if(sNode!=null && tNode!=null) { 130 | int s = ((Vertex)(sNode.getValue())).getInternalIndex(); 131 | int t = ((Vertex)(tNode.getValue())).getInternalIndex(); 132 | return adjacencyMatrix[s][t] != null; 133 | }else{ 134 | throw new IllegalArgumentException("Non-existent ID"); 135 | } 136 | } 137 | 138 | @Override 139 | public DoublyLinkedList getNeighbors(int source) { 140 | BinaryTree.Node> node = 141 | vertices.searchValue( 142 | new GraphVertex(source, null)); 143 | if(node!=null){ 144 | DoublyLinkedList neighborsList = new DoublyLinkedList<>(); 145 | int sourceInternalIndex = ((Vertex) node.getValue()).getInternalIndex(); 146 | vertices.traverseDepthFirstNonRecursive((gv)->{ 147 | int targetInternalIndex = ((Vertex) gv).getInternalIndex(); 148 | if(adjacencyMatrix[sourceInternalIndex][targetInternalIndex]!=null) 149 | neighborsList.appendLast(gv.getId()); 150 | }, BinaryTree.DepthFirstTraversalType.INORDER); 151 | return neighborsList; 152 | }else{ 153 | throw new IllegalArgumentException("Vertex with id "+source+" does not exist"); 154 | } 155 | } 156 | 157 | @Override 158 | public void setVertexValue(int vertex, V value) { 159 | BinaryTree.Node> node = 160 | vertices.searchValue( 161 | new GraphVertex(vertex, null)); 162 | if(node!=null){ 163 | node.getValue().setValue(value); 164 | }else{ 165 | throw new IllegalArgumentException("Vertex with id "+vertex+" does not exist"); 166 | } 167 | } 168 | 169 | @Override 170 | public V getVertexValue(int vertex) { 171 | BinaryTree.Node> node = 172 | vertices.searchValue( 173 | new GraphVertex(vertex, null)); 174 | if(node!=null){ 175 | return node.getValue().getValue(); 176 | }else{ 177 | throw new IllegalArgumentException("Vertex with id "+vertex+" does not exist"); 178 | } 179 | } 180 | 181 | @Override 182 | public void setEdgeValue(int source, int target, E value) { 183 | BinaryTree.Node> sNode = vertices.searchValue( 184 | new GraphVertex(source, null)); 185 | BinaryTree.Node> tNode = vertices.searchValue( 186 | new GraphVertex(target, null)); 187 | if(sNode!=null && tNode!=null) { 188 | int s = ((Vertex)(sNode.getValue())).getInternalIndex(); 189 | int t = ((Vertex)(tNode.getValue())).getInternalIndex(); 190 | adjacencyMatrix[s][t] = value; 191 | if (undirected) { 192 | adjacencyMatrix[t][s] = value; 193 | } 194 | }else{ 195 | throw new IllegalArgumentException("Non-existent ID"); 196 | } 197 | } 198 | 199 | @Override 200 | public E getEdgeValue(int source, int target) { 201 | BinaryTree.Node> sNode = vertices.searchValue( 202 | new GraphVertex(source, null)); 203 | BinaryTree.Node> tNode = vertices.searchValue( 204 | new GraphVertex(target, null)); 205 | if(sNode!=null && tNode!=null) { 206 | int s = ((Vertex)(sNode.getValue())).getInternalIndex(); 207 | int t = ((Vertex)(tNode.getValue())).getInternalIndex(); 208 | return (E) adjacencyMatrix[s][t]; 209 | }else{ 210 | throw new IllegalArgumentException("Non-existent ID"); 211 | } 212 | } 213 | 214 | @Override 215 | public boolean isUndirected() { 216 | return undirected; 217 | } 218 | 219 | @Override 220 | public BinarySearchTree getAllVertices() { 221 | BinarySearchTree allVertices = new RedBlackTree<>(); 222 | vertices.traverseDepthFirstNonRecursive((v) -> allVertices.insertValue(v.getId()), 223 | BinaryTree.DepthFirstTraversalType.PREORDER); 224 | return allVertices; 225 | } 226 | 227 | @Override 228 | public int maxVertexID() { 229 | return nextId-1; 230 | } 231 | 232 | public static void main(String[] args) { 233 | AdjacencyMatrixGraphWithDenseVertex graph = 234 | new AdjacencyMatrixGraphWithDenseVertex<>(true); 235 | for(int i=0;i<10;i++){ 236 | graph.addVertex(); 237 | } 238 | graph.addEdge(0,1); 239 | graph.addEdge(1,2); 240 | graph.addEdge(1,3); 241 | graph.addEdge(2,3); 242 | graph.addEdge(2,4); 243 | graph.addEdge(3,4); 244 | 245 | System.out.println(graph.isAdjacent(2,1)); 246 | System.out.println(graph.isAdjacent(2,5)); 247 | graph.getNeighbors(1).forEach(System.out::println); 248 | 249 | graph.removeVertex(1); 250 | System.out.println(graph.isAdjacent(3,2)); 251 | 252 | System.out.println(graph.isAdjacent(2,5)); 253 | graph.getNeighbors(2).forEach(System.out::println); 254 | 255 | graph.removeVertex(3); 256 | graph.getNeighbors(2).forEach(System.out::println); 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/Section_5/AdjacencyMatrixGraphWithSparseVertex.java: -------------------------------------------------------------------------------- 1 | package Section_5; 2 | 3 | import Section_2.LinkedList; 4 | import Section_3.BinarySearchTree; 5 | import Section_3.RedBlackTree; 6 | import Section_4.DoublyLinkedList; 7 | 8 | public class AdjacencyMatrixGraphWithSparseVertex implements Graph { 9 | private static class NullEdgeValue{}; 10 | 11 | private NullEdgeValue nullEdge = new NullEdgeValue(); 12 | private NullEdgeValue nullVertex = new NullEdgeValue(); 13 | 14 | Object [][] adjacencyMatrix = new Object[0][]; 15 | Object[] vertexValues = new Object[0]; 16 | boolean undirected; 17 | 18 | public AdjacencyMatrixGraphWithSparseVertex(boolean undirected){ 19 | this.undirected = undirected; 20 | } 21 | 22 | @Override 23 | public int addVertex() { 24 | int numVertices = adjacencyMatrix.length; 25 | Object [][] newAdjacencyMatrix = new Object[numVertices+1][]; 26 | for(int i=0;i getNeighbors(int source) { 76 | DoublyLinkedList neighborList = new DoublyLinkedList<>(); 77 | for(int i=0;i getAllVertices() { 122 | BinarySearchTree allVertices = new RedBlackTree<>(); 123 | for(int i=0;igraph = new AdjacencyMatrixGraphWithSparseVertex<>(true); 138 | for(int i=0;i<10;i++){ 139 | graph.addVertex(); 140 | } 141 | graph.addEdge(0,1); 142 | graph.addEdge(1,2); 143 | graph.addEdge(1,3); 144 | graph.addEdge(2,3); 145 | graph.addEdge(2,4); 146 | graph.addEdge(3,4); 147 | 148 | System.out.println(graph.isAdjacent(2,1)); 149 | System.out.println(graph.isAdjacent(2,5)); 150 | graph.getNeighbors(1).forEach(System.out::println); 151 | 152 | graph.removeVertex(1); 153 | System.out.println(graph.isAdjacent(3,2)); 154 | 155 | System.out.println(graph.isAdjacent(2,5)); 156 | graph.getNeighbors(2).forEach(System.out::println); 157 | 158 | graph.removeVertex(3); 159 | graph.getNeighbors(2).forEach(System.out::println); 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/Section_5/Graph.java: -------------------------------------------------------------------------------- 1 | package Section_5; 2 | 3 | import Section_2.LinkedList; 4 | import Section_2.QueueImplLinkedList; 5 | import Section_2.StackImplLinkedList; 6 | import Section_1.OneArgumentExpression; 7 | import Section_3.BinarySearchTree; 8 | import Section_3.RedBlackTree; 9 | import Section_2.BinaryTree; 10 | import Section_4.DoublyLinkedList; 11 | import Section_4.LinkedHeap; 12 | 13 | public interface Graph { 14 | int addVertex(); 15 | void removeVertex(int id); 16 | void addEdge(int source, int target); 17 | void removeEdge(int source, int target); 18 | boolean isAdjacent(int source, int target); 19 | DoublyLinkedList getNeighbors(int source); 20 | void setVertexValue(int vertex, V value); 21 | V getVertexValue(int vertex); 22 | void setEdgeValue(int source, int target, E value); 23 | E getEdgeValue(int source, int target); 24 | boolean isUndirected(); 25 | BinarySearchTree getAllVertices(); 26 | int maxVertexID(); 27 | } -------------------------------------------------------------------------------- /src/Section_5/GraphVertex.java: -------------------------------------------------------------------------------- 1 | package Section_5; 2 | 3 | /** 4 | * Created by debasishc on 20/12/16. 5 | */ 6 | public class GraphVertex implements Comparable>{ 7 | int id; 8 | V value; 9 | 10 | public GraphVertex(int id, V value) { 11 | this.id = id; 12 | this.value = value; 13 | } 14 | 15 | public int getId() { 16 | return id; 17 | } 18 | 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | 23 | public V getValue() { 24 | return value; 25 | } 26 | 27 | public void setValue(V value) { 28 | this.value = value; 29 | } 30 | 31 | @Override 32 | public boolean equals(Object o) { 33 | if (this == o) return true; 34 | if (o == null || getClass() != o.getClass()) return false; 35 | 36 | GraphVertex that = (GraphVertex) o; 37 | 38 | return id == that.id; 39 | 40 | } 41 | 42 | @Override 43 | public int hashCode() { 44 | return id; 45 | } 46 | 47 | 48 | @Override 49 | public int compareTo(GraphVertex o) { 50 | return id - o.id; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Section_6/ArraySearcher.java: -------------------------------------------------------------------------------- 1 | package Section_6; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArraySearcher { 6 | static String[] students = 7 | new String[]{"Tom", "Harry", "Merry", "Aisha", 8 | "Abdullah"}; 9 | static int[] marks = new int[]{63, 70, 65, 85, 72}; 10 | 11 | public static int linearSearch(E[] values, 12 | F valueToLookup) { 13 | for (int i = 0; i < values.length; i++) { 14 | if (values[i].equals(valueToLookup)) { 15 | return i; 16 | } 17 | } 18 | return -1; 19 | } 20 | 21 | private static , F extends E> int binarySearch( 22 | E[] sortedValues, F valueToSearch, int start, int end) { 23 | if(start>=end){ 24 | return -1; 25 | } 26 | int midIndex = (end+start)/2; 27 | int comparison = sortedValues[midIndex].compareTo(valueToSearch); 28 | if(comparison==0){ 29 | return midIndex; 30 | }else if(comparison>0){ 31 | return binarySearch(sortedValues, valueToSearch, start, midIndex); 32 | }else{ 33 | return binarySearch(sortedValues, valueToSearch, midIndex+1, end); 34 | } 35 | } 36 | 37 | private static , F extends E> int binarySearchNonRecursive( 38 | E[] sortedValues, F valueToSearch, int start, int end) { 39 | while(true) { 40 | if (start >= end) { 41 | return -1; 42 | } 43 | int midIndex = (end + start) / 2; 44 | int comparison = 45 | sortedValues[midIndex].compareTo(valueToSearch); 46 | if (comparison == 0) { 47 | return midIndex; 48 | } else if (comparison > 0) { 49 | end = midIndex; 50 | } else { 51 | start = midIndex + 1; 52 | } 53 | } 54 | } 55 | 56 | public static , F extends E> int binarySearch( 57 | E[] sortedValues, F valueToSearch) { 58 | return binarySearch(sortedValues, valueToSearch, 0, sortedValues.length); 59 | } 60 | 61 | public static Integer marksForName(String name) { 62 | int index = linearSearch(students, name); 63 | if (index >= 0) { 64 | return marks[index]; 65 | } else { 66 | return null; 67 | } 68 | } 69 | 70 | public static void main(String[] args) { 71 | Integer[] integers = 72 | new Integer[]{232, 54, 1, 213, 654, 23, 6, 72, 21}; 73 | System.out.println(linearSearch(integers, 5)); 74 | System.out.println(linearSearch(integers, 23)); 75 | Arrays.sort(integers); 76 | System.out.println(binarySearch(integers, 54)); 77 | System.out.println(binarySearch(integers, 54, 0, integers.length)); 78 | System.out.println(marksForName("Merry")); 79 | 80 | // //lets generate a random sorted array of integers. 81 | // int arraySize = 100000000; 82 | // Long array[] = new Long[arraySize]; 83 | // array[0] = (long)(Math.random()*100); 84 | // for(int i=1;ia-b); 51 | 52 | ProducerConsumerQueue queue = new ProducerConsumerQueue<>(4092, 2, (v)->{ 53 | int pos = ArraySearcher.binarySearch(keys,v); 54 | if(pos<0){ 55 | return; 56 | } 57 | values[pos].incrementAndGet(); 58 | }); 59 | 60 | FileReader edgeListFileReader = new FileReader(EDGES_PATH); 61 | while(true){ 62 | int val = edgeListFileReader.readIntFromText(); 63 | if(val == 0){ 64 | break; 65 | } 66 | queue.produce(val); 67 | } 68 | 69 | queue.markCompleted(); 70 | queue.joinThreads(); 71 | 72 | PrintStream out = new PrintStream(OUTPUT_FILE_PATH); 73 | for(int i=0;i { 7 | R compute(A a) throws Exception; 8 | } 9 | -------------------------------------------------------------------------------- /src/Section_6/OneArgumentStatementWithException.java: -------------------------------------------------------------------------------- 1 | package Section_6; 2 | 3 | 4 | 5 | @FunctionalInterface 6 | public interface OneArgumentStatementWithException { 7 | void doSomething(E input) throws Exception; 8 | } 9 | -------------------------------------------------------------------------------- /src/Section_6/PerfectNumberTest.java: -------------------------------------------------------------------------------- 1 | package Section_6; 2 | 3 | import java.util.concurrent.atomic.AtomicLong; 4 | 5 | public class PerfectNumberTest { 6 | 7 | public static boolean isPerfect(long x){ 8 | long div = 2; 9 | long sum=0; 10 | while(true){ 11 | long quotient = x/div; 12 | if(quotient queue = new ProducerConsumerQueue<>(4096, 4, (x)->{ 29 | if(isPerfect(x)){ 30 | System.out.println(x); 31 | } 32 | }); 33 | 34 | for(long i=2;i<5_00_000;i++){ 35 | queue.produce(i); 36 | } 37 | queue.markCompleted(); 38 | queue.joinThreads(); 39 | System.out.println("Time in ms: "+(System.currentTimeMillis()-start)); 40 | } 41 | 42 | public static void findPerfectNumberWithSingleThread(){ 43 | long start = System.currentTimeMillis(); 44 | for(long i=2;i<5_00_000;i++){ 45 | if(isPerfect(i)){ 46 | System.out.println(i); 47 | } 48 | } 49 | System.out.println("Time in ms: "+(System.currentTimeMillis()-start)); 50 | } 51 | 52 | public static void findPerfectNumbersWithFunctionalAPI(){ 53 | long start = System.currentTimeMillis(); 54 | EventStream stream = new EventStream() { 55 | AtomicLong next = new AtomicLong(0L); 56 | @Override 57 | public Long read() { 58 | Long ret = next.incrementAndGet(); 59 | if(ret<=5_00_000L){ 60 | return ret; 61 | } 62 | return null; 63 | } 64 | }; 65 | stream.filter((x)->x>1) 66 | .filter(EventStream::isPerfect) 67 | .consume((x)->{System.out.println(x);}) 68 | .onError((x)->System.out.println(x)) 69 | .process(4096,1,4); 70 | 71 | System.out.println("Time in ms: "+(System.currentTimeMillis()-start)); 72 | } 73 | 74 | public static void main(String[] args) throws Exception{ 75 | findPerfectNumberWithProducerConsumer(); 76 | findPerfectNumberWithSingleThread(); 77 | findPerfectNumbersWithFunctionalAPI(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/Section_6/ProcessorTask.java: -------------------------------------------------------------------------------- 1 | package Section_6; 2 | 3 | public class ProcessorTask implements Task { 4 | OneArgumentStatementWithException processor; 5 | 6 | public ProcessorTask(OneArgumentStatementWithException processor) { 7 | this.processor = processor; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Section_6/ProducerConsumerQueue.java: -------------------------------------------------------------------------------- 1 | package Section_6; 2 | 3 | import java.io.File; 4 | import java.io.PrintStream; 5 | 6 | public class ProducerConsumerQueue { 7 | enum EventType{ 8 | INVOCATION,ERROR,COMPLETION 9 | } 10 | class Event{ 11 | E value; 12 | Exception error; 13 | EventType eventType; 14 | } 15 | ThreadSafeFixedLengthSpinlockQueue queue; 16 | boolean alive = true; 17 | Thread [] threads; 18 | 19 | public ProducerConsumerQueue(int bufferSize,int threadCount,Consumer consumer) { 20 | queue = new ThreadSafeFixedLengthSpinlockQueue<>(bufferSize); 21 | threads = new Thread[threadCount]; 22 | Runnable consumerCode = ()->{ 23 | try{ 24 | while(alive || queue.currentElementCount()>0){ 25 | Event e = queue.dequeue(); 26 | switch (e.eventType) { 27 | case INVOCATION: 28 | consumer.onMessage(e.value); 29 | break; 30 | case ERROR: 31 | consumer.onError(e.error); 32 | break; 33 | case COMPLETION: 34 | alive = false; 35 | consumer.onComplete(); 36 | } 37 | } 38 | queue.killDequeuers(); 39 | } catch (InterruptedException e) { 40 | } finally{ 41 | } 42 | }; 43 | for(int i=0;i { 10 | Semaphore underflowSemaphore; 11 | Semaphore overflowSemaphore; 12 | AtomicInteger nextEnqueueIndex; 13 | AtomicInteger nextDequeueIndex; 14 | 15 | E[] store; 16 | 17 | Semaphore [] enqueueLocks; 18 | Semaphore [] dequeueLocks; 19 | 20 | int length; 21 | 22 | boolean alive; 23 | 24 | public ThreadSafeFixedLengthBlockingQueue(int length){ 25 | this.length = length; 26 | store = (E[]) new Object[length]; 27 | nextEnqueueIndex = new AtomicInteger(); 28 | nextDequeueIndex = new AtomicInteger(); 29 | underflowSemaphore = new Semaphore(length); 30 | overflowSemaphore = new Semaphore(length); 31 | underflowSemaphore.acquireUninterruptibly(length); 32 | enqueueLocks = new Semaphore[length]; 33 | dequeueLocks = new Semaphore[length]; 34 | for(int i=0;i { 11 | int nextEnqueueIndex; 12 | int nextDequeueIndex; 13 | E[] store; 14 | AtomicBoolean[] enqueueLocks; 15 | AtomicBoolean[] dequeueLocks; 16 | AtomicInteger currentElementCount = new AtomicInteger(0); 17 | int length; 18 | volatile boolean alive = true; 19 | 20 | public ThreadSafeFixedLengthSpinlockQueue(int length){ 21 | this.length = length; 22 | store = (E[]) new Object[length]; 23 | enqueueLocks = new AtomicBoolean[length]; 24 | dequeueLocks = new AtomicBoolean[length]; 25 | for(int i=0;i=halfLength || (!currentElementCount.compareAndSet(numberOfElements, numberOfElements+1))){ 75 | enqueueLocks[index].set(false); 76 | continue; 77 | } 78 | store[index] = value; 79 | dequeueLocks[index].set(false); 80 | return; 81 | } 82 | } 83 | } 84 | 85 | public static void main(String[] args) throws Exception{ 86 | final ThreadSafeFixedLengthSpinlockQueue queue = new ThreadSafeFixedLengthSpinlockQueue<>(32); 87 | PrintStream out = new PrintStream(new File("E:\\\\Workspace\\\\Advanced Data Structures And Algorithms In Java 9\\\\src\\\\Section_6\\\\output1.txt")); 88 | long start = System.currentTimeMillis(); 89 | 90 | Runnable dequeer = ()->{ 91 | while(true) { 92 | int value = 0; 93 | try { 94 | value = queue.dequeue(); 95 | } catch (InterruptedException e) { 96 | break; 97 | } 98 | out.println(Thread.currentThread().getId() + 99 | " " + (System.currentTimeMillis()-start) +" " + value); 100 | 101 | } 102 | }; 103 | 104 | Runnable dequeer2 = ()->{ 105 | while(true) { 106 | int value = 0; 107 | try { 108 | value = queue.dequeue(); 109 | if(value>5) 110 | queue.enqueue(value/2); 111 | } catch (InterruptedException e) { 112 | break; 113 | } 114 | out.println(Thread.currentThread().getId() + 115 | " " + (System.currentTimeMillis()-start) +" " + value); 116 | } 117 | }; 118 | 119 | Runnable enqueer = ()->{ 120 | for(int i=0;i<10000;i++) { 121 | try { 122 | queue.enqueueProducerOnly(16); 123 | } catch (InterruptedException e) { 124 | e.printStackTrace(); 125 | } 126 | } 127 | while (queue.currentElementCount()>0); 128 | queue.killDequeuers(); 129 | }; 130 | 131 | for(int i=0;i<2;i++){ 132 | new Thread(enqueer).start(); 133 | } 134 | for(int i=0;i<10;i++){ 135 | new Thread(dequeer2).start(); 136 | } 137 | new Thread(dequeer2).start(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/Section_6/output.txt: -------------------------------------------------------------------------------- 1 | 2508972 : 0 2 | -------------------------------------------------------------------------------- /src/Section_6/ulist.txt: -------------------------------------------------------------------------------- 1 | 2508972 2 | 1081826 3 | 2022585 4 | 141678 5 | 709419 6 | 877187 7 | 1592426 8 | 1013109 9 | 1490560 10 | 623595 --------------------------------------------------------------------------------