├── .DS_Store
├── JAVA
├── Collections
│ ├── binarySearch.md
│ ├── max.md
│ ├── min.md
│ ├── reverse.md
│ ├── reverseOrder.md
│ ├── rotate.md
│ ├── shuffle.md
│ ├── sort.md
│ └── swap.md
├── Iterators.md
├── Pair
│ ├── hashing.md
│ ├── pair.md
│ ├── sorting.md
│ └── utilities.md
├── README.md
├── Strings.md
├── containers
│ ├── lists.md
│ ├── maps.md
│ ├── queues.md
│ ├── sets.md
│ └── stack.md
├── p1.JPG
├── p2.JPG
├── p3.JPG
└── p4.JPG
├── LICENSE
├── README.md
├── _config.yml
├── cpp
├── .DS_Store
├── Iterators.md
├── README.md
├── containers
│ ├── Pairs&Tuples.markdown
│ ├── Vectors.markdown
│ ├── bitsets.md
│ ├── maps.md
│ ├── queue.md
│ ├── sets.md
│ └── stacks.md
├── functions
│ ├── MaxMin.md
│ ├── binary_search.md
│ ├── is_sorted.md
│ ├── lower_bound.md
│ ├── max_element.md
│ ├── min_element.md
│ ├── next_permutation.md
│ ├── reverse.md
│ ├── set_difference.md
│ ├── set_intersection.md
│ ├── set_union.md
│ ├── sort.md
│ └── upper_bound.md
├── introduction.md
├── problems
│ ├── chefcode.cpp
│ ├── ipctrain.cpp
│ ├── kjcp01.cpp
│ ├── kjcp02.cpp
│ └── snakeeat.cpp
└── templates.md
├── problems.md
├── python
├── Readme.md
├── containers
│ ├── dictionary.md
│ ├── heapq.md
│ ├── lists.md
│ └── sets.md
└── methods
│ ├── Counters.md
│ ├── bisect.md
│ ├── itertools.md
│ └── miscellaneous.md
├── reference.md
└── template.md
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/.DS_Store
--------------------------------------------------------------------------------
/JAVA/Collections/binarySearch.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | > This function is used to search the specified object in a list using the binary search algorithm.
7 |
8 | > The method returns the index of the search key, if it is contained in the list and throws ClassCastException if the list contains elements that are not mutually comparable.
9 |
10 | ## Declaration
11 |
12 | ```java
13 | public static int binarySearch(List extends T> list,T key,Comparator super T> c)
14 | ```
15 |
16 | ## Parameters
17 | list − This is the list to be searched.
18 |
19 | key − This is the key to be searched for.
20 |
21 | c − This is the comparator by which the list is ordered. A null value indicates that the elements' natural ordering should be used. The list must be sorted into ascending order according to the specified comparator.
22 | This parameter is optional.
23 |
24 | NOTE!- One important point to keep in mind is that the elements in the Collection must be already sorted, else the results will be something unexpected.
25 |
26 | ## Example (Without Comparator)
27 |
28 | ```java
29 | import java.util.*;
30 |
31 | public class BinarySearch
32 | {
33 | public static void main(String args[])
34 | {
35 |
36 | ArrayList list = new ArrayList();
37 |
38 | list.add(30);
39 | list.add(45);
40 | list.add(100);
41 | list.add(250);
42 | list.add(500);
43 |
44 | int index = Collections.binarySearch(list,45);
45 |
46 | System.out.println("Position of 45 is "+index);
47 | }
48 | }
49 | ```
50 |
51 | ## Output
52 |
53 | ```
54 | Position of 45 is 1
55 | ```
56 |
57 | ## Example (With Comparator)
58 |
59 | ```java
60 | import java.util.*;
61 |
62 | public class BinarySearchwithComparator
63 | {
64 | public static void main(String args[])
65 | {
66 | ArrayList list = new ArrayList();
67 | list.add(500);
68 | list.add(250);
69 | list.add(100);
70 | list.add(45);
71 | list.add(30);
72 | int index = Collections.binarySearch(list, 30,
73 | Collections.reverseOrder());
74 |
75 | System.out.println("Position of 30 is " + index);
76 | }
77 | }
78 |
79 | ```
80 |
81 | ## Output
82 |
83 | ```
84 | Position of 30 is 4
85 | ```
86 |
--------------------------------------------------------------------------------
/JAVA/Collections/max.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | >It returns the maximum element of the given collection, according to the order induced by the specified comparator.
7 |
8 | >All elements in the collection must be mutually comparable by the specified comparator
9 | (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection)
10 |
11 |
12 | NOTE!- This method requires a list type of data, we need to first convert the collection to list first using aslist() function.
13 |
14 | ## Declaration
15 |
16 | ```java
17 | public static T max(Collection extends T> coll,Comparator super T> comp)
18 | ```
19 | ## Parameters
20 | coll - The collection whose maximum element is to be determined.
21 |
22 | comp - The comparator with which to determine the maximum element.
23 |
24 | If the second argument is not provided, then comparison is made based on the natural order of elements
25 | ## Example
26 |
27 | ```java
28 | import java.util.*;
29 | public class MaxExample
30 | {
31 | public static void main(String args[])
32 | {
33 | List list = new ArrayList();
34 | list.add(100);
35 | list.add(-2);
36 | list.add(86);
37 | list.add(986);
38 | list.add(112);
39 | System.out.println("The maximum value in collection is "+Collections.max(list,null));
40 | }
41 | }
42 | ```
43 |
44 | ## Output
45 |
46 | ```
47 | The maximum value in collection is 986
48 | ```
49 |
--------------------------------------------------------------------------------
/JAVA/Collections/min.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | >It returns the minimum element present in the given collection, according to the order induced by the specified comparator.
7 |
8 | >All elements in the collection must be mutually comparable by the specified comparator
9 | (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection)
10 |
11 | NOTE!- This method requires a list type of data, we need to first convert the collection to list first using aslist() function.
12 |
13 | ## Declaration
14 |
15 | ```java
16 | public static T min(Collection extends T> coll,Comparator super T> comp)
17 | ```
18 |
19 | ## Parameters
20 | coll - The collection whose minimum element is to be determined.
21 |
22 | comp - The comparator with which to determine the minimum element.
23 |
24 | If the second argument is not provided, then comparison is made based on the natural order of elements
25 |
26 | ## Example
27 |
28 | ```java
29 | import java.util.*;
30 | public class MinExample
31 | {
32 | public static void main(String args[])
33 | {
34 | List list = new ArrayList();
35 | list.add(100);
36 | list.add(-2);
37 | list.add(86);
38 | list.add(986);
39 | list.add(112);
40 | System.out.println("The minimum value in collection is "+Collections.min(list,null));
41 | }
42 | }
43 | ```
44 |
45 | ## Output
46 |
47 | ```
48 | The minimum value in collection is -2
49 | ```
50 |
--------------------------------------------------------------------------------
/JAVA/Collections/reverse.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | >It reverses the order of the elements in the specified list.
7 |
8 | This method can be used to reverse a LinkedList, ArrayList and arrays.
9 |
10 | ## Declaration
11 |
12 | ```java
13 | public static void reverse(List> list)
14 | ```
15 |
16 | ## Parameters
17 | list - The list which is to be sorted.
18 |
19 | ## Example
20 |
21 | ```java
22 | import java.util.*;
23 |
24 | public class ReverseList
25 | {
26 | public static void main(String[] args)
27 | {
28 | ArrayList letters = new ArrayList();
29 | letters.add("A");
30 | letters.add("B");
31 | letters.add("C");
32 | letters.add("D");
33 | letters.add("E");
34 |
35 | System.out.println("Before reversing: "+letters);
36 | Collections.reverse(letters);
37 | System.out.println("After reversing: "+letters);
38 | }
39 | }
40 | ```
41 |
42 | ## Output
43 |
44 | ```
45 | Before reversing: [A, B, C, D, E]
46 | After reversing: [E, D, C, B, A]
47 | ```
48 |
--------------------------------------------------------------------------------
/JAVA/Collections/reverseOrder.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | > This function returns a comparator that reverse the natural ordering imposed by Comparable.
7 |
8 | > This method along with sort() is used to sort a collection in descending order.
9 |
10 | ## Declaration
11 |
12 | ```java
13 | public static Comparator reverseOrder(Comparator cmp)
14 | ```
15 |
16 | ## Parameters
17 | cmp − This is the comparator.
18 | This parameter is optional.
19 |
20 | ## Example (Using Comparator)
21 |
22 | ```java
23 | import java.util.*;
24 | class User
25 | {
26 | String name;
27 | public User(String name)
28 | {
29 | this.name = name;
30 | }
31 | public String getName()
32 | {
33 | return name;
34 | }
35 |
36 | }
37 | public class ReverseOrderwithComparator
38 | {
39 | public static void main(String args[])
40 | {
41 | ArrayList list = new ArrayList ();
42 | list.add(new User("ABC"));
43 | list.add(new User("XYZ"));
44 | list.add(new User("PQR"));
45 | System.out.println("Sort using Comparator:");
46 | Collections.sort(list, new UserComparator());
47 | for(User u: list)
48 | {
49 | System.out.println(u.getName());
50 | }
51 | System.out.println("Reverse Order using Comparator:");
52 | Collections.sort(list, Collections.reverseOrder(new UserComparator()));
53 | for(User u: list)
54 | {
55 | System.out.println(u.getName());
56 | }
57 | }
58 | }
59 | class UserComparator implements Comparator {
60 | @Override
61 | public int compare(User u1, User u2) {
62 | return (u1.getName()).compareTo(u2.getName());
63 | }
64 | }
65 | ```
66 |
67 | ## Output
68 |
69 | ```
70 | Sort using Comparator:
71 | ABC
72 | PQR
73 | XYZ
74 | Reverse Order using Comparator:
75 | XYZ
76 | PQR
77 | ABC
78 | ```
79 |
--------------------------------------------------------------------------------
/JAVA/Collections/rotate.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | > It is used to rotate the elements present in the specified list by a given distance.
7 |
8 | > The distance can be zero, negative, or greater than size of the list.
9 |
10 | > Positive distance rotates the list to the right, negative distance rotates the list to the left while zero distance does not rotate the list.
11 |
12 | This method can be used to rotate lists and arrays.
13 |
14 | ## Declaration
15 |
16 | ```java
17 | public static void rotate(List> list,int distance)
18 | ```
19 |
20 | ## Parameters
21 | list - This is the list to be rotated.
22 |
23 | distance - This is the distance to rotate the list.
24 |
25 | ## Example
26 |
27 | ```java
28 | import java.util.*;
29 |
30 | public class RotateList
31 | {
32 | public static void main(String[] args)
33 | {
34 | List numbers = new ArrayList();
35 | for (int i = 101; i <= 110; i++)
36 | numbers.add(i);
37 | System.out.println("Before rotating: " +numbers);
38 | Collections.rotate(numbers,3);
39 | System.out.println("After rotating: " +numbers);
40 | }
41 | }
42 |
43 | ```
44 |
45 | ## Output
46 |
47 | ```
48 | Before rotating: [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
49 | After rotating: [108, 109, 110, 101, 102, 103, 104, 105, 106, 107]
50 | ```
51 |
--------------------------------------------------------------------------------
/JAVA/Collections/shuffle.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | > It is used to randomly shuffle the specified list in place using a default or specified source of randomness.
7 |
8 | ## Declaration
9 |
10 | ```java
11 | public static void shuffle(List> list,Random r)
12 | ```
13 |
14 | ## Parameters
15 | list - The list to be shuffled.
16 |
17 | r - The custom source of randomness to use to shuffle the list. This can be used to make shuffling a deterministic process if needed.
18 | When using identical sources of randomness to shuffle two same lists, both lists will contain elements in the exact same order after shuffling.
19 |
20 | When second parameter is not present, the list is shuffled using default source of randomness.
21 |
22 | ## Example (Default source of randomness)
23 |
24 | ```java
25 | import java.util.*;
26 |
27 | public class ShuffleList
28 | {
29 | public static void main(String[] args)
30 | {
31 | List num = new ArrayList();
32 | for (int i = 11; i <= 20; i++)
33 | num.add(i);
34 | System.out.println("Before shuffling: " +num);
35 | Collections.shuffle(num);
36 | System.out.println("After shuffling: " +num);
37 | }
38 | }
39 |
40 | ```
41 |
42 | ## Output
43 |
44 | ```
45 | Before shuffling: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
46 | After shuffling: [12, 20, 11, 17, 13, 19, 15, 16, 18, 14]
47 | ```
48 |
49 | ## Example (Custom source of randomness)
50 |
51 | ```java
52 | import java.util.*;
53 |
54 | public class ShuffleList
55 | {
56 | public static void main(String[] args)
57 | {
58 | List num = new ArrayList();
59 | List num_copy = new ArrayList();
60 | for (int i = 1; i <= 10; i++)
61 | {
62 | num.add(i);
63 | num_copy.add(i);
64 | }
65 | System.out.println("Before shuffling num: " +num);
66 | System.out.println("Before shuffling num_copy: " +num_copy);
67 | Collections.shuffle(num,new Random(3));
68 | Collections.shuffle(num_copy,new Random(3));
69 | System.out.println("After shuffling num: " +num);
70 | System.out.println("After shuffling num_copy: " +num_copy);
71 | }
72 | }
73 |
74 | ```
75 |
76 | ## Output
77 |
78 | ```
79 | Before shuffling num: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
80 | Before shuffling num_copy: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
81 | After shuffling num: [7, 6, 2, 4, 9, 8, 10, 1, 3, 5]
82 | After shuffling num_copy: [7, 6, 2, 4, 9, 8, 10, 1, 3, 5]
83 | ```
84 |
85 | NOTE!- This function runs in linear time
86 |
--------------------------------------------------------------------------------
/JAVA/Collections/sort.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | > It is used to sort the elements present in the specified list of Collection in ascending order using the Merge Sort technique.
7 |
8 | > It can sort the elements of ArrayList, linked list, queue and many more. It can be used to sort an array after creating an ArrayList of given array items.
9 |
10 | ## Declaration
11 |
12 | ```java
13 | public static void sort(List list,Comparator super T> c)
14 | ```
15 |
16 | ## Parameters
17 | list - This is the list to be sorted.
18 |
19 | c - This is the comparator to determine the order of the list.
20 |
21 |
22 | ## Example (Using a Comparator)
23 |
24 | ```java
25 | import java.util.*;
26 | import java.lang.*;
27 | import java.io.*;
28 |
29 | class Product
30 | {
31 | int id, weight;
32 | String name;
33 | public Product(int id, String name, int weight)
34 | {
35 | this.id = id;
36 | this.weight = weight;
37 | this.name = name;
38 | }
39 |
40 | public String toString()
41 | {
42 | return this.id + " " + this.name +
43 | " " + this.weight;
44 | }
45 | }
46 |
47 | class SortbyWeight implements Comparator
48 | {
49 | // Used for sorting in ascending order of weight
50 | public int compare(Product p1, Product p2)
51 | {
52 | return p1.weight - p2.weight;
53 | }
54 | }
55 |
56 | public class SortUsingComparator
57 | {
58 | public static void main (String args[])
59 | {
60 | ArrayList list = new ArrayList();
61 | list.add(new Product(111, "Watermelon",3));
62 | list.add(new Product(112, "Cake",2));
63 | list.add(new Product(113, "Chocolate",1));
64 |
65 | System.out.println("Unsorted");
66 | for (Product p:list)
67 | System.out.println(p);
68 |
69 | Collections.sort(list, new SortbyWeight());
70 |
71 | System.out.println("\nSorted by weight");
72 | for (Product p:list)
73 | System.out.println(p);
74 | }
75 | }
76 | ```
77 |
78 | ## Output
79 |
80 | ```
81 | Unsorted
82 | 111 Watermelon 3
83 | 112 Cake 2
84 | 113 Chocolate 1
85 |
86 | Sorted by weight
87 | 113 Chocolate 1
88 | 112 Cake 2
89 | 111 Watermelon 3
90 | ```
91 |
92 |
--------------------------------------------------------------------------------
/JAVA/Collections/swap.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## Function
5 |
6 | > It is used to swap the elements at the specified positions in the specified list.
7 |
8 | ## Declaration
9 |
10 | ```java
11 | public static void swap(List> list,int index1,int index2)
12 | ```
13 |
14 | ## Parameters
15 | list - The list in which to the swap elements.
16 |
17 | index1 - The index of first element to be swapped.
18 |
19 | index2 - The index of the other element to be swapped.
20 |
21 | If the elements with index numbers of index1 and index2 do not exist, the method throws ArrayIndexOutOfBoundsException.
22 |
23 | ## Example
24 |
25 | ```java
26 | import java.util.*;
27 | public class SwapExample
28 | {
29 | public static void main(String args[])
30 | {
31 | ArrayList list = new ArrayList();
32 | list.add(50);
33 | list.add(10);
34 | list.add(20);
35 | list.add(40);
36 | System.out.println("Before swapping: " +list);
37 | Collections.swap(list, 0,3);
38 | System.out.println("After swapping: " +list);
39 | }
40 | }
41 | ```
42 |
43 | ## Output
44 |
45 | ```
46 | Before swapping: [50, 10, 20, 40]
47 | After swapping: [40, 10, 20, 50]
48 | ```
49 |
50 |
--------------------------------------------------------------------------------
/JAVA/Iterators.md:
--------------------------------------------------------------------------------
1 | # Iterators in JAVA
2 |
3 | - ### Simple and Easy method (For-each Style)
4 | Write collection name right side of colon : in for-each loop and Collection variable in left side of colon.
5 |
6 | For example.
7 |
8 | ```java
9 |
10 | ArrayList al=new ArrayList<>(); //Collection declaration
11 |
12 | al.add(2); al.add(3); al.add(4); // populating data
13 |
14 | for(Integer x: al){
15 |
16 | System.out.println(x);
17 |
18 | }
19 |
20 | ```
21 |
22 | Output
23 | ```
24 | 2
25 |
26 | 3
27 |
28 | 4
29 | ```
30 |
31 |
32 | - ### Iterator
33 | In Java, Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a
34 |
35 | collection of objects.
36 |
37 | - It is used to traverse a collection object elements one by one.
38 | - It is available since Java 1.2 Collection Framework.
39 | - It is applicable for all Collection classes. So it is also known as Universal Java Cursor.
40 | - It supports both READ and REMOVE Operations.
41 | - Compare to Enumeration interface, Iterator method names are simple and easy to use.
42 | - In java ```Iterator``` is class and Object of this class is used to iterate over certain collections.
43 |
44 | Iterator is like pointer which points to location.
45 |
46 | In this section, we will discuss about Java Iterator methods in-brief. We will explore these methods in-depth with some useful examples
47 | in the coming section.
48 |
49 | - boolean hasNext():Returns true if the iteration has more elements.
50 | - E next(): Returns the next element in the iteration.
51 | - default void remove(): Removes from the underlying collection the last element returned by this iterator.
52 | - default void forEachRemaining(Consumer action): Performs the given action for each remaining element until all elements have been processed or the action throws an exception.
53 |
54 |
55 | Even Every Collection has ```iterator()``` method which returns reference of Iterator object which we can use to iterate over Collection.
56 |
57 | Iterator object has .next() method which returns next element of collection and increments pointer.
58 |
59 | hasNext() method which returns boolean value which represents existence of next element in collection.
60 |
61 | So by using both the methods we can iterate over collection.
62 |
63 | For example.
64 |
65 | ```java
66 |
67 | ArrayList al=new ArrayList<>(); //Collection declaration
68 |
69 | al.add(2); al.add(3); al.add(4); // populating data
70 |
71 | Iterator it=al.iterator(); // '<>' these Brackets should contain type of objects you have added in Collection
72 |
73 | while(it.hasNext()){
74 | Integer x=it.next();
75 | System.out.println(x);
76 | }
77 |
78 | ```
79 |
80 | Output
81 | ```
82 | 2
83 |
84 | 3
85 |
86 | 4
87 | ```
88 |
89 | - ### ListIterator
90 | **Note** : Collections are of different types for e.g Lists, maps,sets and many more.
91 |
92 | Normal Iterator object can only be incremented but ListIterator Object can be decremented as well.
93 |
94 | Hence it is most powerful iterator object.
95 |
96 | hasPrevious() and previous() have similar meaning as hasNext() and next() methods.
97 |
98 | ``public interface ListIterator extends Iterator ``
99 |
100 | An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain
101 |
102 | the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element
103 |
104 | that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of
105 |
106 | Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last
107 |
108 | element returned by a call to next() or previous().
109 |
110 | This interface is a member of the Java Collections Framework.
111 |
112 | ```java
113 |
114 |
115 | ArrayList al=new ArrayList<>(); //Collection declaration
116 |
117 | al.add(2); al.add(3); al.add(4); // populating data
118 |
119 | ListIterator it=al.listIterator(); // '<>' these Brackets should contain type of objects you have added in Collection
120 |
121 | while(it.hasNext()){
122 | Integer x=it.next();
123 | if(it.hasPrevious()){
124 | Integer y=it.previous();
125 | System.out.println("Previous "+y);
126 | }
127 | it.next();
128 | System.out.println("Next "+x);
129 |
130 | }
131 |
132 | ```
133 |
134 | **Output**
135 | ```
136 | Previous 2
137 |
138 | Next 2
139 |
140 | Previous 3
141 |
142 | Next 3
143 |
144 | Previous 4
145 |
146 | Next 4
147 |
148 | ```
149 |
150 |
151 |
152 |
153 |
--------------------------------------------------------------------------------
/JAVA/Pair/hashing.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Introduction
4 |
5 | > Hashing is the process of indexing and retrieving element (data) in a data structure to provide faster way of finding the element using the hash key.
6 |
7 | > Java provides HashMap and HashSet classes to implement Hashing by using the hashcode value of an object to determine where the object should be stored in the collection. This hashcode is used again to help locate the object in the collection.
8 |
9 | > In case you want to hash your custom class, you need to use the hashCode() and the equals() methods provided in java.lang.Object class and override them.
10 |
11 | ## hashcode() and equals() methods
12 |
13 | > equals(Object obj): This method indicates whether some other object passed as an argument is "equal to" the current instance. Two objects are equal if and only if they are stored in the same memory address.
14 |
15 | > hashcode(): This method returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance. This integer might change between several executions of the application and won't stay the same.
16 |
17 |
18 | NOTE!- If two objects are equal according to the equals(Object) method, then calling the hashcode() method on each of the two objects must produce the same integer result.
19 |
20 | ## Why overriding hashCode() and equals() method is needed?
21 | Note the examples given below.
22 | In the first example, both the methods are overridden so that Pair("Hello","World") and Pair("World","Hello") both have the same hashCode.
23 | ```java
24 | class Pair
25 | {
26 | String a,b;
27 | public Pair(String a, String b)
28 | {
29 | super();
30 | this.a = a;
31 | this.b = b;
32 | }
33 | @Override
34 | public boolean equals(Object obj)
35 | {
36 | boolean t = true;
37 | if (this == obj)
38 | return true;
39 | if (obj == null)
40 | return false;
41 | if (this.hashCode() == obj.hashCode())
42 | return true;
43 | return t;
44 | }
45 |
46 | @Override
47 | public int hashCode()
48 | {
49 | return a.hashCode() + b.hashCode();
50 | }
51 | }
52 |
53 | public class Main
54 | {
55 | public static void main(String args[])
56 | {
57 | Pair p1 = new Pair ("Hello", "World");
58 | Pair p2 = new Pair ("World", "Hello");
59 | System.out.println("p1 hashcode = " + p1.hashCode());
60 | System.out.println("p2 hashcode = " + p2.hashCode());
61 | System.out.println("Checking equality between p1 and p2 = " + p1.equals(p2));
62 | }
63 | }
64 | ```
65 | ## Output
66 | ```
67 | p1 hashcode = 153375780
68 | p2 hashcode = 153375780
69 | Checking equality between p1 and p2 = true
70 | ```
71 |
72 | > If equals() and hashCode() methods are not overridden, we will get different hash code for Pair("Hello", "World") and Pair("World", "Hello"). The example below demonstrates this.
73 |
74 | ```java
75 | class Pair
76 | {
77 | String a,b;
78 | public Pair(String a, String b)
79 | {
80 | super();
81 | this.a = a;
82 | this.b = b;
83 | }
84 | //Not overriding equals() and hashCode() methods
85 | }
86 |
87 | public class Main
88 | {
89 | public static void main(String args[])
90 | {
91 | Pair p1 = new Pair ("Hello", "World");
92 | Pair p2 = new Pair ("World", "Hello");
93 | System.out.println("p1 hashcode = " + p1.hashCode());
94 | System.out.println("p2 hashcode = " + p2.hashCode());
95 | System.out.println("Checking equality between p1 and p2 = " + p1.equals(p2));
96 | }
97 | }
98 | ```
99 | ## Output
100 | ```
101 | p1 hashcode = 366712642
102 | p2 hashcode = 1829164700
103 | Checking equality between p1 and p2 = false
104 | ```
105 |
--------------------------------------------------------------------------------
/JAVA/Pair/pair.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Function
4 | > JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair.
5 |
6 | > simply refers to a pair of values that are stored together.
7 |
8 | > Pairs provide a convenient way of handling simple key to value association and are particularly useful when we want to return two values from a method.
9 |
10 | NOTE!- You need to have Java 8 installed on your machine in order to run the below program.
11 |
12 |
13 | ## Syntax
14 | ```java
15 | //This returns an object of Pair class with key of Type T1 and Value of Type T2
16 | Pair p = new Pair <> (val1, val2);
17 | ```
18 |
19 | ## Parameters
20 | val1 : Key of type T1
21 |
22 | val2 : Value for key val1, of type T2
23 |
24 | ## Methods of Pair Class
25 |
26 | Method | Description
27 | ------------ | -------------
28 | Pair (K key, V value) | Creates a new pair
29 | boolean equals() | It is used to compare two pair objects. It compares on the basic of the values () which are stored in the pair objects.
30 | String toString() | It returns the String representation of the Pair.
31 | K getKey() | It returns key for the pair.
32 | V getValue() | It returns value for the pair.
33 | int hashCode() | Generates a hash code for the Pair.
34 |
35 | ## Example
36 | ```java
37 | import javafx.util.Pair;
38 |
39 | public class Main
40 | {
41 | public static void main(String args[])
42 | {
43 | Pair p1 =new Pair<>("Mumbai",6);
44 | Pair p2 =new Pair<>("Chennai",7);
45 | Pair p3 =new Pair<>("Bombay",6);
46 | Pair p4 =new Pair<>("Mumbai",6);
47 | //equals method example
48 | System.out.println(p1.equals(p2));
49 | System.out.println(p1.equals(p3));
50 | System.out.println(p1.equals(p4));
51 | //toString example
52 | System.out.println(p1.toString());
53 | //getKey and getValue example
54 | System.out.println("Number of alphabets in "+p1.getKey()+" is "+p1.getValue());
55 | }
56 |
57 |
58 | }
59 | ```
60 |
61 | ## Output
62 | ```
63 | false
64 | false
65 | true
66 | Mumbai=6
67 | Number of alphabets in Mumbai is 6
68 | ```
--------------------------------------------------------------------------------
/JAVA/Pair/sorting.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Introduction
4 | > To sort a collection of Pair objects, we need to override the compareTo() method or create a new method to compare the keys or values. This is because it is not clear whether to sort based on key (first value) or based on value (second value) of Pair objects.
5 |
6 | > It is possible to sort a Hashmap based on key but to sort a HashMap by it's values, we need to convert the existing Map into a List and then sort this list by using Comparator interface and then again put this sorted list back to a Map.
7 |
8 | ## Example (Sorting by second value using Comparator)
9 | ```java
10 | import javafx.util.Pair;
11 | import java.util.*;
12 |
13 | public class Main
14 | {
15 | public static void main(String args[])
16 | {
17 | List> fruits = new ArrayList>();
18 | fruits.add(new Pair("Strawberry",7));
19 | fruits.add(new Pair("Watermelon",2));
20 | fruits.add(new Pair("Orange",5));
21 |
22 | fruits.sort(new Comparator>() {
23 | @Override
24 | public int compare(Pair o1, Pair o2) {
25 | if (o1.getValue() < o2.getValue()) {
26 | return -1;
27 | } else if (o1.getValue().equals(o2.getValue())) {
28 | return 0;
29 | } else {
30 | return 1;
31 | }
32 | }
33 | });
34 | System.out.println("Sorting by second value (integer) in ascending order:");
35 | System.out.println(fruits);
36 | }
37 |
38 |
39 | }
40 | ```
41 | ## Output
42 | ```
43 | Sorting by second value (integer) in ascending order:
44 | [Watermelon=2, Orange=5, Strawberry=7]
45 | ```
46 |
47 |
48 | ## Example (Sorting by first value in descending order)
49 | ```java
50 | import javafx.util.Pair;
51 | import java.util.*;
52 |
53 | public class Main
54 | {
55 | public static void main(String args[])
56 | {
57 | List> fruits = new ArrayList>();
58 | fruits.add(new Pair("Strawberry",7));
59 | fruits.add(new Pair("Watermelon",2));
60 | fruits.add(new Pair("Orange",5));
61 |
62 | fruits.sort(new Comparator>() {
63 | @Override
64 | public int compare(Pair o1, Pair o2) {
65 | if ((o1.getKey()).compareTo(o2.getKey()) >0 ) {
66 | return -1;
67 | } else if (o1.getKey().equals(o2.getKey())) {
68 | return 0;
69 | } else {
70 | return 1;
71 | }
72 | }
73 | });
74 | System.out.println("Sorting by first value (string) in descending order:");
75 | System.out.println(fruits);
76 | }
77 |
78 |
79 | }
80 | ```
81 |
82 | ## Output
83 | ```
84 | Sorting by first value (string) in descending order:
85 | [Watermelon=2, Strawberry=7, Orange=5]
86 | ```
87 |
--------------------------------------------------------------------------------
/JAVA/Pair/utilities.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Introduction
4 |
5 | > java.util contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).
6 |
7 | > Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
8 |
9 |
10 | ## Methods of Collection interface
11 |
12 | Method | Description
13 | ------------ | -------------
14 | public boolean add(Object element) | This method is used to insert an element in a collection.
15 | public boolean addAll(Collection c) | This method is used to insert all elements of Collection c in the invoking collection.
16 | public boolean remove(Object element) | This method is used to delete an element from a collection.
17 | public boolean removeAll(Collection c) | This method is used to delete all the elements of Collection c from the invoking collection.
18 | public boolean retainAll(Collection c) | This method is used to delete all the elements of invoking collection except the elements which are present in specified Collection c.
19 | public int size() | This method returns the total number of elements in the collection.
20 | public void clear() | This method removes all the elements from the collection.
21 | public boolean contains(Object element) | This method is used to search an element in invoking collection.
22 | public boolean containsAll(Collection c) | This method is used to check if all the elements of Collection c are present in invoking collection or not.
23 | public Iterator iterator() | This method returns an iterator.
24 | public boolean isEmpty() | This method checks if collection is empty.
25 | public boolean equals(Object element) | This method is used to compare objects of collections.
26 |
27 | NOTE!- The above methods work for Set and List Interfaces.
28 |
29 |
30 | ## Methods of Iterator interface
31 |
32 | Method | Description
33 | ------------ | -------------
34 | public boolean hasNext() | It returns true if iterator has more elements.
35 | public Object next() | It returns the element and moves the cursor pointer to the next element.
36 | public void remove() | It removes the last elements returned by the iterator. It is rarely used.
37 |
38 | ## Example
39 | ```java
40 | //This example demonstrates the use of all methods listed above
41 | import java.util.*;
42 |
43 | public class Main
44 | {
45 | public static void main(String args[])
46 | {
47 | ArrayList num= new ArrayList();
48 | ArrayList even_num= new ArrayList();
49 | ArrayList odd_num= new ArrayList();
50 |
51 | //inserting elements using add() method
52 | for(int i=1;i<=10;i++)
53 | num.add(i);
54 |
55 | System.out.println("Original list of numbers is: ");
56 | //Print numbers using iterator
57 | Iterator it = num.iterator();
58 | while(it.hasNext())
59 | System.out.println(it.next());
60 |
61 | for(int i=2;i<=10;i=i+2)
62 | even_num.add(i);
63 |
64 | System.out.println("List of even numbers is: ");
65 | Iterator even_it = even_num.iterator();
66 | while(even_it.hasNext())
67 | System.out.println(even_it.next());
68 |
69 |
70 | //inserting all elements of num in odd_num
71 | odd_num.addAll(num);
72 |
73 | //removing elements of even_num from odd_num
74 | odd_num.removeAll(even_num);
75 |
76 | System.out.println("List of odd numbers is: ");
77 | Iterator odd_it = odd_num.iterator();
78 | while(odd_it.hasNext())
79 | System.out.println(odd_it.next());
80 |
81 |
82 | num.clear();
83 | int n = num.size();
84 | int e = even_num.size();
85 | System.out.println("Size of num list is "+n+" and that of even_num list is "+e);
86 |
87 | //check if even_num list contains 10
88 | boolean check = even_num.contains(10);
89 | System.out.println("even_num contains 10? "+check);
90 |
91 | //check if even_num contains all elements of odd_num
92 | check = even_num.containsAll(odd_num);
93 | System.out.println("even_num contains odd_num? "+check);
94 | boolean empty = num.isEmpty();
95 | System.out.println("num is empty? "+empty);
96 | //even if any one element of odd_num is not present in even_num, the method will return false
97 |
98 | //check if temp is equl to odd_num
99 | ArrayList temp= new ArrayList();
100 | temp.addAll(odd_num);
101 | check= temp.equals(odd_num);
102 | System.out.println("temp list equal to odd_num? "+check);
103 |
104 |
105 | }
106 | }
107 | ```
108 |
109 | ## Output
110 | ```
111 | Original list of numbers is:
112 | 1
113 | 2
114 | 3
115 | 4
116 | 5
117 | 6
118 | 7
119 | 8
120 | 9
121 | 10
122 | List of even numbers is:
123 | 2
124 | 4
125 | 6
126 | 8
127 | 10
128 | List of odd numbers is:
129 | 1
130 | 3
131 | 5
132 | 7
133 | 9
134 | Size of num list is 0 and that of even_num list is 5
135 | even_num contains 10? true
136 | even_num contains odd_num? false
137 | num is empty? true
138 | temp list equal to odd_num? true
139 | ```
140 |
141 |
142 | ## Methods of Map Interface
143 | Method | Description
144 | ------------ | -------------
145 | Object put(Object key, Object value) | It is used to insert an entry in this map.
146 | void putAll(Map map) | It is used to insert the specified map in this map.
147 | Object remove(Object key) | It is used to delete an entry for the specified key.
148 | Object get(Object key) | It is used to return the value for the specified key.
149 | boolean containsKey(Object key) | It is used to search the specified key from this map.
150 | Set keySet() | It is used to return the Set view containing all the keys.
151 | Set entrySet() | It is used to return the Set view containing all the keys and values.
152 |
153 |
154 | ## Methods of Map.Entry Interface
155 |
156 | Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It provides methods to get key and value.
157 |
158 | Method | Description
159 | ------------ | -------------
160 | Object getKey() | It is used to obtain key.
161 | Object getValue() | It is used to obtain value.
162 |
163 |
164 | Maps can also be traversed using Iterator.
165 |
166 | ## Example
167 | ```java
168 | //This example demonstrates use of all Map Interface methods
169 | import java.util.*;
170 | class Main
171 | {
172 | public static void main(String args[])
173 | {
174 | Map map=new HashMap();
175 | Map copy=new HashMap();
176 | map.put(100,"ABC");
177 | map.put(101,"XYZ");
178 | map.put(102,"PQR");
179 |
180 | //traversing map
181 | System.out.println("Traversing map:");
182 | for(Map.Entry m:map.entrySet())
183 | System.out.println(m.getKey()+" "+m.getValue());
184 |
185 |
186 | System.out.println("Value of key 100 in map is " +map.get(100));
187 |
188 | //inserting all elements of map into copy
189 | copy.putAll(map);
190 | System.out.println("Traversing copy: ");
191 | for(Map.Entry c:copy.entrySet())
192 | System.out.println(c.getKey()+" "+c.getValue());
193 |
194 |
195 | map.remove(102);
196 | System.out.println("Removed key 102 from map.");
197 | boolean check = map.containsKey(102);
198 |
199 | System.out.println("map contains key 102? "+check);
200 |
201 | }
202 | }
203 | ```
204 |
205 | ## Output
206 | ```
207 | Traversing map:
208 | 100 ABC
209 | 101 XYZ
210 | 102 PQR
211 | Value of key 100 in map is ABC
212 | Traversing copy:
213 | 100 ABC
214 | 101 XYZ
215 | 102 PQR
216 | Removed key 102 from map.
217 | map contains key 102? false
218 | ```
219 |
220 |
--------------------------------------------------------------------------------
/JAVA/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
JAVA Collections Framework
4 |
5 |
6 |
7 | ### Index
8 | 1. Containers
9 | 1. [Lists](./containers/lists.md)
10 | 1. ArrayList
11 | 2. Vector
12 | 3. LinkedList
13 | 2. [Queues](./containers/queues.md)
14 | 1. PriorityQueue
15 | 3. [Stack](./containers/stack.md)
16 | 4. [Maps](./containers/maps.md)
17 | 1. HashMap
18 | 2. TreeMap
19 | 3. LinkedHashMap
20 | 5. [Sets](./containers/sets.md)
21 | 1. HashSet
22 | 2. LinkedHashSet
23 | 3. TreeSet
24 | 6. Pairs
25 | 1. [Hashing](./Pair/hashing.md)
26 | 2. [Pair](./Pair/pair.md)
27 | 3. [Utilities](./Pair/utilities.md)
28 | 4. [sorting](./Pair/sorting.md)
29 | 7. [String/StringBuffers](./Strings.md)
30 | 2. Collections
31 | 1. [reverse](./Collections/reverse.md)
32 | 2. [Sort](./Collections/sort.md)
33 | 3. [reverseOrder](./Collections/reverseOrder.md)
34 | 4. [shuffle](./Collections/shuffle.md)
35 | 5. [rotate](./Collections/rotate.md)
36 | 6. [swap](./Collections/swap.md)
37 | 7. [binarySearch](./Collections/binarySearch.md)
38 | 8. [min](./Collections/min.md)
39 | 9. [max](./Collections/max.md)
40 | 3. [Iterators](./Iterators.md)
41 | 1. iterator
42 | 2. listIterator
43 | 3. for each style
--------------------------------------------------------------------------------
/JAVA/Strings.md:
--------------------------------------------------------------------------------
1 | # JAVA String/StringBuffer
2 |
3 | ### Difference Between String and StringBuffer Class in Java :
4 |
5 |
6 | String and StringBuffer both are the classes which operate on strings. The object of String class is of fixed length.
7 |
8 | The object of the StringBuffer class is growable. The basic difference between String and StringBuffer is that the object of the “String” class is immutable.
9 |
10 | The object of the class “StringBuffer” mutable.
11 |
12 |
13 | 
14 |
15 | **What is meant by immutable:**
16 |
17 | we cannot append,remove new string to created object.StringBuffer objects provide more functionality to the strings as compared to the class String.
18 |
19 | Hence, it is preferable to work with StringBuffer instead of class String.so when we want to make fixed size string use string object and when we want perform operation like append remove we use stringBuffer class object.
20 |
21 | ```
22 | String Object:
23 |
24 | Creating empty string object → String str = new String (“Hello”);
25 |
26 | Appending new string → str.concat(“World !”);
27 |
28 | Printing string object → System.out.println(str);
29 |
30 | Output → Hello
31 |
32 | StringBuffer Object:
33 |
34 | Creating empty string object → String str = new String (“Hello”);
35 |
36 | Appending new string → str.append(“ World !”);
37 |
38 | Printing string object → System.out.println(str);
39 |
40 | Output → Hello World !
41 |
42 | ```
43 |
44 | ### Important Note :
45 | - Concat operation on StringBuffer is O(1 ) while for String Class it is O(n).
46 |
47 | - Because String is immutable hence new object is created for every concat.
48 |
49 | ### Important methods of String class:
50 |
51 | 
52 |
53 |
54 | ### Important methods of StringBuffer class:
55 |
56 | 
57 |
58 |
--------------------------------------------------------------------------------
/JAVA/containers/lists.md:
--------------------------------------------------------------------------------
1 | Lists
2 |
3 | Arraylists
4 |
5 | >Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface
6 |
7 | >ArrayList in Java can be seen as similar to vector in C++.
8 |
9 | > ArrayList only supports object entries, not the primitive data types(like int, float, char, etc).
10 |
11 | >Java ArrayList class maintains insertion order
12 |
13 | >Java ArrayList allows random access because array works at the index basis.
14 |
15 | >In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.
16 |
17 |
18 |
19 | ### Operations
20 |
21 |
22 | |Function |What it does? | Complexity
23 | | :------------- | :------------- | :------------- |
24 | | void clear() | It is used to remove all of the elements from this list.|O(1)
25 | | void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list.|O(1) if added at the end,O(n) if added in the interior
26 | | int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element |O(n)
27 | | int lastIndexOf(Object o) |It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.|O(n)
28 | | Object[] toArray() |It is used to return an array containing all of the elements in this list in the correct order.|O(n)
29 | | Object clone() | It is used to return a shallow copy of an ArrayList.|-
30 | | void trimToSize() |It is used to trim the capacity of this ArrayList instance to be the list's current size.|-
31 |
32 |
33 | ### Implementation of ArrayList
34 |
35 | ```java
36 | //declaration
37 | //creating new generic arraylist
38 | ArrayList al=new ArrayList();
39 | ```
40 | ```java
41 | //simple example
42 | import java.util.*;
43 | class TestCollection1{
44 | public static void main(String args[]){
45 | ArrayList list=new ArrayList();//Creating arraylist
46 | list.add("Shivam");
47 | list.add("Tushar");
48 | list.add("Chirag");
49 | list.add("Neel");
50 | //Traversing list through Iterator
51 | Iterator itr=list.iterator();
52 | while(itr.hasNext()){
53 | System.out.println(itr.next());
54 | }
55 | System.out.println();
56 |
57 |
58 | //addall()
59 |
60 | ArrayList al2=new ArrayList();
61 | list.add("Devansh");
62 | al2.addAll(list);
63 | Iterator itr2 = al2.iterator();
64 |
65 | while(itr2.hasNext()){
66 | System.out.println(itr2.next());
67 | }
68 | System.out.println();
69 |
70 | //indexOf()
71 |
72 | int pos1 =list.indexOf("Shivam");
73 | System.out.println(pos1);
74 | }
75 |
76 | }
77 |
78 | ```
79 | Output:
80 | ```
81 | Shivam
82 | Tushar
83 | Chirag
84 | Neel
85 |
86 | Shivam
87 | Tushar
88 | Chirag
89 | Neel
90 | Devansh
91 |
92 | 0
93 |
94 | ```
95 |
96 |
97 |
98 | Vector
99 |
100 | >Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an index.
101 |
102 | >They are very similar to ArrayList but Vector is synchronised and have some legacy method which collection framework does not contain.
103 |
104 | >It extends AbstractList and implements List interfaces.
105 |
106 |
107 | ### Operations
108 |
109 | |Function |What it does? | Complexity
110 | | :------------- | :------------- | :------------- |
111 | |void clear() | It is used to remove all of the elements from this list.|O(1)
112 | |void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list.|O(1) if added at the end,O(n) if added in the interior
113 | |int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element |O(n)
114 | |int lastIndexOf(Object o) |It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.|O(n)
115 | |Object[] toArray() |It is used to return an array containing all of the elements in this list in the correct order.|O(n)
116 | |Object clone() | It is used to return a shallow copy of an ArrayList.|O(n)
117 | |void trimToSize() |It is used to trim the capacity of this ArrayList instance to be the list's current size.|-
118 | |boolean contains(Object o) |This method returns true if this vector contains the specified element |O(n)
119 | |boolean remove(Object o) |This method removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.|O(n)
120 | |boolean equals(Object o)| This method compares the specified Object with this Vector for equality.|O(n)
121 |
122 |
123 | ### Implementation of Vectors
124 |
125 | ```java
126 | //declaration
127 |
128 |
129 | import java.util.*;
130 | class Vector_demo
131 | {
132 | public static void main(String[] arg)
133 | {
134 |
135 | // create default vector
136 | Vector v = new Vector();
137 |
138 | v.add("Shivam");
139 | v.add("Chirag");
140 | v.add("Devansh");
141 | v.add("Nishchith");
142 |
143 | System.out.println("Vector is " + v);
144 |
145 | //addall()
146 | Vector arr = new Vector();
147 |
148 | // copying all element of array list int0 vector
149 | arr.addAll(v);
150 | System.out.println("vector arr:" + arr);
151 |
152 | // check whether vector contains "Nishchith"
153 | if(v.contains("Nishchith"))
154 | System.out.println("Nishchith exists");
155 |
156 | //equals
157 |
158 | Vector v1 = new Vector();
159 | v1.add("Shivam");
160 | v1.add("Chirag");
161 | v1.add("Devansh");
162 | v1.add("Nishchith");
163 | System.out.println(v.equals(v1);
164 | }
165 | }
166 | ```
167 |
168 |
169 | Output
170 | ```
171 | Vector is [Shivam, Chirag, Devansh, Nishchith]
172 | vector arr:[Shivam, Chirag, Devansh, Nishchith]
173 | Nishchith exists
174 | true
175 | ```
176 |
177 |
178 |
179 | Difference between ArrayList and Vector
180 |
181 | |ArrayList|Vector
182 | | :------------- | :------------- |
183 | |1)ArrayList is not synchronized.|1)Vector is synchronized.
184 | |2) ArrayList increments 50% of current array size if number of element exceeds from its capacity.|2)Vector increments 100% means doubles the array size if total number of element exceeds than its capacity
185 | |3) ArrayList uses Iterator interface to traverse the elements.|3)Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.
186 | |4)Is is fast|4)It is comparatively slower.
187 |
188 |
189 |
190 | LinkedList
191 |
192 | >Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure
193 |
194 | >Java LinkedList class can contain duplicate elements.
195 |
196 | >Java LinkedList class maintains insertion order.
197 |
198 | >Java LinkedList class can be used as list, stack or queue.
199 |
200 | ### Operations
201 |
202 | |Function |What it does? | Complexity
203 | | :------------- | :------------- | :------------- |
204 | |void clear() | It is used to remove all of the elements from this list.|O(1)
205 | |void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list.|O(1) if added at the end,O(n) if added in the interior
206 | |int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element |O(n)
207 | |int lastIndexOf(Object o) |It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.in|O(n)
208 | |Object[] toArray() |It is used to return an array containing all of the elements in this list in the correct order.|O(n)
209 | |Object clone() | It is used to return a shallow copy of an ArrayList.|O(n)
210 | |void trimToSize() |It is used to trim the capacity of this ArrayList instance to be the list's current size.|O(n)
211 | |void addFirst(Object o)|It is used to insert the given element at the beginning of a list.|O(1)
212 | |void addLast(Object o) |It is used to insert the given element at the ending of a list.|O(1)
213 | |int size() |It is used to return the number of elements in a list|O(1)
214 | |Object getFirst()|It is used to return the first element in a list.|O(1)
215 | |Object getLast()|It is used to return the last element in a list.|O(1)
216 |
217 |
218 |
219 | ### Implementation of LinkedList
220 |
221 |
222 |
223 | ```java
224 | // declaration
225 | //eg
226 | LinkedList al=new LinkedList();
227 |
228 | ```
229 |
230 |
231 | ```java
232 | import java.util.*;
233 | public class LinkedList_Demo{
234 | public static void main(String args[]){
235 |
236 | LinkedList al=new LinkedList();
237 | al.add("Neel");
238 | al.add("Devansh");
239 | Iterator itr=al.iterator();
240 | while(itr.hasNext()){
241 | System.out.println(itr.next());
242 | }
243 | System.out.println();
244 |
245 | //addfirst and last
246 |
247 | al.addFirst("chirag");
248 | al.addLast("hello");
249 | Iterator itr2 = al.iterator();
250 | while(itr2.hasNext()){
251 | System.out.println(itr2.next());
252 | }
253 | }
254 | }
255 |
256 | ```
257 | Output:
258 | ```
259 | Neel
260 | Devansh
261 |
262 | chirag
263 | Neel
264 | Devansh
265 | hello
266 | ```
267 |
268 |
--------------------------------------------------------------------------------
/JAVA/containers/maps.md:
--------------------------------------------------------------------------------
1 |
2 |
Maps
3 |
4 |
5 |
6 | A map contains values on the basis of key i.e. key
7 | and value pair. Each key and value pair is known as an entry. Map contains only unique keys.
8 | Map is useful if you have to search, update or delete elements on the basis of key.
9 |
10 | ## HashMaps
11 | Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map
12 | interface.
13 | The important points about Java HashMap class are:
14 |
15 | * A HashMap contains values based on the key.
16 | * It contains only unique elements.
17 | * It may have one null key and multiple null values.
18 | * It maintains no order.
19 |
20 | **HashMap Class Declaration**
21 | ```java
22 | public class HashMap extends AbstractMapimplements Map, Cloneable, Serializable
23 | ```
24 | *Where*
25 | * K: It is the type of keys maintained by this map.
26 | * V: It is the type of mapped values.
27 |
28 | **Constructors of Java HashMap class :**
29 |
30 | | Constructor | Description |
31 | | :---------------| :--------------------|
32 | |HashMap()| It is used to construct a default HashMap.
33 | |HashMap(Map m) |It is used to initializes the hash map by using the elements of the given Map object m.
34 | |HashMap(int capacity) |It is used to initializes the capacity of the hash map to the given integer value, capacity.
35 | |HashMap(int capacity, float fillRatio)| It is used to initialize both the capacity and fill ratio of the hash map by using its arguments.|
36 |
37 |
38 | **Methods of HashMaps Class**
39 |
40 | | Method | Description |
41 | | :------------------- | :------------------ |
42 | |void clear()| It is used to remove all of the mappings from this map.|
43 | | boolean containsKey(Object key) | It is used to return true if this map contains a mapping for the specified key.|
44 | | boolean containsValue(Object value) | It is used to return true if this map maps one or more keys to the specified value.|
45 | | boolean isEmpty()| It is used to return true if this map contains no key-value mappings.|
46 | |Object clone()| It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.|
47 | |Set entrySet() | It is used to return a collection view of the mappings contained in this map. |
48 | | Set keySet() | It is used to return a set view of the keys contained in this map.|
49 | |Object put(Object key, Object value)| It is used to associate the specified value with the specified key in this map.|
50 | |int size()| It is used to return the number of key-value mappings in this map.|
51 | |Collection values() |It is used to return a collection view of the values contained in this map|
52 |
53 | ### Example
54 | ``` java
55 | import java.util.*;
56 | class TestCollection13{
57 | public static void main(String args[]){
58 | HashMap hm=new HashMap();
59 | hm.put(100,"Amit");
60 | hm.put(101,"Vijay");
61 | hm.put(102,"Rahul");
62 | for(Map.Entry m:hm.entrySet()){
63 | System.out.println(m.getKey()+" "+m.getValue());
64 | }
65 | }
66 | }
67 | ```
68 | #### Output
69 | ```java
70 | 102 Rahul
71 | 100 Amit
72 | 101 Vijay
73 | ```
74 |
75 |
76 |
77 |
78 | ## TreeMaps
79 |
80 | Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order.
81 |
82 | The important points about Java TreeMap class are:
83 |
84 | * A TreeMap contains values based on the key.
85 | * It implements the NavigableMap interface and extends AbstractMap class.
86 | * It contains only unique elements.
87 | * It cannot have null key but can have multiple null values.
88 | * It is same as HashMap instead maintains ascending order.
89 |
90 | **Tree Map class declaration**
91 |
92 | ```java
93 | public class TreeMap extends AbstractMapimplements NavigableMap, Cloneable, Serializable
94 | ```
95 | *Where*
96 | * K: It is the type of keys maintained by this map.
97 | * V: It is the type of mapped values.
98 |
99 | **Constructors of Java TreeMap class :**
100 |
101 | |Constructor| Description|
102 | | :---------------| :--------------------|
103 | |TreeMap()| It is used to construct an empty tree map that will be sorted using the natural order of its key.
104 | |TreeMap(Comparator comp)| It is used to construct an empty tree-based map that will be sorted using the comparator comp.
105 | |TreeMap(Map m)| It is used to initialize a tree map with the entries from m, which will be sorted using the natural order of the keys.
106 | |TreeMap(SortedMap sm)| It is used to initialize a tree map with the entries from the SortedMap sm, which will be sorted in the same order as sm.|
107 |
108 | **Methods of Java TreeMap class**
109 |
110 | | Method| Description |
111 | | :-----------------| :---------------------|
112 | |boolean containsKey(Object key) | It is used to return true if this map contains a mapping for the specified key.|
113 | |boolean containsValue(Object value)| It is used to return true if this map maps one or more keys to the specified value.
114 | |Object firstKey() |It is used to return the first (lowest) key currently in this sorted map.
115 | |Object get(Object key)| It is used to return the value to which this map maps the specified key.|
116 | |Object lastKey()| It is used to return the last (highest) key currently in this sorted map.
117 | |Object remove(Object key) |It is used to remove the mapping for this key from this TreeMap if present.|
118 | |void putAll(Map map)| It is used to copy all of the mappings from the specified map to this map.
119 | |Set entrySet()| It is used to return a set view of the mappings contained in this map.|
120 | |int size()| It is used to return the number of key-value mappings in this map.|
121 | |Collection values()| It is used to return a collection view of the values contained in this map.
122 |
123 |
124 | ### Example
125 |
126 | ```java
127 | import java.util.*;
128 | class TestCollection15{
129 | public static void main(String args[]){
130 | TreeMap hm=new TreeMap();
131 | hm.put(100,"Amit");
132 | hm.put(102,"Ravi");
133 | hm.put(101,"Vijay");
134 | hm.put(103,"Rahul");
135 | for(Map.Entry m:hm.entrySet()){
136 | System.out.println(m.getKey()+" "+m.getValue());
137 | }
138 | }
139 | }
140 | ```
141 | #### Output
142 | ```java
143 | 100 Amit
144 | 101 Vijay
145 | 102 Ravi
146 | 103 Rahul
147 | ```
148 | **Note :**
149 | ###### Difference between Hash Map and Tree Maps :
150 |
151 | |HashMap| TreeMap|
152 | | :--------------- | :--------------|
153 | |1) HashMap can contain one null key.| TreeMap can not contain any null key.|
154 | |2) HashMap maintains no order.| TreeMap maintains ascending order.|
155 |
156 |
157 | ## LinkedHashMap
158 | Java LinkedHashMap class is Hash table and Linked list
159 | implementation of the Map interface, with predictable
160 | iteration order. It inherits HashMap class and
161 | implements the Map interface.
162 |
163 | The important points about Java LinkedHashMap class
164 | are:
165 | * A LinkedHashMap contains values based on the key.
166 | * It contains only unique elements.
167 | * It may have one null key and multiple null values.
168 | * It is same as HashMap instead maintains insertion order.
169 |
170 | **LinkedMaps Class Declaration**
171 | ```java
172 | public class LinkedHashMap extends HashMapimplements Map
173 | ```
174 | * K: It is the type of keys maintained by this map.
175 | * V: It is the type of mapped values.
176 |
177 | **Constructors of Java LinkedHashMap class :**
178 |
179 | |Constructor| Description|
180 | | :---------------| :--------------------|
181 | |LinkedHashMap()| It is used to construct a default LinkedHashMap.
182 | |LinkedHashMap(int capacity)| It is used to initialize a LinkedHashMap with the given capacity.
183 | |LinkedHashMap(int capacity, float fillRatio) |It is used to initialize both the capacity and the fillRatio.
184 | |LinkedHashMap(Map m)| It is used to initialize the LinkedHashMap with the elements from the given Map class m.|
185 |
186 | **Methods of LinkedHashMap Class**
187 |
188 | |Method|Description |
189 | | :----------------| :-------------------|
190 | |Object get(Object key) | It is used to return the value to which this map maps the specified key.
191 | |void clear() |It is used to remove all mappings from this map.
192 | |boolean containsKey(Object key)| It is used to return true if this map maps one or more keys to the specified value.|
193 |
194 | ###### Example
195 | ```java
196 | import java.util.*;
197 | class TestCollection14{
198 | public static void main(String args[]){
199 |
200 | LinkedHashMap hm=new LinkedHashMap();
201 |
202 | hm.put(100,"Amit");
203 | hm.put(101,"Vijay");
204 | hm.put(102,"Rahul");
205 |
206 | for(Map.Entry m:hm.entrySet()){
207 | System.out.println(m.getKey()+" "+m.getValue());
208 | }
209 | }
210 | }
211 | ```
212 | **Output**
213 | ```java
214 | 100 Amit
215 | 101 Vijay
216 | 102 Rahul
217 | ```
218 |
--------------------------------------------------------------------------------
/JAVA/containers/queues.md:
--------------------------------------------------------------------------------
1 | Queue
2 |
3 |
4 |
5 | >Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.
6 |
7 |
8 |
9 |
10 | ### Operations
11 |
12 |
13 | |Function | What it does? | Complexity |
14 | | :------------- | :------------- | :------------- |
15 | | boolean add(object) |It is used to insert the specified element into this queue and return true upon success.|O(log(n)) |
16 | | boolean offer(object) |It is used to insert the specified element into this queue.|O(log(n))
17 | |Object remove() |It is used to retrieves and removes the head of this queue.|O(log(n))
18 | |Object poll() |It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.|O(1)
19 | |Object peek() |It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.|O(1)
20 |
21 | Priority Queues
22 |
23 | > Java Priority Queue is implemented using Heap Data Structures
24 |
25 | ### Implementions
26 |
27 |
28 |
29 | ```java
30 | // Java progrm to demonstrate working of priority queue in Java
31 | import java.util.*;
32 |
33 | class Example
34 | {
35 | public static void main(String args[])
36 | {
37 |
38 | PriorityQueue pQueue =
39 | new PriorityQueue();
40 |
41 | pQueue.add("Shivam");
42 | pQueue.add("Neel");
43 | pQueue.add("Devansh");
44 |
45 | System.out.println("Head value using peek function:"
46 | + pQueue.peek());
47 |
48 | System.out.println("The queue elements:");
49 | Iterator itr = pQueue.iterator();
50 | while (itr.hasNext())
51 | System.out.println(itr.next());
52 |
53 | pQueue.poll();
54 | System.out.println("After removing an element" +
55 | "with poll function:");
56 | Iterator itr2 = pQueue.iterator();
57 | while (itr2.hasNext())
58 | System.out.println(itr2.next());
59 |
60 | pQueue.remove("Neel");
61 | System.out.println("after removing Java with" +
62 | " remove function:");
63 | Iterator itr3 = pQueue.iterator();
64 | while (itr3.hasNext())
65 | System.out.println(itr3.next());
66 |
67 |
68 | }
69 | }
70 | ```
71 |
72 |
73 | Output:
74 | ```
75 | Head value using peek function:Shivam
76 | The queue elements:
77 | Shivam
78 | Neel
79 | Devansh
80 |
81 | After removing an elementwith poll function:
82 | Neel
83 | Devansh
84 | after removing Neel with remove function:
85 | Devansh
86 | ```
87 |
88 |
89 |
--------------------------------------------------------------------------------
/JAVA/containers/sets.md:
--------------------------------------------------------------------------------
1 |
2 |
Sets
3 |
4 |
5 |
6 | A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
7 | ## HashSets :
8 | * Java HashSet class is used to create a collection that uses a hash table for storage.
9 | * It inherits the AbstractSet class and implements Set interface.
10 | * The important points about Java HashSet class are:
11 | * HashSet stores the elements by using a mechanism called hashing.
12 | * HashSet contains unique elements only.
13 |
14 | **Hierarchy of HashSet class** :
15 | The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.
16 |
17 | **HashSet class declaration**
18 | ```java
19 | public class HashSet extends AbstractSet implements Set, Cloneable, Serializable
20 | ```
21 | **Constructors of Java HashSet class :**
22 |
23 | |Constructor | Description |
24 | | :---------------| :--------------------|
25 | |HashSet() | It is used to construct a default HashSet.
26 | |HashSet(Collection c) |It is used to initialize the hash set by using the elements of the collection c.|
27 | |HashSet(int capacity)| It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.|
28 |
29 | **Methods of Java HashSet class:**
30 |
31 | | Method | Description|
32 | | :--------------| :------------------
33 | |void clear() |It is used to remove all of the elements from this set.|
34 | |boolean contains(Object o)| It is used to return true if this set contains the specified element.
35 | |boolean add(Object o) |It is used to adds the specified element to this set if it is not already present.
36 | |boolean isEmpty() |It is used to return true if this set contains no elements.
37 | |boolean remove(Object o) |It is used to remove the specified element from this set if it is present.
38 | |Object clone()| It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
39 | |Iterator iterator() |It is used to return an iterator over the elements in this set.
40 | |int size()| It is used to return the number of elements in this set.|
41 |
42 | ##### Example :
43 | ```java
44 | import java.util.*;
45 | class TestCollection9{
46 | public static void main(String args[]){
47 | //Creating HashSet and adding elements
48 | HashSet set=new HashSet();
49 | set.add("Ravi");
50 | set.add("Vijay");
51 | set.add("Ravi");
52 | set.add("Ajay");
53 | //Traversing elements
54 | Iterator itr=set.iterator();
55 | while(itr.hasNext()){
56 | System.out.println(itr.next());
57 | }
58 | }
59 | }
60 | ```
61 | **Output :**
62 | ```java
63 | Ajay
64 | Vijay
65 | Ravi
66 | ```
67 |
68 | ## LinkedHashSet :
69 | Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface.
70 |
71 | The important points about Java LinkedHashSet class are:
72 | * Contains unique elements only like HashSet.
73 | * Provides all optional set operations, and permits null elements.
74 | * Maintains insertion order.
75 |
76 | **Hierarchy of LinkedHashSet class**
77 |
78 | The LinkedHashSet class extends HashSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.
79 |
80 | **LinkedHashSet class declaration**
81 | ```java
82 | public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable
83 | ```
84 | **Constructors of Java LinkedHashSet class**
85 |
86 | |Constructor|Description|
87 | | :--------------| :-------------------------|
88 | |HashSet()| It is used to construct a default HashSet.
89 | |HashSet(Collection c) |It is used to initialize the hash set by using the elements of the collection c.
90 | |LinkedHashSet(int capacity)| It is used initialize the capacity of the linkedhashset to the given integer value capacity.
91 | |LinkedHashSet(int capacity, float fillRatio)| It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.
92 |
93 | **Example :**
94 |
95 | ```java
96 | import java.util.*;
97 | class TestCollection10{
98 | public static void main(String args[]){
99 | LinkedHashSet al=new LinkedHashSet();
100 | al.add("Ravi");
101 | al.add("Vijay");
102 | al.add("Ravi");
103 | al.add("Ajay");
104 | Iterator itr=al.iterator();
105 | while(itr.hasNext()){
106 | System.out.println(itr.next());
107 | }
108 | }
109 | }
110 | ```
111 | **Output :**
112 | ```java
113 | Ravi
114 | Vijay
115 | Ajay
116 | ```
117 |
118 | ## TreeSet :
119 | Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order.
120 |
121 | The important points about Java TreeSet class are:
122 | * Contains unique elements only like HashSet.
123 | * Access and retrieval times are quiet fast.
124 | * Maintains ascending order.
125 | * Hierarchy of TreeSet class
126 | * Java TreeSet class implements NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order.
127 |
128 | **TreeSet class declaration :**
129 | ```java
130 | public class TreeSet extends AbstractSet implements NavigableSet, Cloneable, Serializable
131 | ```
132 | **Constructors of Java TreeSet class :**
133 |
134 | |Constructor|Description|
135 | | :-----------------------| :-------------------------|
136 | |TreeSet() |It is used to construct an empty tree set that will be sorted in an ascending order according to the natural order of the tree set.|
137 | |TreeSet(Collection c) |It is used to build a new tree set that contains the elements of the collection c.
138 | |TreeSet(Comparator comp)| It is used to construct an empty tree set that will be sorted according to given comparator.
139 | |TreeSet(SortedSet ss)| It is used to build a TreeSet that contains the elements of the given SortedSet.|
140 |
141 | **Methods of Java TreeSet class :**
142 |
143 | |Method| Description |
144 | | :---------------- |:---------------------
145 | |boolean addAll(Collection c) |It is used to add all of the elements in the specified collection to this set.
146 | |boolean contains(Object o)| It is used to return true if this set contains the specified element.|
147 | |boolean isEmpty()| It is used to return true if this set contains no elements.|
148 | |boolean remove(Object o)| It is used to remove the specified element from this set if it is present.
149 | |void add(Object o)| It is used to add the specified element to this set if it is not already present.
150 | |void clear() |It is used to remove all of the elements from this set.
151 | |Object clone()| It is used to return a shallow copy of this TreeSet instance.
152 | |Object first()| It is used to return the first (lowest) element currently in this sorted set.
153 | |Object last()| It is used to return the last (highest) element currently in this sorted set.
154 | |int size()| It is used to return the number of elements in this set.|
155 |
156 | **Example : **
157 | ```java
158 | import java.util.*;
159 | class TestCollection11{
160 | public static void main(String args[]){
161 | //Creating and adding elements
162 | TreeSet al=new TreeSet();
163 | al.add("Ravi");
164 | al.add("Vijay");
165 | al.add("Ravi");
166 | al.add("Ajay");
167 | //Traversing elements
168 | Iterator itr=al.iterator();
169 | while(itr.hasNext()){
170 | System.out.println(itr.next());
171 | }
172 | }
173 | }
174 | ```
175 | **Output :**
176 |
177 | ```java
178 | Ajay
179 | Ravi
180 | Vijay
181 | ```
--------------------------------------------------------------------------------
/JAVA/containers/stack.md:
--------------------------------------------------------------------------------
1 | Stack
2 |
3 |
4 |
5 | >Java provides an inbuilt object type called Stack. It is a collection that is based on the last in first out (LIFO) principle. On Creation, a stack is empty.
6 |
7 |
8 |
9 |
10 | ### Operations
11 |
12 |
13 | |Function | What it does? | Complexity |
14 | | :------------- | :------------- | :------------- |
15 | | Object push(Object element) |Pushes an element on the top of the stack.|O(1) |
16 | | Object pop() | Removes and returns the top element of the stack. An ‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack is empty.|O(1) |
17 | |Object peek( ) |Returns the element on the top of the stack, but does not remove it.|O(1) |
18 | |boolean empty() |It returns true if nothing is on the top of the stack. Else, returns false.|O(1)|
19 | |int search(Object element) | It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.| - |
20 |
21 | ### Implementions
22 |
23 | ```java
24 | import java.io.*;
25 | import java.util.*;
26 |
27 | class Main
28 | {
29 | public static void main (String[] args)
30 | {
31 | Stack stack = new Stack();
32 |
33 | stack.push(10);
34 | stack.push(3);
35 | stack.push(5);
36 | stack.push(20);
37 | System.out.println("Current Stack [ bottom to top ]");
38 | for(Integer i : stack){
39 | System.out.print(" "+i);
40 | }
41 | System.out.println("Popped : "+ stack.pop());
42 | stack.push(7);
43 | System.out.println("Peak : " + stack.peek()) ;
44 | System.out.println("Element 3 at position : " + stack.search(3));
45 | }
46 | }
47 |
48 | ```
49 |
50 |
51 | Output:
52 | ```
53 | Current Stack
54 | 10 3 5 20
55 | Popped : 20
56 | Peak : 7
57 | Element 3 at position : 3
58 | ```
59 |
60 |
61 |
--------------------------------------------------------------------------------
/JAVA/p1.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p1.JPG
--------------------------------------------------------------------------------
/JAVA/p2.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p2.JPG
--------------------------------------------------------------------------------
/JAVA/p3.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p3.JPG
--------------------------------------------------------------------------------
/JAVA/p4.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/JAVA/p4.JPG
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 KJSCE Codecell
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 | Standard Template Library
2 |
3 |
4 |
5 | [](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity)
6 | [](http://hits.dwyl.io/KJSCE-Codecell/standard-library-in-x)
7 | [](https://github.com/dwyl/esta/issues)
8 |
9 | [](https://shields.io/)
10 | [](https://shields.io/)
11 | [](https://shields.io/)
12 |
13 |
14 |
15 | ---
16 |
17 | A comprehensive guide to standard template library to make your life easier in X where:
18 | * [X = C++](./cpp/README.md)
19 | * [X = Python](./python/Readme.md)
20 | * [X = Java](./JAVA/README.md)
21 |
22 | ---
23 | Built by folks at KJSCE CODECELL with :heart:
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-hacker
2 |
--------------------------------------------------------------------------------
/cpp/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kjsce-codecell/standard-library-in-x/203c1c8a2ab474539d474d877243827fd67ba935/cpp/.DS_Store
--------------------------------------------------------------------------------
/cpp/Iterators.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | INTRODUCTION
4 |
5 | What are iterators? In STL iterators are the most general way to access data in containers
6 | An iterator is any object that, points to some element in a range of elements (such as an array or a container) and has the ability
7 | to iterate through those elements using a set of operators (with at least the increment (++) and dereference (*) operators).
8 | Iterators provide some common additional functionality to container and makes it possible to iterate(traverse) through the containers which
9 | can be accessed through the bracket( **[ ]** ) operator.
10 | The main advantage of iterators, of course, is that they greatly increase the reuse of code: your own algorithms, based on iterators, will work on a wide range of containers, and your own containers,
11 | which provide iterators, may be passed to a wide range of standard functions.
12 |
13 | CONSTRUCTION
14 | general construction of iterators looks like
15 |
16 | ```cpp
17 | Container ::iterator name;
18 | ```
19 | ex. for creating an iterator for a vector
20 |
21 | ```cpp
22 | vector ::iterator it;
23 | ```
24 |
25 | for list
26 |
27 | ```cpp
28 | list ::iterator it;
29 | ```
30 |
31 |
32 | FUNCTIONS
33 |
34 | | Function | What it does ? |
35 | | :------------- | :------------- |
36 | | **begin()** |This function is used to return the beginning position of the container. |
37 | | **end()** |This function is used to return the end position of the container |
38 | | **advance()** |This function is used to increment the iterator position till the specified number mentioned in its arguments |
39 | | **next()** |This function returns the new iterator that the iterator would point after advancing the positions mentioned in its arguments |
40 | | **prev()** |This function returns the new iterator that the iterator would point after decrementing the positions mentioned in its arguments |
41 | | **inserter()** | This function is used to insert the elements at any position in the container. It accepts 2 arguments, the container and iterator to position where the elements have to be inserted. |
42 | | **distance()** |Calculates the number of elements between first and last|
43 |
44 | **Note** - A few datatypes allow '-' operation to find the distance *second-first* but these aren't allowed for all containers hence we use distance().
45 |
46 | IMPLEMENTATION
47 |
48 | The following is the implementation of few iterator function in vectors,
49 | ```cpp
50 |
51 | #include
52 | #include // for iterators
53 | #include // for vectors
54 | using namespace std;
55 | int main()
56 | {
57 | vector ar = { 1, 2, 3, 4, 5 };
58 | // Declaring iterator to a vector
59 | vector::iterator ptr;
60 | // Displaying vector elements using begin() and end()
61 | cout << "The vector elements are : ";
62 | for (ptr = ar.begin(); ptr < ar.end(); ptr++)
63 | cout << *ptr << " ";
64 | cout<<"\n";
65 | vector::iterator ptr1 = ar.begin();
66 | advance(ptr1, 3);
67 | cout << "The position of iterator after advancing is : ";
68 | cout << *ptr1 << " ";
69 | return 0;
70 | }
71 |
72 | ```
73 | Output:
74 | ```
75 | The vector elements are :
76 | 1 2 3 4 5
77 | The position of iterator after advancing is :
78 | 4
79 |
80 | ```
81 |
82 |
83 | REVERSE ITERATORS
84 |
85 | INTRODUCTION
86 |
87 | Reverse iterator is an iterator adaptor that reverses the direction of a given iterator.
88 | In other words, when provided with a bidirectional iterator, std::reverse_iterator produces a new iterator that moves from the end to the beginning of the sequence defined by the underlying bidirectional iterator.
89 | Here we make us of rend() and rbegin() where rbegin() points to the last element of the container and rend() points to one position before the first element.
90 | Using the operation ++ makes the iterator move a step towards the first element
91 |
92 | IMPLEMENTATION
93 |
94 | ```cpp
95 | for(vector::reverse_iterator i=ar.rbegin();i!=ar.rend();++i)
96 | {
97 | cout<<*i<<" ";
98 | }
99 | ```
100 | Output:
101 |
102 | ```
103 | 5 4 3 2 1
104 | ```
105 | All other functions are the same as that of the iterators.
106 |
107 | **Note** - (For some lazy people) some efforts in typing of syntax can be reduced if you make use of **auto** keyword used provided by c++, using this the above implementation would look like:
108 |
109 | ```cpp
110 | for(auto i=ar.rbegin();i!=ar.rend();++i)
111 | {
112 | cout<<*i<<" ";
113 | }
114 | ```
115 |
--------------------------------------------------------------------------------
/cpp/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
C++ STL
4 |
5 |
6 |
7 | ### Index
8 | 1. [Introduction](./introduction.md)
9 | 2. [What are templates?](./templates.md)
10 | 3. Containers
11 | 1. [Vectors](./containers/Vectors.markdown)
12 | 2. [Iterators](./Iterators.md)
13 | 3. [Sets](./containers/sets.md)
14 | 1. Unordered Sets
15 | 2. Multiset
16 | 4. [Maps](./containers/maps.md)
17 | 1. Unordered Maps
18 | 2. Multimap
19 | 5. [Pairs & Tuples](./containers/Pairs&Tuples.markdown)
20 | 6. [Queue](./containers/queue.md)
21 | 1. Priority Queue
22 | 7. [Stack](./containers/stacks.md)
23 | 8. [Bitset](./containers/bitsets.md)
24 | 4. In-built functions
25 | 1. [next_permutation()](./functions/next_permutation.md)
26 | 2. [max_element()](./functions/max_element.md)
27 | 3. [min_element()](./functions/min_element.md)
28 | 4. [binary_search()](./functions/binary_search.md)
29 | 5. [lower_bound()](./functions/lower_bound.md)
30 | 6. [upper_bound()](./functions/upper_bound.md)
31 | 7. [sort()](./functions/sort.md)
32 | 8. [reverse()](./functions/reverse.md)
33 | 9. [set_union()](./functions/set_union.md)
34 | 10. [set_intersection()](./functions/set_intersection.md)
35 | 11. [set_difference()](./functions/set_difference.md)
36 | 12. [max() & min()](./functions/MaxMin.md)
37 | 13. [is_sorted()](./functions/is_sorted.md)
38 | 5. Solutions to problem
39 | 1. [Second Year Pains-KJCP02](./problems/kjcp02.cpp)
40 | 2. [Sorting Tool-KJCPR](./problems/kjcp01.cpp)
41 | 3. [Snake Eat-SNAKEEAT](./problems/snakeeat.cpp)
42 | 4. [Ipc Trainers-IPCTRAIN](./problems/ipctrain.cpp)
43 | 5. [Chef Subseq-CHEFCODE](./problems/chefcode.cpp)
44 |
--------------------------------------------------------------------------------
/cpp/containers/Pairs&Tuples.markdown:
--------------------------------------------------------------------------------
1 | Pairs & Tuples
2 |
3 |
4 |
5 | Introduction
6 |
7 | Many times while solving various problem where we require 2 values to completely linked with each other in such a scenario it is best to use pairs.
8 | Pair is a container that can be used to bind together a two values which may be of different types. Pair provides a way to store two heterogeneous objects as a single unit.
9 |
10 | construction
11 | The simplest form in general would be the following:
12 |
13 | ```cpp
14 | template struct pair {
15 | T1 first;
16 | T2 second;
17 | };
18 |
19 | ```
20 |
21 | In general pair is a pair of integer values. At a more complex level, pair > is a pair of string and two integers. In the second case, the usage may be like this:
22 |
23 |
24 | ```cpp
25 | pair > P;
26 | string s = P.first; // extract string
27 | int x = P.second.first; // extract first int
28 | int y = P.second.second; // extract second int
29 |
30 | ```
31 |
32 |
33 | We can also initialize a pair just like in vectors
34 |
35 | ```cpp
36 | pair Pair_name (value1, value2) ;
37 | pair g1; //default
38 | pair g2(1, 'a'); //initialized, different data type
39 | pair g3(1, 10); //initialized, same data type
40 | pair g4(g3); //copy of g3
41 |
42 | ```
43 |
44 | Functions
45 |
46 | | Function | What it does ? | Complexity |
47 | | :------------- | :------------- | :------------- |
48 | | make_pair() |This template function allows to create a value pair without writing the types explicitly |O(1)
49 | | operators(=, ==, !=, >=, <=) : |These operations can be appllied to pairs|O(1)
50 | | swap() |This function swaps the contents of one pair object with the contents of another pair object. The pairs must be of same type. |O(1)
51 |
52 | Implementation
53 |
54 | ```cpp
55 | #include
56 | #include //required for pairs
57 | using namespace std;
58 |
59 | int main()
60 | {
61 | pair PAIR1 ;
62 | pair PAIR2 ("Codecell", 1.23) ;
63 | pair PAIR3 ;
64 |
65 | PAIR1.first = 100;
66 | PAIR1.second = 'C' ;
67 |
68 | PAIR3 = make_pair ("Codecell is Best",4.56);
69 |
70 | cout << PAIR1.first << " " ;
71 | cout << PAIR1.second << endl ;
72 |
73 | cout << PAIR2.first << " " ;
74 | cout << PAIR2.second << endl ;
75 |
76 | cout << PAIR3.first << " " ;
77 | cout << PAIR3.second << endl ;
78 |
79 | pairpair1 = make_pair(1, 12);
80 | pairpair2 = make_pair(9, 12);
81 |
82 | cout << (pair1 == pair2) << endl; //compares both first and second values for equality
83 | cout << (pair1 != pair2) << endl; // checks first if they are equal then second
84 | cout << (pair1 >= pair2) << endl; //checks first followed by second
85 | cout << (pair1 <= pair2) << endl;
86 | cout << (pair1 > pair2) << endl;
87 | cout << (pair1 < pair2) << endl;
88 |
89 | cout << "Before swapping:\n " ;
90 | cout << "Contents of pair1 = " << pair1.first << "," << pair1.second ;
91 | cout << "Contents of pair2 = " << pair2.first << "," << pair2.second ;
92 | pair1.swap(pair2);
93 |
94 | cout << "\nAfter swapping:\n ";
95 | cout << "Contents of pair1 = " << pair1.first << "," << pair1.second ;
96 | cout << "Contents of pair2 = " << pair2.first << "," << pair2.second ;
97 |
98 | return 0;
99 | }
100 | ```
101 | Output
102 |
103 | ```
104 | 100 C
105 | Codecell 1.23
106 | Codecell is Best 4.56
107 | 0
108 | 1
109 | 0
110 | 1
111 | 0
112 | 1
113 | Before swapping:
114 | Contents of pair1 = 1,12
115 | Contents of pair2 = 9,12
116 | After swapping:
117 | Contents of pair1 = 9,12
118 | Contents of pair2 = 1,12
119 | ```
120 | Note
121 | Pairs are mainly used at places where we need to rearrange certain data types(sort/insert) but keep together another value related to along with it throughout the process for certain use
122 | By default sorting a pair related container causes data compared on the basis of first parameter although we can create some custom compare function to change the behavior
123 |
124 | ```cpp
125 | #include
126 | using namespace std;
127 |
128 | int main()
129 | {
130 | // Declaring vector of pairs
131 | vector< pair > vect;
132 |
133 | // Initializing 1st and 2nd element of
134 | // pairs with array values
135 | int arr[] = {10, 20, 5, 40 };
136 | int arr1[] = {30, 60, 20, 50};
137 | int n = sizeof(arr)/sizeof(arr[0]);
138 |
139 | // Entering values in vector of pairs
140 | for (int i=0; i Tuples
189 |
190 |
191 | Introduction
192 |
193 | Tuples are nothing completely different but pairs extended from their limitation of size two. In problem solving many time we may accross situation where we require 3-4 values linked together as one that is when we use tuples
194 | A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed
195 |
196 |
197 | Operations
198 |
199 | | Function | What it does ? |
200 | | :------------- | :------------- |
201 | | get() |get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element |
202 | | make_tuple() |make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in tuple|
203 | | tuple_size |It returns the number of elements present in the tuple |
204 | | swap() |The swap(), swaps the elements of the two different tuples.|
205 | | tie() |The work of tie() is to unpack the tuple values into seperate variables. There are two variants of tie(), with and without “ignore” , the “ignore” ignores a particular tuple element and stops it from getting unpacked.|
206 | | tuple_cat() |This function concatenates two tuples and returns a new tuple|
207 |
208 |
209 | Implementation
210 |
211 |
212 | ```cpp
213 |
214 | #include
215 | #include // for tuple
216 | using namespace std;
217 | int main()
218 | {
219 | // Initializing variables for unpacking
220 | int i_val;
221 | char ch_val;
222 | float f_val;
223 |
224 | // Declaring tuple
225 | tuple gk;
226 |
227 | // Assigning values to tuple using make_tuple()
228 | gk = make_tuple('a', 10, 15.5);
229 |
230 | // Initializing tuple
231 | tuple tup1(20,'g',17.5);
232 |
233 | // Printing initial tuple values using get()
234 | cout << "The initial values of tuple are : ";
235 | cout << get<0>(gk) << " " << get<1>(gk);
236 | cout << " " << get<2>(gk) << endl;
237 |
238 | // Use of get() to change values of tuple
239 | get<0>(gk) = 'b';
240 | get<2>(gk) = 20.5;
241 |
242 | // Printing modified tuple values
243 | cout << "The modified values of tuple are : ";
244 | cout << get<0>(gk) << " " << get<1>(gk);
245 | cout << " " << get<2>(gk) << endl;
246 |
247 | // Use of size to find tuple_size of tuple
248 | cout << "The size of tuple is : ";
249 | cout << tuple_size::value << endl;
250 |
251 | // Use of tie() without ignore
252 | tie(i_val,ch_val,f_val) = tup1;
253 |
254 | // Displaying unpacked tuple elements
255 | // without ignore
256 | cout << "The unpacked tuple values (without ignore) are : ";
257 | cout << i_val << " " << ch_val << " " << f_val;
258 | cout << endl;
259 |
260 | // Use of tie() with ignore
261 | // ignores char value
262 | tie(i_val,ignore,f_val) = tup1;
263 |
264 | // Displaying unpacked tuple elements
265 | // with ignore
266 | cout << "The unpacked tuple values (with ignore) are : ";
267 | cout << i_val << " " << f_val;
268 | cout << endl;
269 |
270 | // Concatenating 2 tuples to return a new tuple
271 | auto tup3 = tuple_cat(gk,tup1);
272 | // Displaying new tuple elements
273 | cout << "The new tuple elements in order are : ";
274 | cout << get<0>(tup3) << " " << get<1>(tup3) << " ";
275 | cout << get<2>(tup3) << " " << get<3>(tup3) << " ";
276 | cout << get<4>(tup3) << " " << get<5>(tup3) << endl;
277 |
278 | return 0;
279 | }
280 |
281 | ```
282 |
283 | Output:
284 |
285 | ```
286 | The initial values of tuple are : a 10 15.5
287 | The modified values of tuple are : b 10 20.5
288 | The size of tuple is : 3
289 | The unpacked tuple values (without ignore) are : 20 g 17.5
290 | The unpacked tuple values (with ignore) are : 20 17.5
291 | The new tuple elements in order are : b 10 20.5 20 g 17.5
292 | ```
293 |
294 | Note
295 | Although it might seem to you that tuples are not of much importance but that is not the case it does saves your time in and makes your code clean for writing nested pairs
296 | Also the functionality of sorting of pairs can be extended to tuples by appropriately modifying the custom function involved.
297 |
--------------------------------------------------------------------------------
/cpp/containers/Vectors.markdown:
--------------------------------------------------------------------------------
1 |
2 |
3 | INTRODUCTION
4 |
5 | The simplest STL container is vector.
6 | Vector is just an array with extended functionality. In other words, vectors are dynamic arrays.
7 |
8 | CONSTRUCTION
9 |
10 | ```cpp
11 | vector a; //empty vector
12 | vector b (no of elements, value of each element); //fixed number of elements with default value
13 | vector c (starting iterator/pointer,ending iterator/pointer); //inserting elements from other data structures
14 | vector d (name of vector to be copied);
15 | vector > matrix(no of rows,vector(no of coloumn,default value)) //Declaring a 2D array
16 |
17 | // Note:
18 | vector v[10]; // following declaration isn't a vector with 10 elements but an array of size ten having vector elements
19 |
20 | ```
21 |
22 |
23 | FUNCTIONS
24 |
25 | | Function | What it does ? | Complexity |
26 | | :------------- | :------------- | :------------- |
27 | | at() |Returns the reference to the element at a particular position (can also be done using ‘[ ]’ operator) |O(1)
28 | | clear() |Deletes all the elements from the vector and assign an empty vector |O(N)
29 | | pop_back() |Removes the last element from the vector |O(1)
30 | | push_back() |Inserts a new element at the end of the vector |O(1)
31 | | front() |Returns reference of the first element |O(1)
32 | | back() |Returns reference of the last element |O(1)
33 | | empty() |Returns 1 if vector is empty, else 0 |O(1)
34 | | size() |Returns the total no of elements in the vector| O(1)
35 | | resize() |Resizes the vector to the new length which can be less than or greater than the current length |O(N)
36 |
37 |
38 | Note
39 | begin() and end() function return an iterator(like a pointer) initialized to the first or the last element of the container that can be used to iterate through the collection, while front() and back() function just return a reference to the first or the last element of the container.
40 |
41 | PASSING AS ARGUMENT TO FUNCTION
42 |
43 | Another very important thing that you should remember: When vector is passed as a parameter to some function, a copy of vector is actually created. It may take a lot of time and memory to create new vectors when they are not really needed.
44 | ```cpp
45 | void some_function(vector v) { // Never do it unless you’re sure what you do!
46 | // ...
47 | }
48 | ```
49 | Instead, use the following construction:
50 | ```cpp
51 | int modify_vector(vector& v) { // Correct
52 | V[0]++;
53 | }
54 | ```
55 |
56 | Implementation
57 |
58 | ```cpp
59 | #include
60 | #include
61 |
62 | using namespace std;
63 |
64 | int main()
65 | {
66 | vector v;
67 | v.push_back(5);
68 | while(v.back() > 0)
69 | v.push_back(v.back() - 1);
70 | for(int i = 0;i < v.size();++i)
71 | cout << v.at(i) << ' ';
72 | cout << endl;
73 | while(!v.empty())
74 | {
75 | cout << v.back() << ' ';
76 | v.pop_back();
77 | }
78 | cout << endl;
79 | return 0;
80 | }
81 | ```
82 |
83 | Output:
84 | ```
85 | 5 4 3 2 1 0
86 | 0 1 2 3 4 5
87 | ```
88 |
89 | Further much more functionality can be understood once we start using iterators
90 |
--------------------------------------------------------------------------------
/cpp/containers/bitsets.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | INTRODUCTION
4 |
5 | * A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than other methods to store them.
6 | * However, a limitation of bitset is, N must be known at compile time, it isn't dynamic
7 | * As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector.
8 | * We can access each bit of bitset individually with help of array indexing operator [] that is bs[3] shows bit at index 3 of bitset bs just like a simple array.
9 |
!Remember bitset starts its indexing backward that is for 10110, 0 are at 0th and 3rd indices whereas 1 are at 1st 2nd and 4th indices.
10 |
11 | CONSTRUCTION
12 |
13 | ```cpp
14 |
15 | bitset<10> bset1; // default constructor initializes with all 10 bits 0
16 |
17 | bitset<10> bset2(20); // bset2 is initialized with bits of 20
18 |
19 | bitset<10> bset3(string("1100")); // bset3 is initialized with bits of specified binary string
20 |
21 | ```
22 |
23 | FUNCTIONS
24 |
25 | | Function | What it does ? |
26 | | :------------- | :------------- |
27 | | count() |Returns the number of bits in the bitset that are set (i.e., that have a value of one). |
28 | | size() |Returns the number of bits in the bitset. |
29 | | test() |Returns boolean value regarding a position being set |
30 | | any()/none() |Returns true/false if any bit is set in a given bitset |
31 | | all() |Returns true if all bits are set |
32 | | set() |Sets all bits to 1 or specific bits to 1 or 0 |
33 | | reset() |Sets all bits to 0 or specific pos to 0 |
34 | | flip() |Flips bitvalue at a specific or all positions |
35 | | to_string/to_ulong/to_ullong |Converts the bitsets into appropriate datatypes |
36 |
37 | IMPLEMENTATION
38 |
39 | ```cpp
40 |
41 | #include
42 | #include
43 | #include //for bitsets
44 | using namespace std;
45 |
46 | #define M 32
47 |
48 | int main()
49 | {
50 |
51 | bitset<8> set8; // 00000000
52 | bitset<8> bset1; // 00000000
53 |
54 | // setting first bit (or 6th index)
55 | set8[1] = 1; // 00000010
56 | set8[4] = set8[1]; // 00010010
57 | cout << set8 << endl;
58 |
59 | int numberof1 = set8.count(); // count function returns number of set bits in bitset
60 |
61 | // size function returns total number of bits in bitset so there difference will give us number of unset(0) bits in bitset
62 | int numberof0 = set8.size() - numberof1;
63 | cout << set8 << " has " << numberof1 << " ones and "
64 | << numberof0 << " zeros\n";
65 |
66 | cout << "bool representation of " << set8 << " : ";
67 | for (int i = 0; i < set8.size(); i++)
68 | cout << set8.test(i) << " "; // test function return 1 if bit is set else returns 0
69 |
70 | cout << endl;
71 |
72 | if (!set8.any()) // any function returns true, if atleast 1 bit is set
73 | cout << "set8 has no bit set.\n";
74 |
75 | if (!bset1.any())
76 | cout << "bset1 has no bit set.\n";
77 |
78 | bset1[0]=1;
79 |
80 | // none function returns true, if none of the bits are set
81 | if (!bset1.none())
82 | cout << "bset1 has atleast a bit set\n";
83 |
84 | cout << set8.set() << endl; // bset.set() sets all bits
85 |
86 | cout << set8.set(4, 0) << endl; // bset.set(pos, b) makes bset[pos] = b
87 |
88 | cout << set8.set(4) << endl; // bset.set(pos) makes bset[pos]=1
89 |
90 | // reset function makes all bits 0
91 | cout << set8.reset(2) << endl;
92 | cout << set8.reset() << endl;
93 |
94 | // flip function flips all bits i.e. 1 <-> 0
95 | // and 0 <-> 1
96 | cout << set8.flip(2) << endl;
97 | cout << set8.flip() << endl;
98 |
99 | // Converting decimal number to binary by using bitset
100 | int num = 100;
101 | cout << "\nDecimal number: " << num
102 | << " Binary equivalent: " << bitset<8>(num)< set9(43); //00101011
107 | string s;
108 | s=set9.to_string();
109 | cout<PROBLEMS
142 |
143 |
144 | NOTE!- As such bitset may not feel useful but there are particular sets of problems wherein such properties and function would save a lot of efforts and make things much more simpler.
145 |
--------------------------------------------------------------------------------
/cpp/containers/maps.md:
--------------------------------------------------------------------------------
1 |
2 |
Map
3 |
4 |
5 | Introduction:
6 |
7 | A map is a datastructure to store a key value pair.
8 |
9 | Import:
10 |
11 | ```cpp
12 | #include