├── 2311-longest-binary-subsequence-less-than-or-equal-to-k ├── 2311-longest-binary-subsequence-less-than-or-equal-to-k.cpp ├── NOTES.md └── README.md ├── 875. Koko_Eating_Bananas_Solution_CPP └── Koko_eating_bananas_solution.cpp ├── Algorithms ├── BLogs ├── Blog └── Binary Search.pdf ├── Bubble_Sort.cpp ├── C++ Resources ├── CONTRIBUTING.md ├── CPP Seaching Algorithms ├── Binary Search.cpp └── Linear Search.cpp ├── CSS Animations ├── CodeForces ├── Codeforces Solution ├── 41b ├── 4A_Watermelon.py ├── D_Line.cpp ├── Planet.cpp └── minimum_notation.cpp ├── Convert └── ConvertFtToMm.cpp ├── Determinant_solver.cpp ├── Flood_fill_algo.cpp ├── Gaming Projects ├── Graphs ├── BFS.cpp ├── DFS.cpp ├── Disjisktra.cpp ├── Tarjan_Algorithm.cpp ├── check_star_graph.cpp └── kruskals.cpp ├── Hashing_Techiniques ├── Double_Hashing.c ├── Linear_Probing.c ├── Quadratic_Probing.c └── hashing.c ├── Insertion_sort.cpp ├── Java Resources ├── Java ├── CONTRIBUTING.md ├── kadaneAlgorithm.java ├── queue │ ├── ArrayQueue.java │ ├── LinkedQueue.java │ └── Queue.java └── stack │ ├── ArrayStack.java │ ├── LinkedStack.java │ ├── RPN.java │ └── Stack.java ├── Laptop Price Prediction ├── Leetcode ├── Leetcode.txt ├── MaxSumNonAdjacent.cpp ├── Merge_sort.cpp ├── MyProects ├── Nth_fibonacci_using_Binet'sFormula.cpp ├── Python Resources ├── Quick_sort.cpp ├── README.md ├── React └── myapp │ ├── .gitignore │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt │ ├── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── reportWebVitals.js │ └── setupTests.js │ └── yarn.lock ├── Searching-Algo ├── BFS.c ├── MergeSort.cpp ├── QuickSort.cpp ├── binarysearch.cpp ├── bubllesort.cpp ├── countSort.cpp ├── insertionSort.cpp ├── linearsearch.cpp └── selectionSort.cpp ├── Segment Tree └── segmentTree.cpp ├── Selection_Sort.cpp ├── Slide_Puzzle-Game ├── Readme.md ├── mylinkedlist.h ├── myqueue.h └── solution.cpp ├── Sorting Algos ├── BubbleSort.cpp ├── Counting_Sort.cpp ├── HeapSort.cpp ├── MergeSort.cpp ├── QuickSort.cpp ├── Selection sort.c └── ShellSort.cpp ├── Word Ladder II.cpp ├── css bubbles in cup animation └── index.html ├── lambda_in_cplusplus.cpp ├── leetcode q ├── Climbing_Stairs.cpp ├── FirstandLastPosition.java ├── Interleaving Strings.cpp ├── Subarrays with K Different Integers.cpp ├── Zig_Zag_Conversion.cpp ├── reverseNodes.cpp ├── twosumII.cpp ├── valid-sudoku.cpp └── wildcard_matching.cpp └── sort an array /2311-longest-binary-subsequence-less-than-or-equal-to-k/2311-longest-binary-subsequence-less-than-or-equal-to-k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubsequence(string s, int k) { 4 | 5 | 6 | int ans = 0; 7 | 8 | // reverse to simulate indexing 1001010 => first one has a index of 0 but while forming 9 | // decimal number it will add 2^6 to the result. 10 | // So, reverse the string to get the actual indexing 11 | // reverse = 0101001 12 | // now the last one has a index of 6 and it will contribute 2^6, 13 | 14 | reverse(s.begin(), s.end()); 15 | 16 | for(int i = 0; i < s.size(); i++) 17 | { 18 | // add all zeroes as the previous one's add according to the one and the latter zeroes 19 | // act as leading zeroes 20 | if (s[i] == '0') ans++; 21 | 22 | // bit manipulation to check the maximum 23 | else if (i < 31) 24 | { 25 | // if k is greater, then that 1 bit counts 26 | if (k >= (1 << i)) 27 | { 28 | k -= (1 << i); 29 | ans++; 30 | } 31 | } 32 | } 33 | 34 | return ans; 35 | } 36 | }; -------------------------------------------------------------------------------- /2311-longest-binary-subsequence-less-than-or-equal-to-k/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /2311-longest-binary-subsequence-less-than-or-equal-to-k/README.md: -------------------------------------------------------------------------------- 1 |

2311. Longest Binary Subsequence Less Than or Equal to K

Medium


You are given a binary string s and a positive integer k.

2 | 3 |

Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.

4 | 5 |

Note:

6 | 7 | 12 | 13 |

 

14 |

Example 1:

15 | 16 |
Input: s = "1001010", k = 5
17 | Output: 5
18 | Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
19 | Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
20 | The length of this subsequence is 5, so 5 is returned.
21 | 
22 | 23 |

Example 2:

24 | 25 |
Input: s = "00101001", k = 1
26 | Output: 6
27 | Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
28 | The length of this subsequence is 6, so 6 is returned.
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 | 39 |
-------------------------------------------------------------------------------- /875. Koko_Eating_Bananas_Solution_CPP/Koko_eating_bananas_solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | long int time(vector piles, long int m){ 5 | 6 | long int cnt=0; 7 | for(auto p:piles){ 8 | cnt+=(p+m-1)/m; 9 | } 10 | return cnt; 11 | } 12 | int minEatingSpeed(vector& piles, int h) { 13 | sort(piles.begin(), piles.end()); 14 | long long int l = 1, r = piles[piles.size()-1]; 15 | while (l <= r) { 16 | long int m = l+ (r-l)/2, total = 0; 17 | 18 | total=time(piles,m); 19 | if (total > h) 20 | l = m + 1; 21 | else 22 | r = m-1; 23 | } 24 | return l; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms: -------------------------------------------------------------------------------- 1 | // Q84 https://leetcode.com/problems/lfu-cache/ 2 | 3 | struct Node{ 4 | int key,value,cnt; 5 | Node *next; 6 | Node* prev; 7 | Node(int _key,int _value){ 8 | key=_key; 9 | value=_value; 10 | cnt=1; 11 | } 12 | }; 13 | struct List{ 14 | int size; 15 | Node *head; 16 | Node* tail; 17 | List(){ 18 | head =new Node(0,0); 19 | tail= new Node(0,0); 20 | head->next=tail; 21 | tail->prev=head; 22 | size=0; 23 | } 24 | void addFront(Node* newnode){ 25 | Node*t=head->next; 26 | newnode->next=t; 27 | newnode->prev=head; 28 | head->next=newnode; 29 | t->prev=newnode; 30 | size++; 31 | } 32 | 33 | void removeNode(Node* delnode){ 34 | Node* delprev=delnode->prev; 35 | Node* delnext=delnode->next; 36 | delprev->next=delnext; 37 | delnext->prev=delprev; 38 | size--; 39 | } 40 | }; 41 | 42 | class LFUCache { 43 | map keyNode; 44 | mapfreqListMap; 45 | int maxsize; 46 | int minfreq; 47 | int cursize; 48 | public: 49 | LFUCache(int capacity) { 50 | maxsize=capacity; 51 | minfreq=0; 52 | cursize=0; 53 | } 54 | 55 | void updateFreqListMap(Node *node){ 56 | keyNode.erase(node->key); 57 | freqListMap[node->cnt]->removeNode(node); 58 | if(node->cnt==minfreq&&freqListMap[node->cnt]->size==0){ 59 | minfreq++; 60 | } 61 | 62 | List* nextHigherFreqList=new List(); 63 | if(freqListMap.find(node->cnt+1)!=freqListMap.end()){ 64 | nextHigherFreqList=freqListMap[node->cnt+1]; 65 | } 66 | node->cnt++; 67 | nextHigherFreqList->addFront(node); 68 | freqListMap[node->cnt]=nextHigherFreqList; 69 | keyNode[node->key]=node; 70 | } 71 | 72 | int get(int key) { 73 | if(keyNode.find(key)!=keyNode.end()){ 74 | Node* node=keyNode[key]; 75 | int val=node->value; 76 | updateFreqListMap(node); 77 | return val; 78 | } 79 | return -1; 80 | } 81 | 82 | void put(int key, int value) { 83 | if(maxsize==0) 84 | return; 85 | if(keyNode.find(key)!=keyNode.end()){ 86 | Node* node=keyNode[key]; 87 | node->value=value; 88 | updateFreqListMap(node); 89 | } 90 | else{ 91 | if(cursize==maxsize){ 92 | List *list=freqListMap[minfreq]; 93 | keyNode.erase(list->tail->prev->key); 94 | freqListMap[minfreq]->removeNode(list->tail->prev); 95 | cursize--; 96 | } 97 | cursize++; 98 | minfreq=1; 99 | List *listFreq=new List(); 100 | if(freqListMap.find(minfreq)!=freqListMap.end()){ 101 | listFreq=freqListMap[minfreq]; 102 | } 103 | 104 | Node* node=new Node(key,value); 105 | listFreq->addFront(node); 106 | keyNode[key]=node; 107 | freqListMap[minfreq]=listFreq; 108 | 109 | 110 | } 111 | } 112 | }; 113 | // int maxsize; 114 | // int minfreq; 115 | // int cursize; 116 | 117 | // int maxSizeCache; 118 | // int minFreq; 119 | // int curSize; 120 | /** 121 | * Your LFUCache object will be instantiated and called as such: 122 | * LFUCache* obj = new LFUCache(capacity); 123 | * int param_1 = obj->get(key); 124 | * obj->put(key,value); 125 | */ 126 | -------------------------------------------------------------------------------- /BLogs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Blog/Binary Search.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fabayu/HACKTOBERFEST-2022/df116160c911e8ca2f2bdd7c1d56efb1596617ed/Blog/Binary Search.pdf -------------------------------------------------------------------------------- /Bubble_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std ; 3 | 4 | int bubble_sort(int arr[] , int n) 5 | { 6 | for(int i=1; i arr[j+1]) 13 | { 14 | swap(arr[j] , arr[j+1]) ; 15 | swapped = true ; 16 | } 17 | } 18 | 19 | if(swapped = false) 20 | { 21 | break ; 22 | } 23 | } 24 | return arr[5] ; 25 | } 26 | 27 | int main() 28 | { 29 | int arr[50] = { 4,3,2,1 } ; 30 | int size = 4 ; 31 | 32 | bubble_sort(arr , size) ; 33 | 34 | for(int i=0; i<4; i++) 35 | { 36 | cout<How to contribute to open source - Complete Guide by Eddie Jaoude. 42 | - How NOT to contribute to open source on GitHub - (5 tips) by Eddie Jaoude. 43 | - How to keep your GitHub Fork in-sync and up to date by Eddie Jaoude 44 | 45 | ### Need more help? 🤔 46 | 47 | You can refer to the following articles on basics of Git and Github and also contact me, in case you are stuck: 48 | 49 | - Forking a Repo 50 | - Cloning a Repo 51 | - How to create a Pull Request 52 | - Getting started with Git and GitHub 53 | - Learn GitHub from Scratch 54 | 55 | ### Thank you for reading and Happy Coding. 🤩 -------------------------------------------------------------------------------- /CPP Seaching Algorithms/Binary Search.cpp: -------------------------------------------------------------------------------- 1 | // Contributed by Sanjoy Saha [github : SanjoySaha24] 2 | 3 | #include 4 | using namespace std; 5 | int binarySearch(int myarray[], int beg, int end, int key) 6 | { 7 | int mid; 8 | if(end >= beg) { 9 | mid = (beg + end)/2; 10 | if(myarray[mid] == key) 11 | { 12 | return mid+1; 13 | } 14 | else if(myarray[mid] < key) { 15 | return binarySearch(myarray,mid+1,end,key); 16 | } 17 | else { 18 | return binarySearch(myarray,beg,mid-1,key); 19 | } 20 | } 21 | return -1; 22 | } 23 | int main () 24 | { 25 | int myarray[10] = {5,8,10,13,21,23,25,43,54,75}; 26 | int key, location=-1; 27 | cout<<"The input array is"<>key; 33 | location = binarySearch(myarray, 0, 9, key); 34 | if(location != -1) { 35 | cout<<"Key found at location "< 4 | using namespace std; 5 | int main() 6 | { 7 | int myarray[10] = {21,43,23,54,75,13,5,8,25,10}; 8 | int key,loc; 9 | cout<<"The input array is"<>key; 15 | for (int i = 0; i< 10; i++) 16 | { 17 | if(myarray[i] == key) 18 | { 19 | loc = i+1; 20 | break; 21 | } 22 | else 23 | loc = 0; 24 | } 25 | if(loc != 0) 26 | { 27 | cout<<"Key found at position "< 12 | using namespace std; 13 | 14 | #define nl "\n" 15 | #define ll long long int 16 | #define INF 1e9 17 | 18 | void solve() 19 | { 20 | int n; 21 | cin >> n; 22 | int points[3] = {2, (n - 2) / 3 + ((n - 2) % 3 > 0) + 2, n}; 23 | int segments[3] = {1, points[1] - points[0] - 1, points[2] - points[1] - 1}; 24 | cout << min({abs(segments[0] - segments[1]), abs(segments[1] - segments[2]), abs(segments[2] - segments[0])}) << nl; 25 | } 26 | 27 | int main() 28 | { 29 | ios_base::sync_with_stdio(false); 30 | cin.tie(NULL); 31 | int T = 1; 32 | cin >> T; 33 | for (int t = 1; t <= T; t++) 34 | { 35 | solve(); 36 | } 37 | } 38 | 39 | Problem B - https://codeforces.com/contest/1735/problem/B 40 | 41 | Idea - 42 | 43 | It is obvious that we have to consider the smallest element always since it can not become larger to meet the problem's description. Now we need to make rest of all the elements strictly less than twice. We know the largest number that can satisfy our contraints would be "2 * smallest_element - 1". Let's call this number X. So idea was to make all the elements smaller or equal to that number but larger or equal to the smallest_element (This was my thinking, the problem constraints required that for every pair the bigger number is strictly less than twice of the smaller number). Now if I divide the current element by X and adding 1 if there is a remainder it'll give me smallest factor of X larger or equal to current element. The remainder can then be simply distributed among these elements leading to a possible solution. 44 | 45 | Code - 46 | 47 | #include 48 | using namespace std; 49 | 50 | #define nl "\n" 51 | #define ll long long int 52 | #define INF 1e9 53 | 54 | void solve() 55 | { 56 | int n; 57 | cin >> n; 58 | int a[n]; 59 | for (int &x : a) 60 | cin >> x; 61 | ll minVal = 2 * a[0] - 1, ans = 0; 62 | for (int &x : a) 63 | ans += x / minVal + (x % minVal > 0) - 1; 64 | cout << ans << nl; 65 | } 66 | 67 | int main() 68 | { 69 | ios_base::sync_with_stdio(false); 70 | cin.tie(NULL); 71 | int T = 1; 72 | cin >> T; 73 | for (int t = 1; t <= T; t++) 74 | { 75 | solve(); 76 | } 77 | } 78 | 79 | Problem C - https://codeforces.com/contest/1735/problem/C 80 | 81 | Idea - 82 | 83 | It is obvious that we want each character of the string to be preceded by the smallest possible character to give the lexographically smallest string. The problem with this was there if we proceed this way only there may be configuration of characters such that they create a cycle of length less than 26. So to fix this, we'll just check if adding the smallest unassigned character is leading to a cycle or not by simply performing a dfs in reverse direction and returning whether we are reaching the current smallest character or not. If yes, skip to next character otherwise assign it to current character. We'll do this until we have assigned 25 characters and only 1 character is remaining which will complete our cycle of 26 characters. 84 | 85 | Code - 86 | 87 | #include 88 | using namespace std; 89 | 90 | #define nl "\n" 91 | #define ll long long int 92 | #define INF 1e9 93 | 94 | bool dfs(char curr, const char &target, const vector &v) 95 | { 96 | if (curr == target) 97 | return true; 98 | if (v[curr - 'a'] == -1) 99 | return false; 100 | return dfs(v[curr - 'a'] + 'a', target, v); 101 | } 102 | 103 | void solve() 104 | { 105 | int n; 106 | cin >> n; 107 | string s; 108 | cin >> s; 109 | set st; 110 | for (int i = 0; i < 26; i++) 111 | st.insert('a' + i); 112 | vector v(26, -1); 113 | for (int i = 0; i < n; i++) 114 | { 115 | if (v[s[i] - 'a'] != -1) 116 | continue; 117 | char c; 118 | for (auto &x : st) 119 | if (st.size() == 1 || !dfs(x, s[i], v)) 120 | { 121 | c = x; 122 | break; 123 | } 124 | v[s[i] - 'a'] = c - 'a'; 125 | st.erase(c); 126 | } 127 | for (int i = 0; i < n; i++) 128 | cout << char(v[s[i] - 'a'] + 'a'); 129 | cout << nl; 130 | } 131 | 132 | int main() 133 | { 134 | ios_base::sync_with_stdio(false); 135 | cin.tie(NULL); 136 | int T = 1; 137 | cin >> T; 138 | for (int t = 1; t <= T; t++) 139 | { 140 | solve(); 141 | } 142 | } 143 | 144 | Problem D - https://codeforces.com/contest/1735/problem/D 145 | 146 | Idea - 147 | 148 | The idea was to find for each pair of cards present on the table, the other card that will complete the set. If it is present on the table, just incremenet the count of sets formed by taking that card by 1. Then it is a simple combinatorics problem of selecting 2 out of available sets by simply calculating count_of_sets*(count_of_sets-1)/2. 149 | 150 | Code - 151 | 152 | #include 153 | using namespace std; 154 | 155 | #define nl "\n" 156 | #define ll long long int 157 | #define INF 1e9 158 | 159 | long long power(long long num, long long pw) 160 | { 161 | ll res = 1; 162 | while (pw) 163 | { 164 | if (pw & 1) 165 | res *= num; 166 | num *= num; 167 | pw /= 2; 168 | } 169 | return res; 170 | } 171 | 172 | void solve() 173 | { 174 | int n, k; 175 | cin >> n >> k; 176 | vector> a(n, vector(k)); 177 | for (int i = 0; i < n; i++) 178 | for (int j = 0; j < k; j++) 179 | cin >> a[i][j]; 180 | map mp; 181 | for (int i = 0; i < n; i++) 182 | { 183 | ll num = 0; 184 | for (int j = 0; j < k; j++) 185 | num += a[i][j] * power(3, j); 186 | mp[num] = 0; 187 | } 188 | for (int i = 0; i < n; i++) 189 | for (int j = i + 1; j < n; j++) 190 | { 191 | ll sum = 0; 192 | for (int l = 0; l < k; l++) 193 | if (a[i][l] == a[j][l]) 194 | sum += a[i][l] * power(3, l); 195 | else 196 | sum += (3 - a[i][l] - a[j][l]) * power(3, l); 197 | if (mp.count(sum)) 198 | mp[sum]++; 199 | } 200 | 201 | ll ans = 0; 202 | for (auto &x : mp) 203 | ans += x.second * (x.second - 1) / 2; 204 | cout << ans << nl; 205 | } 206 | 207 | int main() 208 | { 209 | ios_base::sync_with_stdio(false); 210 | cin.tie(NULL); 211 | int T = 1; 212 | for (int t = 1; t <= T; t++) 213 | { 214 | solve(); 215 | } 216 | } -------------------------------------------------------------------------------- /Codeforces Solution/41b: -------------------------------------------------------------------------------- 1 | // Problem link: https://codeforces.com/problemset/problem/41/B 2 | #include 3 | using namespace std; 4 | 5 | const int MOD = 1e9 + 7; 6 | const int N = 1e6 + 5; 7 | 8 | int a[N], m[N]; 9 | 10 | int main() { 11 | ios_base::sync_with_stdio(false); 12 | cin.tie(NULL); cout.tie(NULL); 13 | 14 | int n, b; cin >> n >> b; 15 | for (int i = 1; i <= n; ++i) cin >> a[i]; 16 | 17 | for (int i = n; i >= 0; --i) m[i] = max(m[i + 1], a[i]); 18 | 19 | int ans = b; 20 | for (int i = 1; i <= n; ++i) { 21 | ans = max(ans, b % a[i] + b / a[i] * m[i + 1]); 22 | } 23 | 24 | cout << (n == 1 ? b : ans); 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Codeforces Solution/4A_Watermelon.py: -------------------------------------------------------------------------------- 1 | w = int(input()) 2 | if w%2 == 0 and w != 2: 3 | print("YES") 4 | else: 5 | print("NO") 6 | -------------------------------------------------------------------------------- /Codeforces Solution/D_Line.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | #define l long 5 | void findCount(){ 6 | l int n; 7 | cin>>n; 8 | string s; 9 | cin>>s; 10 | ll int sum=0; 11 | ll int arr[n]; 12 | for(int i=0;i()); 23 | for(int i=0;i0){ 25 | sum+=arr[i]; 26 | } 27 | cout<>t; 37 | while(t--){ 38 | findCount(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Codeforces Solution/Planet.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | using namespace std; 4 | int main() 5 | { 6 | int T; 7 | cin >> T; 8 | while (T--) 9 | { 10 | int n,c; 11 | cin >> n >> c; 12 | int a[n]; 13 | mapmp; 14 | for (int i = 0; i < n; i++) 15 | { 16 | cin >> a[i]; 17 | mp[a[i]]++; 18 | } 19 | int ans = 0; 20 | for(auto it:mp) 21 | { 22 | ans=ans+min(it.second,c); 23 | } 24 | cout << ans << endl; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Codeforces Solution/minimum_notation.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link - https://codeforces.com/problemset/problem/1730/C 2 | 3 | #include 4 | using namespace std; 5 | 6 | #define nl "\n" 7 | #define ll long long int 8 | #define INF 1e9 9 | 10 | void solve() 11 | { 12 | string s; 13 | cin >> s; 14 | map mp; 15 | for (auto &digit : s) 16 | mp[digit - '0']++; 17 | 18 | int n = s.length(); 19 | // string ans = ""; 20 | priority_queue, greater> pq; 21 | 22 | for (auto &digit : s) 23 | { 24 | if (digit - '0' == mp.begin()->first) 25 | { 26 | while (!pq.empty() && pq.top() <= digit - '0') 27 | cout << pq.top(), pq.pop(); 28 | cout << digit; 29 | } 30 | else 31 | { 32 | pq.push(min(digit - '0' + 1, 9)); 33 | } 34 | mp[digit - '0']--; 35 | if (mp[digit - '0'] == 0) 36 | mp.erase(digit - '0'); 37 | } 38 | while (!pq.empty()) 39 | cout << pq.top(), pq.pop(); 40 | cout << nl; 41 | } 42 | 43 | int main() 44 | { 45 | ios_base::sync_with_stdio(false); 46 | cin.tie(NULL); 47 | int T = 1; 48 | cin >> T; 49 | for (int t = 1; t <= T; t++) 50 | { 51 | solve(); 52 | } 53 | } -------------------------------------------------------------------------------- /Convert/ConvertFtToMm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | const double milimeter = 384.9; 8 | int feet; 9 | double hasil; 10 | 11 | cout<<"Konversi Kaki (ft) ke Milimeter (mm)"<>feet; 14 | 15 | hasil = feet * milimeter; 16 | 17 | cout<<"Hasil = "< 2 | #include 3 | using namespace std; 4 | int determinant( int matrix[10][10], int n) { 5 | int det = 0; 6 | int submatrix[10][10]; 7 | if (n == 2) 8 | return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1])); 9 | else { 10 | for (int x = 0; x < n; x++) { 11 | int subi = 0; 12 | for (int i = 1; i < n; i++) { 13 | int subj = 0; 14 | for (int j = 0; j < n; j++) { 15 | if (j == x) 16 | continue; 17 | submatrix[subi][subj] = matrix[i][j]; 18 | subj++; 19 | } 20 | subi++; 21 | } 22 | det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 )); 23 | } 24 | } 25 | return det; 26 | } 27 | int main() { 28 | int n, i, j; 29 | int matrix[10][10]; 30 | cout << "Enter the size of the matrix:\n"; 31 | cin >> n; 32 | cout << "Enter the elements of the matrix:\n"; 33 | for (i = 0; i < n; i++) 34 | for (j = 0; j < n; j++) 35 | cin >> matrix[i][j]; 36 | cout<<"The entered matrix is:"< 2 | using namespace std; 3 | bool isValid(int screen[][8], int m, int n, int x, int y, int prevC, int newC) 4 | { 5 | if(x < 0 || x >= m || y < 0 || y >= n || screen[x][y] != prevC 6 | || screen[x][y]== newC) 7 | return false; 8 | return true; 9 | } 10 | void floodFill(int screen[][8], int m, int n, int x, int y, int prevC, int newC) 11 | { 12 | vector> queue; 13 | pair p(x,y); 14 | queue.push_back(p); 15 | screen[x][y] = newC; 16 | while(queue.size() > 0) 17 | { 18 | pair currPixel = queue[queue.size() - 1]; 19 | queue.pop_back(); 20 | 21 | int posX = currPixel.first; 22 | int posY = currPixel.second; 23 | if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) 24 | { 25 | screen[posX + 1][posY] = newC; 26 | p.first = posX + 1; 27 | p.second = posY; 28 | queue.push_back(p); 29 | } 30 | 31 | if(isValid(screen, m, n, posX-1, posY, prevC, newC)) 32 | { 33 | screen[posX-1][posY]= newC; 34 | p.first = posX-1; 35 | p.second = posY; 36 | queue.push_back(p); 37 | } 38 | 39 | if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) 40 | { 41 | screen[posX][posY + 1]= newC; 42 | p.first = posX; 43 | p.second = posY + 1; 44 | queue.push_back(p); 45 | } 46 | 47 | if(isValid(screen, m, n, posX, posY-1, prevC, newC)) 48 | { 49 | screen[posX][posY-1]= newC; 50 | p.first = posX; 51 | p.second = posY-1; 52 | queue.push_back(p); 53 | } 54 | } 55 | } 56 | 57 | int main() 58 | { 59 | int screen[][8] ={ 60 | {1, 1, 1, 1, 1, 1, 1, 1}, 61 | {1, 1, 1, 1, 1, 1, 0, 0}, 62 | {1, 0, 0, 1, 1, 0, 1, 1}, 63 | {1, 2, 2, 2, 2, 0, 1, 0}, 64 | {1, 1, 1, 2, 2, 0, 1, 0}, 65 | {1, 1, 1, 2, 2, 2, 2, 0}, 66 | {1, 1, 1, 1, 1, 2, 1, 1}, 67 | {1, 1, 1, 1, 1, 2, 2, 1}}; 68 | int m = 8; 69 | int n = 8; 70 | int x = 4; 71 | int y = 4; 72 | int prevC = screen[x][y]; 73 | int newC = 3; 74 | floodFill(screen, m, n, x, y, prevC, newC); 75 | for(int i = 0; i < m; i++) 76 | { 77 | for(int j = 0; j < n; j++) 78 | { 79 | cout << screen[i][j] << " "; 80 | } 81 | cout << endl; 82 | } 83 | 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /Gaming Projects: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Graphs/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bfs(vector> &graph, int source, vector &vis) 5 | { 6 | queue q; 7 | q.push(source); 8 | vis[source] = true; 9 | while (!q.empty()) 10 | { 11 | int curr = q.front(); 12 | q.pop(); 13 | cout << curr << " "; 14 | for (int neigh : graph[curr]) 15 | if (!vis[neigh]) 16 | { 17 | q.push(neigh); 18 | vis[neigh] = true; 19 | } 20 | } 21 | } 22 | 23 | int main() 24 | { 25 | int n, e; 26 | cout << "Enter the Number of Nodes : " << endl; 27 | cin >> n; 28 | cout << "Enter the number of Edges : " << endl; 29 | cin >> e; 30 | vector> graph(n); 31 | vector vis(n, false); 32 | for (int i = 0; i < e; i++) 33 | { 34 | int u, v; 35 | cin >> u >> v; 36 | graph[u].push_back(v); 37 | graph[v].push_back(u); 38 | } 39 | for (int i = 0; i < n; i++) 40 | { 41 | if (!vis[i]) 42 | bfs(graph, i, vis); 43 | } 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Graphs/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void dfs(vector> &graph, int source, vector &vis) 5 | { 6 | cout << source << " "; 7 | vis[source] = true; 8 | for (int neigh : graph[source]) 9 | if (!vis[neigh]) 10 | dfs(graph, neigh, vis); 11 | } 12 | 13 | int main() 14 | { 15 | int n, e; 16 | cin >> n >> e; 17 | vector> graph(n); 18 | vector vis(n, false); 19 | for (int i = 0; i < e; i++) 20 | { 21 | int u, v; 22 | cin >> u >> v; 23 | graph[u].push_back(v); 24 | graph[v].push_back(u); 25 | } 26 | for (int i = 0; i < n; i++) 27 | { 28 | if (!vis[i]) 29 | dfs(graph, i, vis); 30 | } 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Graphs/Disjisktra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void dijisktra(vector>> &adj, int source) 5 | { 6 | int n = adj.size(); 7 | vector vis(n, false); 8 | vector dis(n, INT_MAX); 9 | set> st; 10 | 11 | st.insert({0, source}); 12 | dis[source] = 0; 13 | 14 | while (st.size() > 0) 15 | { 16 | auto node = *st.begin(); 17 | int v = node.second; 18 | int v_dis = node.first; 19 | st.erase(st.begin()); 20 | if (vis[v]) 21 | continue; 22 | vis[v] = true; 23 | for (auto neigh : adj[v]) 24 | { 25 | int neigh_v = neigh.first; 26 | int neigh_wt = neigh.second; 27 | if (dis[v] + neigh_wt < dis[neigh_v]) 28 | { 29 | dis[neigh_v] = dis[v] + neigh_wt; 30 | st.insert({dis[neigh_v], neigh_v}); 31 | } 32 | } 33 | } 34 | for (int i = 0; i < n; i++) 35 | cout << "distance from " << source << " to " << i << " is : - > " << dis[i] << endl; 36 | } 37 | int main() 38 | { 39 | int n, m; 40 | cout << "Enter Number of Nodes" << endl; 41 | cin >> n; 42 | cout << "Enter number of edges" << endl; 43 | cin >> m; 44 | vector>> adj(n); 45 | for (int i = 0; i < m; i++) 46 | { 47 | int u, v, w; 48 | cin >> u >> v >> w; 49 | adj[u].push_back({v, w}); 50 | } 51 | int source; 52 | cin >> source; 53 | dijisktra(adj, source); 54 | return 0; 55 | } 56 | // 0 1 4 0 7 8 1 2 8 1 7 1 2 3 7 2 8 2 2 5 4 3 4 9 3 5 1 4 5 1 5 6 2 6 7 1 6 8 6 7 8 7 -------------------------------------------------------------------------------- /Graphs/Tarjan_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define NIL -1 5 | using namespace std; 6 | 7 | // A class that represents an directed graph 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | list *adj; // A dynamic array of adjacency lists 12 | 13 | // A Recursive DFS based function used by SCC() 14 | void SCCUtil(int u, int disc[], int low[], 15 | stack *st, bool stackMember[]); 16 | public: 17 | Graph(int V); // Constructor 18 | void addEdge(int v, int w); // function to add an edge to graph 19 | void SCC(); // prints strongly connected components 20 | }; 21 | 22 | Graph::Graph(int V) 23 | { 24 | this->V = V; 25 | adj = new list[V]; 26 | } 27 | 28 | void Graph::addEdge(int v, int w) 29 | { 30 | adj[v].push_back(w); 31 | } 32 | 33 | // A recursive function that finds and prints strongly connected 34 | // components using DFS traversal 35 | // u --> The vertex to be visited next 36 | // disc[] --> Stores discovery times of visited vertices 37 | // low[] -- >> earliest visited vertex (the vertex with minimum 38 | // discovery time) that can be reached from subtree 39 | // rooted with current vertex 40 | // *st -- >> To store all the connected ancestors (could be part 41 | // of SCC) 42 | // stackMember[] --> bit/index array for faster check whether 43 | // a node is in stack 44 | void Graph::SCCUtil(int u, int disc[], int low[], stack *st, 45 | bool stackMember[]) 46 | { 47 | // A static variable is used for simplicity, we can avoid use 48 | // of static variable by passing a pointer. 49 | static int time = 0; 50 | 51 | // Initialize discovery time and low value 52 | disc[u] = low[u] = ++time; 53 | st->push(u); 54 | stackMember[u] = true; 55 | 56 | // Go through all vertices adjacent to this 57 | list::iterator i; 58 | for (i = adj[u].begin(); i != adj[u].end(); ++i) 59 | { 60 | int v = *i; // v is current adjacent of 'u' 61 | 62 | // If v is not visited yet, then recur for it 63 | if (disc[v] == -1) 64 | { 65 | SCCUtil(v, disc, low, st, stackMember); 66 | 67 | // Check if the subtree rooted with 'v' has a 68 | // connection to one of the ancestors of 'u' 69 | // Case 1 (per above discussion on Disc and Low value) 70 | low[u] = min(low[u], low[v]); 71 | } 72 | 73 | // Update low value of 'u' only of 'v' is still in stack 74 | // (i.e. it's a back edge, not cross edge). 75 | // Case 2 (per above discussion on Disc and Low value) 76 | else if (stackMember[v] == true) 77 | low[u] = min(low[u], disc[v]); 78 | } 79 | 80 | // head node found, pop the stack and print an SCC 81 | int w = 0; // To store stack extracted vertices 82 | if (low[u] == disc[u]) 83 | { 84 | while (st->top() != u) 85 | { 86 | w = (int) st->top(); 87 | cout << w << " "; 88 | stackMember[w] = false; 89 | st->pop(); 90 | } 91 | w = (int) st->top(); 92 | cout << w << "\n"; 93 | stackMember[w] = false; 94 | st->pop(); 95 | } 96 | } 97 | 98 | // The function to do DFS traversal. It uses SCCUtil() 99 | void Graph::SCC() 100 | { 101 | int *disc = new int[V]; 102 | int *low = new int[V]; 103 | bool *stackMember = new bool[V]; 104 | stack *st = new stack(); 105 | 106 | // Initialize disc and low, and stackMember arrays 107 | for (int i = 0; i < V; i++) 108 | { 109 | disc[i] = NIL; 110 | low[i] = NIL; 111 | stackMember[i] = false; 112 | } 113 | 114 | // Call the recursive helper function to find strongly 115 | // connected components in DFS tree with vertex 'i' 116 | for (int i = 0; i < V; i++) 117 | if (disc[i] == NIL) 118 | SCCUtil(i, disc, low, st, stackMember); 119 | } 120 | 121 | // Driver program to test above function 122 | int main() 123 | { 124 | cout << "\nSCCs in first graph \n"; 125 | Graph g1(5); 126 | g1.addEdge(1, 0); 127 | g1.addEdge(0, 2); 128 | g1.addEdge(2, 1); 129 | g1.addEdge(0, 3); 130 | g1.addEdge(3, 4); 131 | g1.SCC(); 132 | 133 | cout << "\nSCCs in second graph \n"; 134 | Graph g2(4); 135 | g2.addEdge(0, 1); 136 | g2.addEdge(1, 2); 137 | g2.addEdge(2, 3); 138 | g2.SCC(); 139 | 140 | cout << "\nSCCs in third graph \n"; 141 | Graph g3(7); 142 | g3.addEdge(0, 1); 143 | g3.addEdge(1, 2); 144 | g3.addEdge(2, 0); 145 | g3.addEdge(1, 3); 146 | g3.addEdge(1, 4); 147 | g3.addEdge(1, 6); 148 | g3.addEdge(3, 5); 149 | g3.addEdge(4, 5); 150 | g3.SCC(); 151 | 152 | cout << "\nSCCs in fourth graph \n"; 153 | Graph g4(11); 154 | g4.addEdge(0,1);g4.addEdge(0,3); 155 | g4.addEdge(1,2);g4.addEdge(1,4); 156 | g4.addEdge(2,0);g4.addEdge(2,6); 157 | g4.addEdge(3,2); 158 | g4.addEdge(4,5);g4.addEdge(4,6); 159 | g4.addEdge(5,6);g4.addEdge(5,7);g4.addEdge(5,8);g4.addEdge(5,9); 160 | g4.addEdge(6,4); 161 | g4.addEdge(7,9); 162 | g4.addEdge(8,9); 163 | g4.addEdge(9,8); 164 | g4.SCC(); 165 | 166 | cout << "\nSCCs in fifth graph \n"; 167 | Graph g5(5); 168 | g5.addEdge(0,1); 169 | g5.addEdge(1,2); 170 | g5.addEdge(2,3); 171 | g5.addEdge(2,4); 172 | g5.addEdge(3,0); 173 | g5.addEdge(4,2); 174 | g5.SCC(); 175 | 176 | return 0; 177 | } 178 | 179 | -------------------------------------------------------------------------------- /Graphs/check_star_graph.cpp: -------------------------------------------------------------------------------- 1 | // CPP to find whether given graph is star or not 2 | #include 3 | using namespace std; 4 | 5 | // define the size of incidence matrix 6 | #define size 4 7 | 8 | // function to find star graph 9 | bool checkStar(int mat[][size]) 10 | { 11 | // initialize number of vertex 12 | // with deg 1 and n-1 13 | int vertexD1 = 0, vertexDn_1 = 0; 14 | 15 | // check for S1 16 | if (size == 1) 17 | return (mat[0][0] == 0); 18 | 19 | // check for S2 20 | if (size == 2) 21 | return (mat[0][0] == 0 && mat[0][1] == 1 && 22 | mat[1][0] == 1 && mat[1][1] == 0 ); 23 | 24 | // check for Sn (n>2) 25 | for (int i = 0; i < size; i++) 26 | { 27 | int degreeI = 0; 28 | for (int j = 0; j < size; j++) 29 | if (mat[i][j]) 30 | degreeI++; 31 | 32 | if (degreeI == 1) 33 | vertexD1++; 34 | else if (degreeI == size-1) 35 | vertexDn_1++; 36 | } 37 | 38 | return (vertexD1 == (size-1) && 39 | vertexDn_1 == 1); 40 | } 41 | 42 | // driver code 43 | int main() 44 | { 45 | int mat[size][size] = { {0, 1, 1, 1}, 46 | {1, 0, 0, 0}, 47 | {1, 0, 0, 0}, 48 | {1, 0, 0, 0}}; 49 | 50 | checkStar(mat) ? cout << "Star Graph" : 51 | cout << "Not a Star Graph"; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Graphs/kruskals.cpp: -------------------------------------------------------------------------------- 1 | // Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the subset of the edges of that graph which 2 | 3 | // ->form a tree that includes every vertex 4 | // ->has the minimum sum of weights among all the trees that can be formed from the graph 5 | // We start from the edges with the lowest weight and keep adding edges until we reach our goal. 6 | 7 | // The steps for implementing Kruskal's algorithm are as follows: 8 | 9 | // Sort all the edges from low weight to high 10 | // Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle, then reject this edge. 11 | // Keep adding edges until we reach all vertices. 12 | 13 | // Any minimum spanning tree algorithm revolves around checking if adding an edge creates a loop or not. 14 | #include 15 | using namespace std; 16 | #define edge pair 17 | 18 | int find_set(int u, vector parent) 19 | { 20 | // If i is the parent of itself 21 | if (parent[u] == u) 22 | return u; 23 | // Else if i is not the parent of itself 24 | // Then i is not the representative of his set, 25 | // so we recursively call Find on its parent 26 | return find_set(parent[u], parent); 27 | } 28 | 29 | // Making two nodes of same set 30 | void union_set(int u, int v, vector &parent) 31 | { 32 | parent[u] = parent[v]; 33 | } 34 | 35 | void kruskals(vector> &Graph, vector> &MST, int n) 36 | { 37 | // Making Parent Vector 38 | vector parent(n, 0); 39 | for (int i = 0; i < n; i++) 40 | { 41 | parent[i] = i; 42 | } 43 | // Graph will sorted by weights 44 | sort(Graph.begin(), Graph.end()); 45 | 46 | // Now we will iterate edges in increasing order and add them in the MST if there is not a cycle 47 | for (int i = 0; i < Graph.size(); i++) 48 | { 49 | pair edg = Graph[i]; 50 | 51 | int uParent = find_set(edg.second.first, parent); 52 | int vParent = find_set(edg.second.second, parent); 53 | if (uParent != vParent) 54 | { 55 | MST.push_back(Graph[i]); 56 | // parent[uParent] = parent[vParent]; 57 | union_set(uParent, vParent, parent); 58 | } 59 | } 60 | } 61 | 62 | void print(vector> MST) 63 | { 64 | cout << "Edge :" 65 | << " Weight" << endl; 66 | for (int i = 0; i < MST.size(); i++) 67 | { 68 | cout << MST[i].second.first << " - " << MST[i].second.second << " : " 69 | << MST[i].first; 70 | cout << endl; 71 | } 72 | } 73 | 74 | int main() 75 | { 76 | int n, e; 77 | cout << "Enter Number of nodes and number of edges" << endl; 78 | cin >> n >> e; 79 | vector> Graph; 80 | vector> MST; 81 | for (int i = 0; i < e; i++) 82 | { 83 | int u, v, w; 84 | cin >> u >> v >> w; 85 | Graph.push_back({w, {u, v}}); 86 | } 87 | kruskals(Graph, MST, n); 88 | print(MST); 89 | return 0; 90 | } -------------------------------------------------------------------------------- /Hashing_Techiniques/Double_Hashing.c: -------------------------------------------------------------------------------- 1 | //Double Hashing [ Closed Hashing ( Open Addressing ) ] 2 | 3 | //Quadratic Probing [ Closed Hashing ( Open Addressing ) ] 4 | 5 | #include 6 | #define SIZE 10 7 | #define PRIME 7 //used in Second Hash Function 8 | 9 | //Hash Function 10 | int hash1 (int key) //1st Hash Function 11 | { 12 | return key % SIZE; 13 | } 14 | 15 | int hash2 (int key) //2nd Hash Function 16 | { 17 | return (PRIME - (key % PRIME)); 18 | } 19 | 20 | //Find Free Space In Hash Table 21 | int probe (int H[] , int key) //Double Hashing 22 | { 23 | int index1 = hash1(key); 24 | int index2 = hash2(key); 25 | int i = 0; 26 | 27 | while(H[(index1 + i * index2) % SIZE] != 0) //Hash Function Used = (( h'(x) = ((h1(x) + i * h2(x)) % SIZE )) ,where, i = 0 , 1 , 2 , 3 . . . . . . . 28 | i++; 29 | 30 | return (index1 + i * index2) % SIZE; 31 | } 32 | 33 | //Insert ELement in Hash Table 34 | void Insert(int H[] , int key) 35 | { 36 | int index1 = hash1(key); 37 | 38 | if(H[index1] != 0) //if collision occurs probe 39 | { 40 | int newIndex = probe(H,key); 41 | H[newIndex] = key; 42 | } 43 | else 44 | H[index1] = key; //if no collision occurs 45 | } 46 | 47 | //Search Element in Hash Table 48 | int Search(int H[], int key) 49 | { 50 | int index1 = hash1(key); 51 | int index2 = hash2(key); 52 | int i = 0; 53 | while(H[(index1 + i * index2) % SIZE ] != key) 54 | { 55 | i++; //worst case if space means "0" not found so 56 | if((index1 + i * index2) % SIZE == 0 ) //this means all indexes have value therefore 57 | return -1; //if i becomes = size && element not found return -1 58 | } 59 | 60 | return (index1 + i * index2) % SIZE; 61 | } 62 | 63 | //Delete key From Hash Table (Re-Hashing) 64 | void Delete(int H[], int key) 65 | { 66 | int index1= hash1(key); 67 | int index2 = hash2(key); 68 | int i = 0, j = 0; 69 | while(H[(index1 + i * index2) % SIZE] != key) 70 | { 71 | i++; 72 | if((index1 + i * index2) % SIZE == 0) 73 | { 74 | printf("\n%d Key not Exist's in Hash Table\n",key); 75 | break; 76 | } 77 | } 78 | H[(index1 + i * index2) % SIZE] = 0; //deleting memory by making it Zero. 79 | 80 | int arr[SIZE] = {0}; //New arry for rehashing initializing to 0 81 | for(int i = 0; i < SIZE ; i++) 82 | { 83 | if(H[i] != 0) 84 | { 85 | arr[j] = H[i]; 86 | j++; 87 | } 88 | } 89 | 90 | for(int i = 0; i %d\n",i,H[i]); 107 | } 108 | 109 | int main() 110 | { 111 | int HT[10] = {0}; 112 | int res; 113 | Insert(HT, 3); 114 | Insert(HT, 10); 115 | Insert(HT, 93); 116 | Insert(HT, 13); 117 | Insert(HT, 65); 118 | Insert(HT, 6); 119 | 120 | printf("Elements in Hash Table\n\n"); 121 | print(HT); 122 | 123 | res = Search(HT,10); //if Found Print Key Index Else -1 124 | (res != -1) ? printf("\n%d Key found at Index %d\n",10,res) : printf("\n%D Key Not Found %d\n",10,res); 125 | 126 | Delete(HT,65); //Delete Key From Hash Table 127 | Delete(HT,93); //Delete Key From Hash Table 128 | 129 | printf("\nElements in Hash Table After Performing Deletion Done Through Re-Hashing\n\n"); 130 | print(HT); //Print after Deleting 131 | 132 | 133 | Insert(HT, 65); //Insert 134 | Delete(HT,10); //Delete 135 | 136 | printf("\nElements in Hash Table After Performing INsertion & Deletion Again Final Hash Table\n\n"); 137 | print(HT); 138 | 139 | res = Search(HT,65); //if Found Print Key Index Else -1 140 | (res != -1) ? printf("\n%d Key found at Index %d\n",65,res) : printf("\n%d Key Not Found %d\n",65,res); 141 | 142 | return 0; 143 | } -------------------------------------------------------------------------------- /Hashing_Techiniques/Linear_Probing.c: -------------------------------------------------------------------------------- 1 | //Linear Probing [ Closed Hashing ( Open Addressing ) ] 2 | 3 | #include 4 | #define SIZE 10 5 | 6 | //Hash Function 7 | int hash (int key) 8 | { 9 | return key % SIZE; 10 | } 11 | 12 | //Find Free Space In Hash Table 13 | int probe (int H[] , int key) //Linear Probe 14 | { 15 | int index = hash(key); 16 | int i = 0; 17 | 18 | while(H[(index + i) % SIZE] != 0) //Hash Function Used = (( h'(x) = (h(x) + f(i)) % SIZE )) ,where, i = 0 , 1 , 2 , 3 . . . . . . . 19 | i++; 20 | 21 | return (index + i) % SIZE; 22 | } 23 | 24 | //Insert ELement in Hash Table 25 | void Insert(int H[] , int key) 26 | { 27 | int index = hash(key); 28 | 29 | if(H[index] != 0) 30 | index = probe(H , key); 31 | H[index] = key; 32 | } 33 | 34 | //Search Element in Hash Table 35 | int Search(int H[], int key) 36 | { 37 | int index = hash(key); 38 | int i = 0; 39 | while(H[(index + i) % SIZE ] != key) 40 | { 41 | i++; //worst case if space means "0" not found so 42 | if((index + i) % SIZE == 0 ) //this means all indexes have value therefore 43 | return -1; //if i becomes = size && element not found return -1 44 | } 45 | 46 | return (index + i) % SIZE; 47 | } 48 | 49 | //Delete key From Hash Table (Re-Hashing) 50 | void Delete(int H[], int key) 51 | { 52 | int index = hash(key); 53 | int i = 0, j = 0; 54 | while(H[(index + i) % SIZE] != key) 55 | { 56 | i++; 57 | if((index + i) % SIZE == 0) 58 | { 59 | printf("\n%d Key not Exist's in Hash Table\n",key); 60 | break; 61 | } 62 | } 63 | H[(index + i) % SIZE] = 0; //deleting memory by making it Zero. 64 | 65 | int arr[SIZE] = {0}; //New arry for rehashing initializing to 0 66 | for(int i = 0; i < SIZE ; i++) 67 | { 68 | if(H[i] != 0) 69 | { 70 | arr[j] = H[i]; 71 | j++; 72 | } 73 | } 74 | 75 | for(int i = 0; i %d\n",i,H[i]); 92 | } 93 | 94 | int main() 95 | { 96 | int HT[10] = {0}; 97 | int res; 98 | Insert(HT, 3); 99 | Insert(HT, 10); 100 | Insert(HT, 93); 101 | Insert(HT, 13); 102 | Insert(HT, 65); 103 | Insert(HT, 6); 104 | 105 | printf("Elements in Hash Table\n\n"); 106 | print(HT); 107 | 108 | res = Search(HT,10); //if Found Print Key Index Else -1 109 | (res != -1) ? printf("\n%d Key found at Index %d\n",10,res) : printf("\n%D Key Not Found %d\n",10,res); 110 | 111 | Delete(HT,65); //Delete Key From Hash Table 112 | Delete(HT,93); //Delete Key From Hash Table 113 | 114 | printf("\nElements in Hash Table After Performing Deletion Done Through Re-Hashing\n\n"); 115 | print(HT); //Print after Deleting 116 | 117 | 118 | Insert(HT, 65); //Insert 119 | Delete(HT,10); //Delete 120 | 121 | printf("\nElements in Hash Table After Performing INsertion & Deletion Again Final Hash Table\n\n"); 122 | print(HT); 123 | 124 | res = Search(HT,65); //if Found Print Key Index Else -1 125 | (res != -1) ? printf("\n%d Key found at Index %d\n",65,res) : printf("\n%d Key Not Found %d\n",65,res); 126 | 127 | return 0; 128 | } -------------------------------------------------------------------------------- /Hashing_Techiniques/Quadratic_Probing.c: -------------------------------------------------------------------------------- 1 | //Quadratic Probing [ Closed Hashing ( Open Addressing ) ] 2 | 3 | #include 4 | #define SIZE 10 5 | 6 | //Hash Function 7 | int hash (int key) 8 | { 9 | return key % SIZE; 10 | } 11 | 12 | //Find Free Space In Hash Table 13 | int probe (int H[] , int key) //Quadratic Probe 14 | { 15 | int index = hash(key); 16 | int i = 0; 17 | 18 | while(H[(index + (i*i)) % SIZE] != 0) //Hash Function Used = (( h'(x) = (h(x) + f((i*i))) % SIZE )) ,where, i = 0 , 1 , 2 , 3 . . . . . . . 19 | i++; 20 | 21 | return (index + (i*i)) % SIZE; 22 | } 23 | 24 | //Insert ELement in Hash Table 25 | void Insert(int H[] , int key) 26 | { 27 | int index = hash(key); 28 | 29 | if(H[index] != 0) 30 | index = probe(H , key); 31 | H[index] = key; 32 | } 33 | 34 | //Search Element in Hash Table 35 | int Search(int H[], int key) 36 | { 37 | int index = hash(key); 38 | int i = 0; 39 | while(H[(index + (i*i)) % SIZE ] != key) 40 | { 41 | i++; //worst case if space means "0" not found so 42 | if((index + (i*i)) % SIZE == 0 ) //this means all indexes have value therefore 43 | return -1; //if i becomes = size && element not found return -1 44 | } 45 | 46 | return (index + (i*i)) % SIZE; 47 | } 48 | 49 | //Delete key From Hash Table (Re-Hashing) 50 | void Delete(int H[], int key) 51 | { 52 | int index = hash(key); 53 | int i = 0, j = 0; 54 | while(H[(index + (i*i)) % SIZE] != key) 55 | { 56 | i++; 57 | if((index + (i*i)) % SIZE == 0) 58 | { 59 | printf("\n%d Key not Exist's in Hash Table\n",key); 60 | break; 61 | } 62 | } 63 | H[(index + (i*i)) % SIZE] = 0; //deleting memory by making it Zero. 64 | 65 | int arr[SIZE] = {0}; //New arry for rehashing initializing to 0 66 | for(int i = 0; i < SIZE ; i++) 67 | { 68 | if(H[i] != 0) 69 | { 70 | arr[j] = H[i]; 71 | j++; 72 | } 73 | } 74 | 75 | for(int i = 0; i %d\n",i,H[i]); 92 | } 93 | 94 | int main() 95 | { 96 | int HT[10] = {0}; 97 | int res; 98 | Insert(HT, 3); 99 | Insert(HT, 10); 100 | Insert(HT, 93); 101 | Insert(HT, 13); 102 | Insert(HT, 65); 103 | Insert(HT, 6); 104 | 105 | printf("Elements in Hash Table\n\n"); 106 | print(HT); 107 | 108 | res = Search(HT,10); //if Found Print Key Index Else -1 109 | (res != -1) ? printf("\n%d Key found at Index %d\n",10,res) : printf("\n%D Key Not Found %d\n",10,res); 110 | 111 | Delete(HT,65); //Delete Key From Hash Table 112 | Delete(HT,93); //Delete Key From Hash Table 113 | 114 | printf("\nElements in Hash Table After Performing Deletion Done Through Re-Hashing\n\n"); 115 | print(HT); //Print after Deleting 116 | 117 | 118 | Insert(HT, 65); //Insert 119 | Delete(HT,10); //Delete 120 | 121 | printf("\nElements in Hash Table After Performing INsertion & Deletion Again Final Hash Table\n\n"); 122 | print(HT); 123 | 124 | res = Search(HT,65); //if Found Print Key Index Else -1 125 | (res != -1) ? printf("\n%d Key found at Index %d\n",65,res) : printf("\n%d Key Not Found %d\n",65,res); 126 | 127 | return 0; 128 | } -------------------------------------------------------------------------------- /Hashing_Techiniques/hashing.c: -------------------------------------------------------------------------------- 1 | //Chaning [ Closed Hashing ( Open Addressing ) ] 2 | 3 | #include 4 | #include 5 | 6 | struct Node{ 7 | int data; 8 | struct Node *next; 9 | }; 10 | 11 | //Function for sorted Insert in an Array of Linkedlist 12 | void SortedInsert(struct Node **H, int x) 13 | { 14 | struct Node *temp, *q = NULL , *p = *H; 15 | 16 | temp = (struct Node*)malloc(sizeof(struct Node)); 17 | temp -> data = x; 18 | temp -> next = NULL; 19 | 20 | if(*H == NULL) 21 | *H = temp; 22 | 23 | else 24 | { 25 | while(p && p->data < x) 26 | { 27 | q = p; 28 | p = p -> next; 29 | } 30 | if(p == *H) 31 | { 32 | temp -> next = *H; 33 | *H = temp; 34 | } 35 | else{ 36 | temp -> next = q -> next; 37 | q -> next = temp; 38 | } 39 | } 40 | } 41 | 42 | //Hash Function used 43 | int hash(int key) 44 | { 45 | return key % 10; 46 | } 47 | 48 | //Function to Insert in a Hash Table 49 | void Insert(struct Node *H[], int key) 50 | { 51 | int index = hash(key); 52 | SortedInsert(&H[index],key); 53 | } 54 | 55 | // Search ELement in Hash Table 56 | struct Node *Search(struct Node *p, int key) 57 | { 58 | while(p != NULL) 59 | { 60 | if(key == p -> data) 61 | return p; 62 | p = p -> next; 63 | } 64 | return NULL; 65 | } 66 | 67 | // Delete Key From Hash Table 68 | void Delete(struct Node *p,struct Node **q, int key) 69 | { 70 | struct Node *prev = p, *curr = p; 71 | 72 | if(curr -> data == key) 73 | { prev = curr; 74 | curr = curr -> next; 75 | free(prev); 76 | prev = NULL; 77 | *q = curr; 78 | } 79 | else{ 80 | while(curr && curr->next) 81 | { 82 | curr = curr -> next; 83 | if(curr -> data == key) 84 | { 85 | prev -> next = curr -> next; 86 | free(curr); 87 | curr = NULL; 88 | } 89 | prev = prev -> next; 90 | } 91 | } 92 | } 93 | 94 | // Print Elements of Hash Table 95 | void print(struct Node *p) 96 | { 97 | int i = 0; 98 | 99 | while(p != NULL) 100 | { 101 | printf("chain[%d]--> %d \t",i,p->data); 102 | p = p->next; 103 | i++; 104 | } 105 | printf("NULL"); 106 | } 107 | 108 | int main() 109 | { 110 | struct Node *HT[10]; //Array of Pointers 111 | struct Node *temp; 112 | int i; 113 | 114 | //for initialising to NULL 115 | for(i = 0; i<10 ; i++) 116 | HT[i] = NULL; 117 | 118 | //Insert in a HASH TABLE 119 | Insert(HT,12); 120 | Insert(HT,23); 121 | Insert(HT,35); 122 | Insert(HT,92); 123 | Insert(HT,11); 124 | Insert(HT,50); 125 | Insert(HT,44); 126 | Insert(HT,16); 127 | Insert(HT,7); 128 | Insert(HT,48); 129 | Insert(HT,8); 130 | Insert(HT,98); 131 | Insert(HT,99); 132 | Insert(HT,10); 133 | Insert(HT,33); 134 | Insert(HT,58); 135 | Insert(HT,13); 136 | Insert(HT,77); 137 | 138 | printf("\nElements in Hash Table\n\n"); 139 | for(int i = 0; i<10 ; i++) 140 | { 141 | printf("Index[%d] --> ",i); 142 | print(HT[i]); 143 | printf("\n"); 144 | } 145 | 146 | printf("\n------------------------------------\n"); 147 | 148 | printf("\nSearching of keys in Hash Table\n\n"); 149 | 150 | temp = Search(HT[hash(23)],23); 151 | temp ? printf("%d Key Found!!!\n",temp -> data) : printf("-1 Key Not Found!!!\n"); 152 | 153 | printf("\n"); 154 | 155 | //Searching key in Hash Table 156 | 157 | temp = Search(HT[hash(9)],9); 158 | temp ? printf("%d Key Found!!!\n",temp -> data) : printf("-1 Key Not Found!!!\n"); 159 | 160 | printf("\n------------------------------------\n"); 161 | 162 | // Deleting key from Hash Table 163 | 164 | Delete(HT[hash(33)],&HT[hash(33)],33); //Last Element 165 | Delete(HT[hash(48)],&HT[hash(48)],48); //Middle Element 166 | Delete(HT[hash(44)],&HT[hash(44)],44); //First Element 167 | 168 | printf("\nElements in Hash Table After Performing Deletion\n\n"); 169 | for(int i = 0; i<10 ; i++) 170 | { 171 | 172 | printf("Index[%d] --> ",i); 173 | print(HT[i]); 174 | printf("\n"); 175 | } 176 | 177 | return 0; 178 | } -------------------------------------------------------------------------------- /Insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int insertion_sort(int *arr , int n) 5 | { 6 | for(int i=1; i=0 && arr[j] > temp) 13 | { 14 | arr[j+1] = arr[j] ; 15 | j -- ; 16 | } 17 | 18 | arr[j+1] = temp ; 19 | } 20 | 21 | return *arr ; 22 | } 23 | 24 | int main() 25 | { 26 | int arr[] = {8,4,1,5,9,2} ; 27 | int n = sizeof(arr) / sizeof(arr[0]) ; 28 | 29 | // print the unsorted array 30 | cout << "unsorted array : " ; 31 | for (int i = 0; i < n; i++) 32 | { 33 | cout << arr[i] << " "; 34 | } 35 | 36 | // calling the function . 37 | insertion_sort(arr, n) ; 38 | 39 | cout << endl ; 40 | 41 | // print the sorted array 42 | cout << "sorted array : "; 43 | for(int i=0; i= 0; i--) { //as it is an stack so last element willl be the first element 72 | string += String.valueOf(array[i] + ","); 73 | } 74 | string = string.substring(0, string.lastIndexOf(',')) + "]"; 75 | return string; 76 | } 77 | 78 | /////equals() compares two stacks 79 | public boolean equals(Stack obj) { 80 | if (this.size() != obj.size()) { 81 | return false; 82 | } 83 | Object array[] = new Object[this.size()]; 84 | Object array2[] = new Object[this.size()]; //as size of both are equal 85 | boolean areEqual = true; 86 | int i = 0; //counter variable 87 | for (; i < array.length; i++) { 88 | array[i] = this.pop(); //storing elements in array by popping so that we can store later same elements 89 | array2[i] = obj.pop(); 90 | if (!array[i].equals(array2[i])) { 91 | areEqual = false; 92 | } 93 | } 94 | while (--i >= 0) { 95 | this.push(array[i]); //again inserting those elements in 96 | obj.push(array2[i]); 97 | } 98 | return areEqual; 99 | } 100 | 101 | ////findLast() finds last element in the stack 102 | public Object findLast() { 103 | if (this.isEmpty()) { 104 | throw new IllegalStateException("Stack is empty!"); 105 | } 106 | return array[0]; 107 | } 108 | 109 | /////toLinkedStack() returns LinkedStack object equivalent to curent ArrayStack object 110 | public LinkedStack toLinkedStack() { 111 | if (this.isEmpty()) { 112 | return null; 113 | } 114 | LinkedStack stack = new LinkedStack(); 115 | for (int i = 0; i < this.size; i++) { 116 | stack.push(array[i]); 117 | } 118 | return stack; 119 | } 120 | 121 | public static void main(String[] args) { 122 | ArrayStack stack = new ArrayStack(2); 123 | stack.push(30); 124 | stack.push("Hello1"); 125 | stack.push(20); 126 | ArrayStack stack2 = new ArrayStack(2); 127 | stack2.push(30); 128 | stack2.push("Hello"); 129 | stack2.push(20); 130 | System.out.println("stack.toString(): " + stack.toString()); 131 | System.out.println("stack2.toString(): " + stack2.toString()); 132 | System.out.println("stack.equals(stack2): " + stack.equals(stack2)); 133 | System.out.println("stack.findLast(): " + stack.findLast()); 134 | System.out.println("stack.toLinkedStack().toString(): " + stack.toLinkedStack().toString()); 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /Java/stack/LinkedStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | /** 7 | * 8 | * @author Zohaib Hassan Soomro 9 | */ 10 | package stack; 11 | 12 | import java.util.*; 13 | 14 | public class LinkedStack implements Stack { 15 | 16 | private int size; 17 | private Node top; 18 | 19 | private class Node { 20 | 21 | private Object object; 22 | private Node next; 23 | 24 | public Node(Object object, Node next) { 25 | this.object = object; 26 | this.next = next; 27 | } 28 | 29 | } 30 | 31 | @Override 32 | public Object peek() { 33 | if (this.isEmpty()) { 34 | throw new NoSuchElementException("Stack is Empty!"); 35 | } 36 | return top.object; 37 | } 38 | 39 | @Override 40 | public Object pop() { 41 | if (this.isEmpty()) { 42 | throw new NoSuchElementException("Stack is Empty!"); 43 | } 44 | Object obj = top.object; 45 | top = top.next; 46 | --size; 47 | return obj; 48 | } 49 | 50 | @Override 51 | public void push(Object obj) { 52 | top = new Node(obj, top); 53 | size++; 54 | } 55 | 56 | @Override 57 | public int size() { 58 | return size; 59 | } 60 | 61 | @Override 62 | public boolean isEmpty() { 63 | return (size == 0); 64 | } 65 | 66 | /////toString() converts all data of current object into an string 67 | public String toString() { 68 | if (this.isEmpty()) { 69 | return ""; 70 | } 71 | String string = "["; 72 | for (Node i = top; i != null; i = i.next) { 73 | string += String.valueOf(i.object + ","); 74 | } 75 | string = string.substring(0, string.lastIndexOf(',')) + "]"; 76 | return string; 77 | } 78 | 79 | /////equals() compares two stacks 80 | public boolean equals(Stack obj) { 81 | if (this.size() != obj.size()) { 82 | return false; 83 | } 84 | Object array[] = new Object[this.size()]; 85 | Object array2[] = new Object[this.size()]; //as size of both are equal 86 | boolean areEqual = true; 87 | int i = 0; //counter variable 88 | for (; i < array.length; i++) { 89 | array[i] = this.pop(); //storing elements in array by popping so that we can store later same elements 90 | array2[i] = obj.pop(); 91 | if (!array[i].equals(array2[i])) { 92 | areEqual = false; 93 | } 94 | } 95 | while (--i >= 0) { 96 | this.push(array[i]); //again inserting those elements in 97 | obj.push(array2[i]); 98 | } 99 | return areEqual; 100 | } 101 | 102 | ////findLast() finds last element in the stack 103 | public Object findLast() { 104 | if (this.isEmpty()) { 105 | throw new NoSuchElementException("Stack is empty!"); 106 | } 107 | Node i = top; 108 | for (; i.next != null; i = i.next) //because if i.next=null it means i will be pointing to the last Object 109 | { 110 | } 111 | return i.object; 112 | } 113 | 114 | /////toArrayStack() returns ArrayStack object equivalent to curent LinkedStack object 115 | public ArrayStack toArrayStack() { 116 | if (this.isEmpty()) { 117 | return null; 118 | } 119 | Object array[] = new Object[this.size]; 120 | int count = 0; 121 | ArrayStack stack = new ArrayStack(this.size); 122 | for (Node i = top; i != null; i = i.next) { 123 | array[count++] = i.object; //for preserving same order that's why storing elements in an Object array 124 | } 125 | for (int i = this.size - 1; i >= 0; i--) { 126 | stack.push(array[i]); 127 | } 128 | return stack; 129 | } 130 | 131 | public static void main(String[] args) { 132 | LinkedStack stack = new LinkedStack(); 133 | stack.push(4); 134 | stack.push("Hello"); 135 | stack.push(200); 136 | LinkedStack stack2 = new LinkedStack(); 137 | stack2.push(4); 138 | stack2.push("Hello"); 139 | stack2.push(200); 140 | System.out.println("stack.toString(): " + stack.toString()); 141 | System.out.println("stack2.toString(): " + stack2.toString()); 142 | System.out.println("stack.equals(stack2): " + stack.equals(stack2)); 143 | System.out.println("stack.findLast(): " + stack.findLast()); 144 | System.out.println("stack.toArrayStack().toString(): " + stack.toArrayStack().toString()); 145 | 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /Java/stack/RPN.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package stack; 7 | 8 | import java.util.Arrays; 9 | 10 | /** 11 | * 12 | * @author Zohaib Hassan Soomro 13 | */ 14 | ///////////Reverse Polish Notation i.e 7 2 + 5 2- * = (7+2)*(5-2) 15 | public class RPN { 16 | 17 | public RPN(String[] array) { 18 | Stack stack = new ArrayStack(array.length); 19 | // or 20 | // Stack stack = new LinkedStack(); 21 | for (int i = 0; i < array.length; i++) { 22 | String input = array[i]; 23 | if (isAnOperator(input)) { 24 | double lastElement = Double.parseDouble((String) stack.pop()); 25 | double secondlastElement = Double.parseDouble((String) stack.pop()); 26 | double result = evaluate(secondlastElement, lastElement, input); 27 | stack.push("" + result); 28 | } else { 29 | stack.push(input); 30 | } 31 | } 32 | } 33 | //DMAS= Division, Multiplication, Addition, Subtraction 34 | 35 | /////checks if input is an operator 36 | private boolean isAnOperator(String operator) { 37 | return (operator.length() == 1 && ("DMAS".indexOf(operator) >= 0 || "dmas".indexOf(operator) >= 0)); 38 | } 39 | 40 | /////evaluates last two digits with corresponding operation 41 | private double evaluate(double x, double y, String op) { 42 | double z = 0; 43 | switch (op) { 44 | case "a": 45 | case "A": 46 | z = x + y; 47 | break; 48 | case "s": 49 | case "S": 50 | z = x - y; 51 | break; 52 | 53 | case "m": 54 | case "M": 55 | z = x * y; 56 | break; 57 | 58 | case "d": 59 | case "D": 60 | z = x / y; 61 | break; 62 | } 63 | System.out.println(x + " " + op + " " + y + " = " + z); 64 | return z; 65 | } 66 | 67 | public static void main(String[] args) { 68 | String str = new String("7 2 s 5 8 4 D m 2 d D 2 a"); //works on both lowercase & uppercase// (((7-2) / ((5*(8/4)) /2))+2)=3 69 | String[] array = str.split(" "); 70 | new RPN(array); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Java/stack/Stack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package stack; 7 | 8 | /** 9 | * 10 | * @author Zohaib Hassan Soomro 11 | */ 12 | public interface Stack { 13 | public Object peek(); 14 | public Object pop(); 15 | public void push(Object obj); 16 | public int size(); 17 | public boolean isEmpty(); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Laptop Price Prediction: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import seaborn as sns 6 | from sklearn.model_selection import train_test_split 7 | import pickle 8 | import warnings 9 | warnings.filterwarnings("ignore") 10 | from sklearn.compose import ColumnTransformer 11 | from sklearn.pipeline import Pipeline 12 | from sklearn.preprocessing import OneHotEncoder 13 | from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error 14 | from sklearn.linear_model import LinearRegression,Ridge,Lasso 15 | from sklearn.neighbors import KNeighborsRegressor 16 | from sklearn.tree import DecisionTreeRegressor 17 | from sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor,AdaBoostRegressor,ExtraTreesRegressor 18 | from sklearn.svm import SVR 19 | 20 | df=pd.read_csv('laptop_data.csv') 21 | df.head() 22 | 23 | df.shape 24 | 25 | df.info() 26 | 27 | df.isnull().sum() 28 | 29 | df.duplicated().sum() 30 | 31 | df.drop('Unnamed: 0',axis=1,inplace=True) 32 | 33 | df.head() 34 | 35 | df['Ram'] = df['Ram'].str.replace('GB','') 36 | df['Weight'] = df['Weight'].str.replace('kg','') 37 | 38 | df.head() 39 | 40 | print(df['Ram'].dtype) 41 | print(df['Weight'].dtype) 42 | 43 | df['Ram']=df['Ram'].astype('int32') 44 | df['Weight']=df['Weight'].astype('float32') 45 | 46 | sns.barplot(df['Ram'],df['Price']) 47 | plt.show() 48 | # By change in Ram size, the price varies 49 | 50 | df.info() 51 | 52 | df['Company'].value_counts().plot(kind='bar') 53 | plt.show() 54 | # Mostly we have laptop of dell, lenovo and hp 55 | 56 | sns.barplot(x=df['Company'],y=df['Price']) 57 | plt.xticks(rotation='vertical') 58 | plt.show() 59 | # Razer have most expensive laptops 60 | # laptop price alse depends upon what type of company we choose 61 | 62 | df['TypeName'].value_counts().plot(kind='bar') 63 | plt.show() 64 | # Mostly we have notebook laptops 65 | 66 | sns.barplot(x=df['TypeName'],y=df['Price']) 67 | plt.xticks(rotation='vertical') 68 | plt.show() 69 | # Workstation type laptops are most expensive 70 | # laptop price also depends upon on type of laptop 71 | 72 | sns.distplot(df['Inches']) 73 | plt.show() 74 | # Mostly laptops are of 16 inches 75 | 76 | sns.scatterplot(df['Inches'],df['Price']) 77 | plt.show() 78 | # With the increase in icnhes, laptop prices also increases 79 | 80 | df['ScreenResolution'].value_counts() 81 | 82 | df['Ips']=df['ScreenResolution'].apply(lambda x:1 if 'IPS Panel' in x else 0) 83 | 84 | df['Ips'].value_counts().plot(kind='bar') 85 | plt.show() 86 | # Mostly laptops have no IPS Panel 87 | 88 | sns.barplot(df['Ips'],df['Price']) 89 | plt.show() 90 | # IPS Panel laptops have high price 91 | 92 | df['Touchscreen']=df['ScreenResolution'].apply(lambda x:1 if 'Touchscreen' in x else 0) 93 | 94 | df['Touchscreen'].value_counts().plot(kind='bar') 95 | plt.show() 96 | # Mostly laptops have no touchscreen 97 | 98 | sns.barplot(df['Touchscreen'],df['Price']) 99 | plt.show() 100 | # Touch Screen laptops have high price 101 | 102 | res=df['ScreenResolution'].str.split('x') 103 | 104 | df['X_res']=0 105 | df['Y_res']=0 106 | for i in range(len(res)): 107 | df['Y_res'][i]=res[i][1] 108 | df['X_res'][i]=res[i][0][-4:] 109 | 110 | df.head() 111 | 112 | df['X_res']=df['X_res'].astype('int32') 113 | df['Y_res']=df['Y_res'].astype('int32') 114 | 115 | sns.distplot(df['Y_res']) 116 | plt.show() 117 | 118 | sns.barplot(x=df['Y_res'],y=df['Price']) 119 | plt.show() 120 | 121 | sns.distplot(df['X_res']) 122 | plt.show() 123 | 124 | sns.barplot(x=df['X_res'],y=df['Price']) 125 | plt.xticks(rotation='vertical') 126 | plt.show() 127 | 128 | df.corr()['Price'] 129 | 130 | df['ppi'] = (((df['X_res']**2) + (df['Y_res']**2))**0.5)/df['Inches'].astype('float') 131 | df.corr()['Price'] 132 | # Having strong corelation of ppi with price 133 | 134 | df.drop(['ScreenResolution','X_res','Y_res','Inches'],axis=1,inplace=True) 135 | 136 | df.head() 137 | 138 | df['Cpu Brand']=df['Cpu'] 139 | for i,j in zip(range(len(df['Cpu'])),df['Cpu']): 140 | if 'Intel Core i3' in j: 141 | df['Cpu Brand'][i]='Intel Core i3' 142 | elif 'Intel Core i5' in j: 143 | df['Cpu Brand'][i]='Intel Core i5' 144 | elif 'Intel Core i7' in j: 145 | df['Cpu Brand'][i]='Intel Core i7' 146 | elif 'AMD' in j: 147 | df['Cpu Brand'][i]='AMD' 148 | else: 149 | df['Cpu Brand'][i]='Other Processor' 150 | 151 | df['Cpu Brand'].value_counts().plot(kind='bar') 152 | plt.show() 153 | 154 | sns.barplot(x=df['Cpu Brand'],y=df['Price']) 155 | plt.xticks(rotation='vertical') 156 | plt.show() 157 | 158 | df.drop('Cpu',axis=1,inplace=True) 159 | 160 | sns.distplot(df['Ram']) 161 | plt.show() 162 | 163 | sns.barplot(x=df['Ram'],y=df['Price']) 164 | plt.xticks(rotation='vertical') 165 | plt.show() 166 | 167 | df['Memory'].value_counts() 168 | 169 | df['SSD']=0 170 | df['HDD']=0 171 | df['Hybrid']=0 172 | df['Flash Storage']=0 173 | df['Memory']=df['Memory'].str.replace('1TB','1000GB') 174 | df['Memory']=df['Memory'].str.replace('1.0TB','1000GB') 175 | df['Memory']=df['Memory'].str.replace('2.0TB','2000GB') 176 | df['Memory']=df['Memory'].str.replace('2TB','2000GB') 177 | for i in range(len(df)): 178 | a=df['Memory'][i].split('+') 179 | b=a[0].split('GB') 180 | if 'SSD' in a[0]: 181 | df['SSD'][i]=b[0] 182 | elif 'HDD' in a[0]: 183 | df['HDD'][i]=b[0] 184 | elif 'Hybrid' in a[0]: 185 | df['Hybrid'][i]=b[0] 186 | elif 'Flash Storage' in a[0]: 187 | df['Flash Storage'][i]=b[0] 188 | if '+'in df['Memory'][i]: 189 | c=a[1].split('GB') 190 | if 'SSD' in a[1]: 191 | df['SSD'][i]=int(df['SSD'][i])+int(c[0]) 192 | elif 'HDD' in a[1]: 193 | df['HDD'][i]=int(df['HDD'][i])+int(c[0]) 194 | elif 'Hybrid' in a[1]: 195 | df['Hybrid'][i]=int(df['Hybrid'][i])+int(c[0]) 196 | elif 'Flash Storage' in a[1]: 197 | df['Flash Storage'][i]=int(df['Flash Storage'][i])+int(c[0]) 198 | 199 | sns.distplot(df['HDD']) 200 | plt.show() 201 | 202 | sns.distplot(df['SSD']) 203 | plt.show() 204 | 205 | sns.distplot(df['Flash Storage']) 206 | plt.show() 207 | 208 | sns.distplot(df['Hybrid']) 209 | plt.show() 210 | 211 | df.drop('Memory',axis=1,inplace=True) 212 | 213 | df.corr()['Price'] 214 | 215 | df['Hybrid'].value_counts() 216 | 217 | df['Flash Storage'].value_counts() 218 | 219 | df.drop(['Hybrid','Flash Storage'],axis=1,inplace=True) 220 | 221 | df.head() 222 | 223 | df['Gpu Brand']=0 224 | for i in range(len(df['Gpu'])): 225 | df['Gpu Brand'][i]=df['Gpu'][i].split(' ')[0] 226 | 227 | df=df[df['Gpu Brand']!='ARM'] 228 | df.reset_index(inplace=True) 229 | 230 | df.drop('Gpu',axis=1,inplace=True) 231 | df.head() 232 | 233 | df['Gpu Brand'].value_counts().plot(kind='bar') 234 | plt.show() 235 | 236 | sns.barplot(df['Gpu Brand'],df['Price']) 237 | plt.show() 238 | 239 | df['OpSys'].value_counts() 240 | 241 | sns.barplot(df['OpSys'],df['Price']) 242 | plt.xticks(rotation='vertical') 243 | plt.show() 244 | 245 | df['OS']=0 246 | for i in range(len(df['OpSys'])): 247 | if 'Windows' in df['OpSys'][i]: 248 | df['OS'][i]='Windows' 249 | elif 'mac' in df['OpSys'][i]: 250 | df['OS'][i]='Mac' 251 | elif 'Mac' in df['OpSys'][i]: 252 | df['OS'][i]='Mac' 253 | else: 254 | df['OS'][i]='Others/No Linus/No OS' 255 | 256 | df.drop(columns=['OpSys'],inplace=True) 257 | 258 | df.head() 259 | 260 | sns.barplot(x=df['OS'],y=df['Price']) 261 | plt.xticks(rotation='vertical') 262 | plt.show() 263 | 264 | df['OS'].value_counts() 265 | 266 | df.corr()['Price'] 267 | 268 | plt.figure(figsize=(10,5)) 269 | sns.heatmap(df.corr(),annot=True) 270 | plt.show() 271 | 272 | sns.distplot(np.log(df['Price'])) 273 | plt.show() 274 | 275 | df['Price']=np.log(df['Price']) 276 | 277 | df.drop('index',axis=1,inplace=True) 278 | 279 | df.head() 280 | 281 | X = df.drop(columns=['Price']) 282 | y = np.log(df['Price']) 283 | 284 | X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.15,random_state=2) 285 | 286 | """### Linear regression""" 287 | 288 | step1 = ColumnTransformer(transformers=[ 289 | ('col_tnf',OneHotEncoder(sparse=False,drop='first'),[0,1,7,10,11]) 290 | # We will not count price that's why our counting change 291 | ],remainder='passthrough') 292 | 293 | step2 = LinearRegression() 294 | 295 | pipe = Pipeline([ 296 | ('step1',step1), 297 | ('step2',step2) 298 | ]) 299 | 300 | pipe.fit(X_train,y_train) 301 | 302 | y_pred = pipe.predict(X_test) 303 | 304 | print('R2 score',r2_score(y_test,y_pred)) 305 | print('MAE',mean_absolute_error(y_test,y_pred)) 306 | -------------------------------------------------------------------------------- /Leetcode: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------------------------------- 2 | Problem 1 : 3 | Link to question : https://leetcode.com/problems/two-sum/ 4 | Solution : 5 | In Python 3: 6 | class Solution: 7 | def twoSum(self, nums: List[int], target: int) -> List[int]: 8 | for i in range(len(nums)): 9 | for j in range(i+1,len(nums)): 10 | sum=nums[i]+nums[j] 11 | if sum==target: 12 | return i,j 13 | return [] 14 | -------------------------------------------------------------------------------------------------------- 15 | Problem 2 : 16 | Link : https://leetcode.com/problems/reverse-linked-list/ 17 | Solution 18 | CPP 19 | ListNode* reverseList(ListNode* head) { 20 | if( head==NULL || head->next==NULL){ 21 | return head; 22 | } 23 | 24 | ListNode* newnode=reverseList(head->next); 25 | head->next->next=head; 26 | head->next=NULL; 27 | return newnode; 28 | 29 | 30 | } 31 | 32 | ------------------------------------------------------------------------------------------------------------ 33 | Problem 3: 34 | Link : https://leetcode.com/problems/first-bad-version/ 35 | solution 36 | CPP 37 | int firstBadVersion(int n) { 38 | int low=1,high=n; 39 | int mid=0;; 40 | while(low<=high){ 41 | mid=low+(high-low)/2; 42 | if(low==high) return mid; 43 | 44 | if(isBadVersion(mid)) 45 | high=mid; 46 | else 47 | low=mid+1; 48 | } 49 | return-1; 50 | } 51 | 52 | --------------------------------------------------------------------------------------------------------------- 53 | Problem 4: 54 | link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 55 | solution 56 | CPP 57 | 58 | int maxProfit(vector& prices) { 59 | int lsf = INT_MAX; 60 | int op = 0; 61 | int pist = 0; 62 | 63 | for(int i = 0; i < prices.size(); i++){ 64 | if(prices[i] < lsf){ 65 | lsf = prices[i]; 66 | } 67 | pist = prices[i] - lsf; 68 | if(op < pist){ 69 | op = pist; 70 | } 71 | } 72 | return op; 73 | 74 | } 75 | 76 | --------------------------------------------------------------------------------------------------------------- 77 | Problem 9: 78 | link : https://leetcode.com/problems/palindrome-number/ 79 | solution 80 | CPP 81 | class Solution { 82 | long long convert(int x){ 83 | //reversing can exceed the allowed INTEGER domain for 32-bit. 84 | long long ans=0; 85 | while(x>0){ 86 | ans = ans*10+x%10; 87 | x=x/10; 88 | } 89 | return ans; 90 | } 91 | public: 92 | bool isPalindrome(int x) { 93 | if(x<0) return false; 94 | //getting the reverse number and checking whether reversed_number==original_number 95 | long long ans=convert(x); 96 | //typeCasting for Checking 97 | return ans==(long long)(x); 98 | } 99 | }; 100 | 101 | --------------------------------------------------------------------------------------------------------------- 102 | Problem 704: 103 | link : https://leetcode.com/problems/binary-search/ 104 | solution 105 | C 106 | 107 | 108 | 109 | int search(int* nums, int numsSize, int target){ 110 | if (numsSize == 1 && nums[0] == target) 111 | return 0; 112 | 113 | int min , max , mid ; 114 | min=0; 115 | max=numsSize-1; 116 | 117 | while(min<=max) 118 | { mid=(min+max)/2; 119 | if(nums[mid]==target) 120 | { 121 | // printf("%d",target); 122 | return mid; 123 | 124 | } 125 | else if(target > nums[mid]) 126 | { 127 | min=mid+1; 128 | } 129 | else 130 | { 131 | max=mid-1; 132 | } 133 | } 134 | return -1; 135 | } 136 | 137 | ---------------------------------------------------------------------------------------------------------------------------- 138 | Problem 42: 139 | link : https://leetcode.com/problems/trapping-rain-water/ 140 | solution 141 | java 142 | 143 | import java.util.*; 144 | 145 | 146 | class Solution { 147 | public int trap(int[] height) { 148 | int result = 0; 149 | 150 | if(height==null || height.length<=2) 151 | return result; 152 | 153 | int left[] = new int[height.length]; 154 | int right[]= new int[height.length]; 155 | 156 | //scan from left to right 157 | int max = height[0]; 158 | left[0] = height[0]; 159 | for(int i=1; i=0; i--){ 172 | if(height[i] List[int]: 11 | for i in range(len(nums)): 12 | for j in range(i+1, len(nums)): 13 | sum = nums[i]+nums[j] 14 | if sum == target: 15 | return i, j 16 | return [] 17 | -------------------------------------------------------------------------------------------------------- 18 | Problem 2: 19 | Link to question: https: // leetcode.com/problems/valid-parentheses/ 20 | Solution: 21 | In Python 3: 22 | 23 | class Solution: 24 | def isValid(s): 25 | st = [s[0]] 26 | for i in range(1, len(s)): 27 | if len(st) == 0: 28 | st += s[i] 29 | else: 30 | if st[-1]+s[i] in ['()', '[]', '{}']: 31 | st.pop() 32 | else: 33 | st += s[i] 34 | return len(st) == 0 35 | -------------------------------------------------------------------------------------------------------- 36 | -------------------------------------------------------------------------------- /MaxSumNonAdjacent.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int solve(vector &arr, int index,vector& dp){ 5 | if(index>=arr.size()){ 6 | return 0; 7 | } 8 | if(dp[index]!=-1){ 9 | return dp[index]; 10 | } 11 | int inc=arr[index] + solve (arr,index+2,dp); 12 | int exc= 0 + solve(arr,index+1,dp); 13 | return dp[index]=max(inc,exc); 14 | } 15 | int solve2(vector arr){ 16 | vector dp(arr.size()+2,0); 17 | int n= arr.size(); 18 | for(int i=n-1;i>=0;i--){ 19 | int inc=arr[i] + dp[i+2]; 20 | int exc= 0 + dp[i+1]; 21 | dp[i]=max(inc,exc); 22 | } 23 | return dp[0]; 24 | 25 | } 26 | int solve3(vector arr){ 27 | int next1=0; 28 | int next2=0; 29 | int curr; 30 | int n= arr.size(); 31 | for(int i=n-1;i>=0;i--){ 32 | int inc=arr[i] + next2; 33 | int exc= 0 + next1; 34 | curr=max(inc,exc); 35 | next2=next1; 36 | next1=curr; 37 | } 38 | return curr; 39 | 40 | } 41 | int main(){ 42 | 43 | vector arr; 44 | arr.push_back(2); 45 | arr.push_back(1); 46 | arr.push_back(4); 47 | arr.push_back(9); 48 | //vector dp(arr.size(),-1); 49 | cout<< solve2(arr); 50 | } -------------------------------------------------------------------------------- /Merge_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int *arr, int start, int end); 5 | 6 | void merge_sort(int *arr, int start, int end) 7 | { 8 | // base case 9 | if (start >= end) 10 | return; 11 | 12 | int mid = start + (end - start) / 2; 13 | 14 | // left part sort 15 | merge_sort(arr, start, mid); 16 | 17 | // right part sort 18 | merge_sort(arr, mid + 1, end); 19 | 20 | // for merging two sorted arrays 21 | merge(arr, start, end); 22 | } 23 | 24 | void merge(int *arr, int start, int end) 25 | { 26 | int mid = start + (end - start) / 2; 27 | 28 | // length of both array 29 | int len1 = mid - start + 1; 30 | int len2 = end - mid; 31 | 32 | // create new dynamic array 33 | int *first = new int[len1]; 34 | int *second = new int[len2]; 35 | 36 | // copy first array in *first 37 | int mainArrayIndex = start; 38 | for (int i = 0; i < len1; i++) 39 | { 40 | first[i] = arr[mainArrayIndex++]; 41 | } 42 | 43 | // copy second array in *second 44 | mainArrayIndex = mid + 1; 45 | for (int i = 0; i < len2; i++) 46 | { 47 | second[i] = arr[mainArrayIndex++]; 48 | } 49 | 50 | // merge 2 sorted array 51 | int index1 = 0; 52 | int index2 = 0; 53 | mainArrayIndex = start; 54 | 55 | // dono index ko compare kar ra , jo chota hai usko arr mai daal ra . 56 | while (index1 < len1 && index2 < len2) 57 | { 58 | if (first[index1] < second[index2]) 59 | { 60 | arr[mainArrayIndex++] = first[index1++]; 61 | } 62 | 63 | if (first[index1] > second[index2]) 64 | { 65 | arr[mainArrayIndex++] = second[index2++]; 66 | } 67 | } 68 | 69 | // agar index 1 ke element bach gaye ho to . 70 | while (index1 < len1) 71 | { 72 | arr[mainArrayIndex++] = first[index1++]; 73 | } 74 | 75 | // agar index 2 ke element bach gaye ho to . 76 | while (index1 < len2) 77 | { 78 | arr[mainArrayIndex++] = second[index2++]; 79 | } 80 | } 81 | 82 | int main() 83 | { 84 | int arr[5] = {82, 924, 91, 5, 29}; 85 | int n = 5; 86 | 87 | merge_sort(arr, 0, n - 1); 88 | 89 | for (int i = 0; i < n; i++) 90 | { 91 | cout << arr[i] << " "; 92 | } 93 | } -------------------------------------------------------------------------------- /MyProects: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Nth_fibonacci_using_Binet'sFormula.cpp: -------------------------------------------------------------------------------- 1 | //printing nth fibonacci number usin binet's formula 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | double phi = (1 + sqrt(5)) / 2; 9 | cout << (int)(pow(phi, n) / sqrt(5) + 0.5); 10 | return 0; 11 | } 12 | // this approach takes O(logn) time complexity 13 | -------------------------------------------------------------------------------- /Python Resources: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Quick_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int partition(int *arr, int s, int e) 6 | { 7 | int pivot = arr[s]; 8 | int count = 0; 9 | 10 | // It will count ki pivot se bade kitne element hai 11 | for (int i = s + 1; i <= e; i++) 12 | { 13 | if (arr[i] <= pivot) 14 | { 15 | count++; 16 | } 17 | } 18 | 19 | // place pivot to the right posistion 20 | int pivotIndex = count + s; 21 | swap(arr[pivotIndex], arr[s]); 22 | 23 | // left & right wla paer 24 | 25 | int i = s; 26 | int j = e; 27 | 28 | while (i < pivotIndex && j > pivotIndex) 29 | { 30 | while(arr[i] < pivot) 31 | { 32 | i++; 33 | } 34 | 35 | while(arr[j] > pivot) 36 | { 37 | j--; 38 | } 39 | 40 | if (i < pivotIndex && j > pivotIndex) 41 | { 42 | swap(arr[i++], arr[j--]) ; 43 | } 44 | } 45 | 46 | return pivotIndex; 47 | } 48 | 49 | void quick_sort(int *arr, int s, int e) 50 | { 51 | if (s >= e) 52 | return; 53 | 54 | int p = partition(arr, s, e); 55 | 56 | // for left side . 57 | quick_sort(arr, s, p - 1) ; 58 | 59 | // for right side 60 | quick_sort(arr, p + 1, e); 61 | } 62 | 63 | int main() 64 | { 65 | int arr[] = {8, 3, 5, 2, 0} ; 66 | int n = sizeof(arr) / sizeof(arr[0]) ; 67 | cout << n << endl; 68 | 69 | cout << "Array before quick sort : "; 70 | 71 | for (int i = 0; i < n; i++) 72 | { 73 | cout << arr[i] << " "; 74 | } 75 | 76 | quick_sort(arr, 0, n - 1) ; 77 | 78 | cout << endl ; 79 | cout << "Array after quick sort : " ; 80 | 81 | for (int i = 0; i < n; i++) 82 | { 83 | cout << arr[i] << " "; 84 | } 85 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HACKTOBERFEST-2022 2 | 3 | 4 | # 🎉Hacktoberfest 2022🎉 5 | 6 | (◔◡◔)  7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Made with [contrib.rocks](https://contrib.rocks). 15 | -------------------------------------------------------------------------------- /React/myapp/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /React/myapp/README.md: -------------------------------------------------------------------------------- 1 | Buy Me A Coffee 2 | 3 | IMAGE ALT TEXT HERE 6 | 7 | ### Click the above image to view the YouTube tutorial 8 | 9 | # Getting Started with Create React App 10 | 11 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 12 | 13 | ## Available Scripts 14 | 15 | In the project directory, you can run: 16 | 17 | ### `yarn start` 18 | 19 | Runs the app in the development mode.\ 20 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 21 | 22 | The page will reload if you make edits.\ 23 | You will also see any lint errors in the console. 24 | 25 | ### `yarn test` 26 | 27 | Launches the test runner in the interactive watch mode.\ 28 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 29 | 30 | ### `yarn build` 31 | 32 | Builds the app for production to the `build` folder.\ 33 | It correctly bundles React in production mode and optimizes the build for the best performance. 34 | 35 | The build is minified and the filenames include the hashes.\ 36 | Your app is ready to be deployed! 37 | 38 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 39 | 40 | ### `yarn eject` 41 | 42 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 43 | 44 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 45 | 46 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 47 | 48 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 49 | 50 | ## Learn More 51 | 52 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 53 | 54 | To learn React, check out the [React documentation](https://reactjs.org/). 55 | 56 | ### Code Splitting 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 59 | 60 | ### Analyzing the Bundle Size 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 63 | 64 | ### Making a Progressive Web App 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 67 | 68 | ### Advanced Configuration 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 71 | 72 | ### Deployment 73 | 74 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 75 | 76 | ### `yarn build` fails to minify 77 | 78 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 79 | -------------------------------------------------------------------------------- /React/myapp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "calculator", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.11.4", 7 | "@testing-library/react": "^11.1.0", 8 | "@testing-library/user-event": "^12.1.10", 9 | "react": "^17.0.2", 10 | "react-dom": "^17.0.2", 11 | "react-number-format": "^4.5.5", 12 | "react-scripts": "4.0.3", 13 | "web-vitals": "^1.0.1" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts start", 17 | "build": "react-scripts build", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject" 20 | }, 21 | "eslintConfig": { 22 | "extends": [ 23 | "react-app", 24 | "react-app/jest" 25 | ] 26 | }, 27 | "browserslist": { 28 | "production": [ 29 | ">0.2%", 30 | "not dead", 31 | "not op_mini all" 32 | ], 33 | "development": [ 34 | "last 1 chrome version", 35 | "last 1 firefox version", 36 | "last 1 safari version" 37 | ] 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /React/myapp/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fabayu/HACKTOBERFEST-2022/df116160c911e8ca2f2bdd7c1d56efb1596617ed/React/myapp/public/favicon.ico -------------------------------------------------------------------------------- /React/myapp/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /React/myapp/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fabayu/HACKTOBERFEST-2022/df116160c911e8ca2f2bdd7c1d56efb1596617ed/React/myapp/public/logo192.png -------------------------------------------------------------------------------- /React/myapp/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fabayu/HACKTOBERFEST-2022/df116160c911e8ca2f2bdd7c1d56efb1596617ed/React/myapp/public/logo512.png -------------------------------------------------------------------------------- /React/myapp/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /React/myapp/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /React/myapp/src/App.css: -------------------------------------------------------------------------------- 1 | @import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap"); 2 | * { 3 | padding: 0; 4 | margin: 0; 5 | box-sizing: border-box; 6 | -webkit-user-select: none; 7 | -webkit-user-drag: none; 8 | -webkit-app-region: none; 9 | } 10 | 11 | body { 12 | background-color: burlywood; 13 | display: grid; 14 | place-content: center; 15 | font-family: "Roboto", sans-serif; 16 | height: 100vh; 17 | font-size: 2rem; 18 | } 19 | 20 | .container { 21 | height: 80vh; 22 | width: 50vh; 23 | background-color: black; 24 | border-radius: 1rem; 25 | padding: 1rem; 26 | -webkit-box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); 27 | -moz-box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); 28 | box-shadow: 7px 7px 5px 0px rgba(50, 50, 50, 0.75); 29 | } 30 | 31 | .wrapper { 32 | display: grid; 33 | height: 100%; 34 | width: 100%; 35 | grid-template-columns: repeat(4, 1fr); 36 | grid-template-rows: repeat(6, 1fr); 37 | gap: 10px; 38 | } 39 | 40 | .screen { 41 | grid-column: 1 / -1; 42 | color: white; 43 | text-align: right; 44 | padding: 0.5rem; 45 | font-size: 4rem; 46 | overflow: hidden; 47 | } 48 | 49 | .btn { 50 | display: grid; 51 | place-content: center; 52 | background-color: rgb(54, 52, 52); 53 | border-radius: 50%; 54 | color: white; 55 | cursor: pointer; 56 | font-weight: bold; 57 | } 58 | .btn:hover { 59 | background-color: gray; 60 | } 61 | 62 | .light-gray { 63 | background-color: gray; 64 | color: black; 65 | } 66 | 67 | .light-gray:hover { 68 | background-color: white; 69 | } 70 | 71 | .orange { 72 | background-color: orange; 73 | } 74 | 75 | .orange:hover { 76 | background-color: white; 77 | color: orange; 78 | } 79 | 80 | .zero { 81 | grid-column: 1 / span 2; 82 | border-radius: 25px; 83 | place-content: unset; 84 | align-items: center; 85 | padding-left: 2rem; 86 | } 87 | -------------------------------------------------------------------------------- /React/myapp/src/App.js: -------------------------------------------------------------------------------- 1 | import "./App.css"; 2 | import { useState, useEffect } from "react"; 3 | import NumberFormat from "react-number-format"; 4 | 5 | function App() { 6 | const [preState, setPreState] = useState(""); 7 | const [curState, setCurState] = useState(""); 8 | const [input, setInput] = useState("0"); 9 | const [operator, setOperator] = useState(null); 10 | const [total, setTotal] = useState(false); 11 | 12 | const inputNum = (e) => { 13 | if (curState.includes(".") && e.target.innerText === ".") return; 14 | 15 | if (total) { 16 | setPreState(""); 17 | } 18 | 19 | curState 20 | ? setCurState((pre) => pre + e.target.innerText) 21 | : setCurState(e.target.innerText); 22 | setTotal(false); 23 | }; 24 | 25 | useEffect(() => { 26 | setInput(curState); 27 | }, [curState]); 28 | 29 | useEffect(() => { 30 | setInput("0"); 31 | }, []); 32 | const operatorType = (e) => { 33 | setTotal(false); 34 | setOperator(e.target.innerText); 35 | if (curState === "") return; 36 | if (preState !== "") { 37 | equals(); 38 | } else { 39 | setPreState(curState); 40 | setCurState(""); 41 | } 42 | }; 43 | 44 | const equals = (e) => { 45 | if (e?.target.innerText === "=") { 46 | setTotal(true); 47 | } 48 | let cal; 49 | switch (operator) { 50 | case "/": 51 | cal = String(parseFloat(preState) / parseFloat(curState)); 52 | break; 53 | 54 | case "+": 55 | cal = String(parseFloat(preState) + parseFloat(curState)); 56 | break; 57 | case "X": 58 | cal = String(parseFloat(preState) * parseFloat(curState)); 59 | break; 60 | case "-": 61 | cal = String(parseFloat(preState) - parseFloat(curState)); 62 | break; 63 | default: 64 | return; 65 | } 66 | setInput(""); 67 | setPreState(cal); 68 | setCurState(""); 69 | }; 70 | 71 | const minusPlus = () => { 72 | if (curState.charAt(0) === "-") { 73 | setCurState(curState.substring(1)); 74 | } else { 75 | setCurState("-" + curState); 76 | } 77 | }; 78 | 79 | const percent = () => { 80 | preState 81 | ? setCurState(String((parseFloat(curState) / 100) * preState)) 82 | : setCurState(String(parseFloat(curState) / 100)); 83 | }; 84 | 85 | const reset = () => { 86 | setPreState(""); 87 | setCurState(""); 88 | setInput("0"); 89 | }; 90 | return ( 91 |
92 |
93 |
94 | {input !== "" || input === "0" ? ( 95 | 100 | ) : ( 101 | 106 | )} 107 |
108 |
109 | AC 110 |
111 |
112 | % 113 |
114 |
115 | +/- 116 |
117 |
118 | / 119 |
120 |
121 | 7 122 |
123 |
124 | 8 125 |
126 |
127 | 9 128 |
129 |
130 | X 131 |
132 |
133 | 4 134 |
135 |
136 | 5 137 |
138 |
139 | 6 140 |
141 |
142 | + 143 |
144 |
145 | 1 146 |
147 |
148 | 2 149 |
150 |
151 | 3 152 |
153 |
154 | - 155 |
156 |
157 | 0 158 |
159 |
160 | . 161 |
162 |
163 | = 164 |
165 |
166 |
167 | ); 168 | } 169 | 170 | export default App; 171 | -------------------------------------------------------------------------------- /React/myapp/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /React/myapp/src/index.css: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /React/myapp/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /React/myapp/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /React/myapp/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /React/myapp/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /Searching-Algo/BFS.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct queue 5 | { 6 | int size; 7 | int f; 8 | int r; 9 | int* arr; 10 | }; 11 | 12 | 13 | int isEmpty(struct queue *q){ 14 | if(q->r==q->f){ 15 | return 1; 16 | } 17 | return 0; 18 | } 19 | 20 | int isFull(struct queue *q){ 21 | if(q->r==q->size-1){ 22 | return 1; 23 | } 24 | return 0; 25 | } 26 | 27 | void enqueue(struct queue *q, int val){ 28 | if(isFull(q)){ 29 | printf("This Queue is full\n"); 30 | } 31 | else{ 32 | q->r++; 33 | q->arr[q->r] = val; 34 | // printf("Enqued element: %d\n", val); 35 | } 36 | } 37 | 38 | int dequeue(struct queue *q){ 39 | int a = -1; 40 | if(isEmpty(q)){ 41 | printf("This Queue is empty\n"); 42 | } 43 | else{ 44 | q->f++; 45 | a = q->arr[q->f]; 46 | } 47 | return a; 48 | } 49 | 50 | int main(){ 51 | // Initializing Queue (Array Implementation) 52 | struct queue q; 53 | q.size = 400; 54 | q.f = q.r = 0; 55 | q.arr = (int*) malloc(q.size*sizeof(int)); 56 | 57 | // BFS Implementation 58 | int node; 59 | int i = 1; 60 | int visited[7] = {0,0,0,0,0,0,0}; 61 | //Adjacency Matrix 62 | int a [7][7] = { 63 | {0,1,1,1,0,0,0}, 64 | {1,0,1,0,0,0,0}, 65 | {1,1,0,1,1,0,0}, 66 | {1,0,1,0,1,0,0}, 67 | {0,0,1,1,0,1,1}, 68 | {0,0,0,0,1,0,0}, 69 | {0,0,0,0,1,0,0} 70 | }; 71 | 72 | printf("%d", i); 73 | visited[i] = 1; 74 | enqueue(&q, i); // Enqueue i for exploration 75 | while (!isEmpty(&q)) 76 | { 77 | int node = dequeue(&q); 78 | for (int j = 0; j < 7; j++) 79 | { 80 | if(a[node][j] ==1 && visited[j] == 0){ 81 | printf("%d", j); 82 | visited[j] = 1; 83 | enqueue(&q, j); 84 | } 85 | } 86 | } 87 | return 0; 88 | } 89 | -------------------------------------------------------------------------------- /Searching-Algo/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printArray(int *A, int n) 5 | { 6 | for (int i = 0; i < n; i++) 7 | { 8 | printf("%d ", A[i]); 9 | } 10 | cout << "\n"; 11 | } 12 | void merge(int A[], int mid, int low, int high) 13 | { 14 | int i, j, k, B[100]; 15 | i = low; 16 | j = mid + 1; 17 | k = low; 18 | while (i <= mid && j <= high) 19 | { 20 | if (A[i] < A[j]) 21 | { 22 | B[k] = A[i]; 23 | i++; 24 | k++; 25 | } 26 | else 27 | { 28 | B[k] = A[j]; 29 | j++; 30 | k++; 31 | } 32 | } 33 | // If element are left in any half 34 | // So including all the sorted subarray in new Array 35 | while (i <= mid) 36 | { 37 | B[k] = A[i]; 38 | k++; 39 | i++; 40 | } 41 | while (j <= high) 42 | { 43 | B[k] = A[j]; 44 | j++; 45 | k++; 46 | } 47 | for (int i = low; i <=high; i++) 48 | { 49 | A[i]=B[i]; 50 | } 51 | 52 | } 53 | void Merge_sort(int A[],int low, int high) 54 | { 55 | int mid; 56 | if(low< high) 57 | { 58 | mid=(low+high)/2; 59 | Merge_sort(A,low,mid); 60 | Merge_sort(A,mid+1,high); 61 | merge(A,mid,low, high); 62 | } 63 | 64 | } 65 | int main() 66 | { 67 | int A[] = {3, 5, 2, 13, 12, 3, 2, 13, 45}; 68 | // 3, 5, 2, 13, 12, 3, 2, 13, 45 69 | // 3, 2, 2, 13i, 12, 3j, 5, 13, 45 70 | // 3, 2, 2, 3j, 12i, 13, 5, 13, 45 --> first call to partition returns 3 71 | int n = 9; 72 | 73 | printArray(A, n); 74 | Merge_sort(A, 0, n - 1); 75 | printArray(A, n); 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /Searching-Algo/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void printArray(int *A, int n) 6 | { 7 | for (int i = 0; i < n; i++) 8 | { 9 | printf("%d ", A[i]); 10 | } 11 | cout<<"\n"; 12 | } 13 | 14 | int partition(int A[], int low, int high) 15 | { 16 | int pivot = A[low]; 17 | int i = low + 1; 18 | int j = high; 19 | int temp; 20 | 21 | do 22 | { 23 | while (A[i] <= pivot) 24 | { 25 | i++; 26 | } 27 | 28 | while (A[j] > pivot) 29 | { 30 | j--; 31 | } 32 | 33 | if (i < j) 34 | { 35 | temp = A[i]; 36 | A[i] = A[j]; 37 | A[j] = temp; 38 | } 39 | } while (i < j); 40 | 41 | // Swap A[low] and A[j] 42 | temp = A[low]; 43 | A[low] = A[j]; 44 | A[j] = temp; 45 | return j; 46 | } 47 | 48 | void quickSort(int A[], int low, int high) 49 | { 50 | int partitionIndex; // Index of pivot after partition 51 | 52 | if (low < high) 53 | { 54 | partitionIndex = partition(A, low, high); 55 | quickSort(A, low, partitionIndex - 1); // sort left subarray 56 | quickSort(A, partitionIndex + 1, high); // sort right subarray 57 | } 58 | } 59 | 60 | int main() 61 | { 62 | int A[] = {3, 5, 2, 13, 12, 3, 2, 13, 45}; 63 | // 3, 5, 2, 13, 12, 3, 2, 13, 45 64 | // 3, 2, 2, 13i, 12, 3j, 5, 13, 45 65 | // 3, 2, 2, 3j, 12i, 13, 5, 13, 45 --> first call to partition returns 3 66 | int n = 9; 67 | 68 | printArray(A, n); 69 | quickSort(A, 0, n - 1); 70 | printArray(A, n); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Searching-Algo/binarysearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int binarySearch(int myarray[], int beg, int end, int key) 5 | { 6 | int mid; 7 | if(end >= beg) { 8 | mid = (beg + end)/2; 9 | if(myarray[mid] == key) 10 | { 11 | return mid+1; 12 | } 13 | else if(myarray[mid] < key) { 14 | return binarySearch(myarray,mid+1,end,key); 15 | } 16 | else { 17 | return binarySearch(myarray,beg,mid-1,key); 18 | } 19 | } 20 | return -1; 21 | } 22 | int main () 23 | { 24 | int myarray[10] = {5,8,10,13,21,23,25,43,54,75}; 25 | int key, location=-1; 26 | cout<<"The input array is"<>key; 32 | location = binarySearch(myarray, 0, 9, key); 33 | if(location != -1) { 34 | cout<<"Key found at location "< 2 | #define int int64_t 3 | using namespace std; 4 | 5 | int32_t main() 6 | { 7 | int n; 8 | cin>>n; 9 | int arr[n]; 10 | for (int i = 0; i < n; i++) 11 | { 12 | cin>>arr[i]; 13 | } 14 | int c=1,k=0; 15 | while (carr[i+1]) 20 | { 21 | swap(arr[i],arr[i+1]); 22 | k++; 23 | } 24 | } 25 | c++; 26 | 27 | } 28 | for (int i = 0; i < n; i++) 29 | { 30 | cout<0){ 51 | A[j] = i; 52 | count[i] = count[i] - 1; 53 | j++; 54 | } 55 | else{ 56 | i++; 57 | } 58 | } 59 | } 60 | 61 | int main(){ 62 | int A[] = {9, 1, 4, 14, 4, 15, 6}; 63 | int n = 7; 64 | printArray(A, n); 65 | countSort(A, n); 66 | printArray(A, n); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Searching-Algo/insertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define int int64_t 3 | using namespace std; 4 | 5 | int32_t main() 6 | { 7 | int n; 8 | cin >> n; 9 | int arr[n]; 10 | for (int i = 0; i < n; i++) 11 | { 12 | cin >> arr[i]; 13 | } 14 | 15 | for (int i = 1; i < n; i++) 16 | { 17 | int current = arr[i]; 18 | int j = i - 1; 19 | 20 | while (arr[j] > current && j >= 0) 21 | { 22 | arr[j + 1] = arr[j]; 23 | j--; 24 | } 25 | arr[j + 1] = current; 26 | } 27 | for (int i = 0; i < n; i++) 28 | { 29 | cout << arr[i] << " "; 30 | } 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Searching-Algo/linearsearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int myarray[10] = {21,43,23,54,75,13,5,8,25,10}; 7 | int key,loc; 8 | cout<<"The input array is"<>key; 14 | for (int i = 0; i< 10; i++) 15 | { 16 | if(myarray[i] == key) 17 | { 18 | loc = i+1; 19 | break; 20 | } 21 | else 22 | loc = 0; 23 | } 24 | if(loc != 0) 25 | { 26 | cout<<"Key found at position "< 2 | using namespace std; 3 | 4 | 5 | void Selection_sort(int arr[],int n) 6 | { 7 | for (int i = 0; i < n-1; i++) 8 | { 9 | int indexOfMin=i; 10 | for (int j = i+1; j >n; 31 | int arr[n]; 32 | for (int i = 0; i < n; i++) 33 | { 34 | cin>>arr[i]; 35 | } 36 | Selection_sort(arr,n); 37 | printArray(arr,n); 38 | 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /Segment Tree/segmentTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void buildTree(vector &nums, vector &tree, int si, int ei, int idx) 5 | { 6 | if (si == ei) 7 | { 8 | tree[idx] = nums[si]; 9 | return; 10 | } 11 | 12 | int mid = si + ((ei - si) / 2); 13 | 14 | buildTree(nums, tree, si, mid, (2 * idx) + 1); 15 | buildTree(nums, tree, mid + 1, ei, (2 * idx) + 2); 16 | tree[idx] = tree[(2 * idx) + 1] + tree[(2 * idx) + 2]; 17 | } 18 | 19 | void buildTree(vector &nums, vector &tree) 20 | { 21 | int n = nums.size(); 22 | buildTree(nums, tree, 0, n - 1, 0); 23 | } 24 | 25 | int getSum(vector &tree, int L, int R, int si, int ei, int idx) 26 | { 27 | if (ei < L || si > R) 28 | { 29 | return 0; 30 | } 31 | 32 | if (L <= si && R >= ei) 33 | { 34 | return tree[idx]; 35 | } 36 | 37 | int mid = si + ((ei - si) / 2); 38 | 39 | return getSum(tree, L, R, si, mid, (2 * idx) + 1) + getSum(tree, L, R, mid + 1, ei, (2 * idx) + 2); 40 | } 41 | 42 | int getSum(vector &nums, vector &tree, int L, int R) 43 | { 44 | return getSum(tree, L, R, 0, nums.size() - 1, 0); 45 | } 46 | 47 | void update(vector &tree, int si, int ei, int idx, int index, int val) 48 | { 49 | if (si > index || ei < index) 50 | { 51 | return; 52 | } 53 | tree[idx] += val; 54 | if (si < ei) 55 | { 56 | int mid = si + ((ei - si) / 2); 57 | update(tree, si, mid, (2 * idx) + 1, index, val); 58 | update(tree, mid + 1, ei, (2 * idx) + 2, index, val); 59 | } 60 | } 61 | 62 | void update(vector &nums, vector &tree, int index, int val) 63 | { 64 | update(tree, 0, tree.size() - 1, 0, index, val - nums[index]); 65 | nums[index] = val; 66 | } 67 | 68 | int main() 69 | { 70 | #ifndef ONLINE_JUDGE 71 | freopen("E:/Code/DSA/input.txt", "r", stdin); 72 | freopen("E:/Code/DSA/output.txt", "w", stdout); 73 | #endif 74 | int n; 75 | cin >> n; 76 | vector nums(n); 77 | for (int i = 0; i < n; i++) 78 | { 79 | cin >> nums[i]; 80 | } 81 | vector tree(4 * n); 82 | buildTree(nums, tree); 83 | cout << getSum(nums, tree, 0, 1) << endl; 84 | cout << getSum(nums, tree, 0, 0) << endl; 85 | cout << getSum(nums, tree, 0, 2) << endl; 86 | cout << getSum(nums, tree, 0, 3) << endl; 87 | cout << getSum(nums, tree, 1, 3) << endl; 88 | cout << getSum(nums, tree, 2, 3) << endl; 89 | cout << getSum(nums, tree, 3, 3) << endl; 90 | cout << getSum(nums, tree, 1, 2) << endl; 91 | cout << getSum(nums, tree, 2, 2) << endl; 92 | update(nums, tree, 1, 25); 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /Selection_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std ; 4 | 5 | int selection_sort(int arr[] , int n) 6 | { 7 | for(int i=0; i arr[j] ) 14 | { 15 | minimum = j ; 16 | } 17 | } 18 | swap(arr[i] , arr[minimum]) ; 19 | } 20 | 21 | return arr[5] ; 22 | } 23 | 24 | int main() 25 | { 26 | int arr[100] = {2,4,5,3,1} ; 27 | int size = 5 ; 28 | 29 | selection_sort(arr , size) ; 30 | 31 | for(int i=0; i 8 | 9 |

10 |
11 | 12 | - Concept of [Breadth-first search(BFS)](https://en.wikipedia.org/wiki/Breadth-first_search) to consider all cases 13 | - Created own singly linked list 14 | - linked list based queue for BFS . 15 | - Convert grid into string of digits so that easy to process 16 | - Convert string into grid finally, 17 | -------------------------------------------------------------------------------- /Slide_Puzzle-Game/mylinkedlist.h: -------------------------------------------------------------------------------- 1 | 2 | //** singly Lindked list operation operation *// 3 | 4 | #include 5 | 6 | //node of singly linked list 7 | struct listNode 8 | { 9 | struct listNode *next; //next node linked to current node 10 | char *data; //string state contained by the list 11 | }; 12 | 13 | struct listNode *head = NULL; 14 | 15 | //Returns 1 if value is found in the list, else 0 16 | //Time complexity : O(N) 17 | int isPresent(char *value) 18 | { 19 | struct listNode *dummy = head; 20 | while (dummy) 21 | { 22 | //if data of dummy node and value is same 23 | if (strcmp(value, dummy->data) == 0) 24 | return 1; 25 | 26 | dummy = dummy->next; 27 | } 28 | return 0; 29 | } 30 | 31 | //Inserts a new value in the list 32 | //Time complexity : O(1) 33 | void insert(char *value) 34 | { 35 | struct listNode *newNode = (struct listNode *)malloc(sizeof(struct listNode)); 36 | 37 | newNode->data = (char *)malloc(sizeof(char) * 10); 38 | strcpy(newNode->data, value); 39 | newNode->next = head; 40 | 41 | head = newNode; 42 | } 43 | -------------------------------------------------------------------------------- /Slide_Puzzle-Game/myqueue.h: -------------------------------------------------------------------------------- 1 | /**** Queue using linked list***/ 2 | 3 | #include 4 | #include 5 | 6 | // node of tree-linked list 7 | struct Node 8 | { 9 | Node *next; // pointer to next node of the list 10 | Node *parent; // parent node of this node to be pushed to queue 11 | char *val; // value contained by the node 12 | int valMoved; // value moved to occupy the empty space 13 | }; 14 | 15 | typedef struct Node queueNode; 16 | 17 | typedef struct 18 | { 19 | queueNode *front; // front of the queue 20 | queueNode *rear; // rear of the queue 21 | int size; 22 | } Queue; 23 | 24 | Queue *q; 25 | 26 | // returns 1 if queue is empty else 0 27 | int is_empty() 28 | { 29 | return q->front == NULL; 30 | } 31 | 32 | // pushes an elment at back of the queue 33 | void enqueue(char *value, int valueMoved, queueNode *parentNode) 34 | { 35 | q->size++; 36 | queueNode *dummy = new queueNode(); 37 | 38 | dummy->val = (char *)malloc(sizeof(char) * 10); 39 | strcpy(dummy->val, value); 40 | 41 | dummy->next = NULL; 42 | dummy->parent = parentNode; 43 | dummy->valMoved = valueMoved; 44 | 45 | if (is_empty()) 46 | q->rear = q->front = dummy; 47 | else 48 | { 49 | q->rear->next = dummy; 50 | q->rear = q->rear->next; 51 | } 52 | } 53 | 54 | // removes the front element from the queue 55 | void dequeue() 56 | { 57 | // queue should not be empty 58 | assert(!is_empty()); 59 | q->size--; 60 | 61 | q->front = q->front->next; 62 | } 63 | 64 | // returns the element at front of the queue 65 | char *frontVal() 66 | { 67 | // queue should not be empty 68 | assert(!is_empty()); 69 | 70 | return q->front->val; 71 | } 72 | 73 | // returns the node at front of the queue 74 | queueNode *frontNode() 75 | { 76 | // queue should not be empty 77 | assert(!is_empty()); 78 | 79 | return q->front; 80 | } 81 | 82 | // returns the size of the queue 83 | int queueSize() 84 | { 85 | return q->size; 86 | } 87 | 88 | // function to initialize the queue 89 | void initializeQueue() 90 | { 91 | q = (Queue *)malloc(sizeof(Queue)); 92 | q->front = NULL; 93 | q->rear = NULL; 94 | q->size = 0; 95 | } 96 | 97 | // reverses a path of parent nodes 98 | queueNode *reversePath(queueNode *head) 99 | { 100 | queueNode *previousNode = NULL; 101 | 102 | while (head) 103 | { 104 | queueNode *Node = head->parent; 105 | head->parent = previousNode; 106 | previousNode = head; 107 | head = Node; 108 | } 109 | 110 | return previousNode; 111 | } -------------------------------------------------------------------------------- /Slide_Puzzle-Game/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "assert.h" 3 | #include "mylinkedlist.h" 4 | #include "myqueue.h" 5 | #include 6 | #pragma GCC optimize("O3,unroll-loops") 7 | #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") 8 | using namespace std; 9 | #define ln "\n" 10 | #define ll long long 11 | #define fast_cin() \ 12 | ios_base::sync_with_stdio(false); \ 13 | cin.tie(NULL); \ 14 | cout.tie(NULL); 15 | 16 | // user inputs 17 | ll sizeofRow, sizeofColumn; 18 | ll input[6][6]; 19 | 20 | // input matrix in form of string 21 | char *initialState; 22 | myQueue *endNode; 23 | 24 | // Direction to move to block 25 | ll X[4] = {0, 0, 1, -1}; 26 | ll Y[4] = {1, -1, 0, 0}; 27 | 28 | void takeInput() 29 | { 30 | cout << "\nEnter the desired number of rows: "; 31 | cin >> sizeofRow; 32 | cout << "\nEnter the desired number of columns: "; 33 | cin >> sizeofColumn; 34 | ll product = (sizeofRow * sizeofColumn * 1LL); 35 | if (product > 9) 36 | { 37 | cout << "\nGrid size is too big to handle\n" 38 | << ln; 39 | exit(0); // To end the program 40 | } 41 | 42 | // array to check if any number is visited greater than once 43 | 44 | ll no_of_Occurence[product]; 45 | 46 | // we intialised with 0 value 47 | memset(no_of_Occurence, 0, sizeof(no_of_Occurence)); 48 | 49 | cout << "\nEnter the initial grid with" << sizeofRow << "sizeofRow and" << sizeofColumn << "sizeofColumn\n"; 50 | cout << "Only distinct numbers between 1-" << product - 1 << " and a 0 to represent an empty space\n\n"; 51 | 52 | for (ll i = 0; i < sizeofRow; i++) 53 | { 54 | for (ll j = 0; j < sizeofColumn; j++) 55 | { 56 | cin >> input[i][j]; 57 | 58 | // if any invalid value is added to grid 59 | if (input[i][j] >= product) 60 | { 61 | cout << "\n Sorry, Enter number is invalid \n" 62 | << ln; 63 | exit(0); 64 | } 65 | 66 | // we increase the number of occurence 67 | no_of_Occurence[input[i][j]]++; 68 | } 69 | } 70 | 71 | // if any character is repeated in the grid 72 | for (ll i = 0; i < product; i++) 73 | { 74 | if (no_of_Occurence[i] != 1) 75 | { 76 | cout << "\nYou have entered INVALID grid \n"; 77 | exit(0); 78 | } 79 | } 80 | } 81 | 82 | //-------------------------Converts a matrix to string format------------------------ 83 | void convertMatrixToString() 84 | { 85 | initialState = (char *)malloc(sizeof(char) * (sizeofRow * sizeofColumn + 1)); 86 | ll index = 0; 87 | for (ll i = 0; i < sizeofRow; i++) 88 | { 89 | for (ll j = 0; j < sizeofColumn; j++) 90 | { 91 | initialState[index++] = (char)(input[i][j] + '0'); 92 | } 93 | } 94 | initialState[index] = '\0'; 95 | } 96 | 97 | //----------------------prints a matrix of sizeofRow rows and sizeofColumn columns from a string------------------ 98 | void printMatrixFromString(char *string) 99 | { 100 | cout<<"\n"; 101 | for (ll i = 0; string[i] != '\0'; i++) 102 | { 103 | cout<< string[i]; 104 | if (((i + 1) % sizeofColumn) == 0) 105 | { 106 | cout<<"\n"; 107 | for (ll j = 0; j < sizeofColumn; j++) 108 | cout<<"---"; 109 | cout<<"\n"; 110 | } 111 | else 112 | { 113 | cout<<" | "; 114 | } 115 | } 116 | cout<<"\n"; 117 | } 118 | 119 | //------------------------Returns 1 if solution state is reached, else 0----------------------------------- 120 | ll reachedAnswerState(char *toCheck) 121 | { 122 | for (ll i = 0; i + 1 < sizeofRow * sizeofColumn; i++) 123 | { 124 | if ((toCheck[i] - '0') != (i + 1)) 125 | return 0; 126 | } 127 | 128 | return toCheck[sizeofRow * sizeofColumn - 1] == '0'; 129 | } 130 | 131 | void swap(char *a, char *b) 132 | { 133 | char temp = *a; 134 | *a = *b; 135 | *b = temp; 136 | } 137 | 138 | //---------------------pushes all the reachable states from a given state---------------------------------- 139 | //-----------------------------------Time Complexity : O((N*M)!)--------------------------------------------- 140 | void pushReachableStates(myQueue *parent, char *initialState) 141 | { 142 | // Finding the index at which empty space or 0 is present 143 | ll indexOfZero = -1; 144 | for (ll i = 0; i < sizeofRow * sizeofColumn; i++) 145 | { 146 | if (initialState[i] == '0') 147 | { 148 | indexOfZero = i; 149 | break; 150 | } 151 | } 152 | 153 | // Computing the x and y coordinate of 0 in grid 154 | ll xCoordinate = indexOfZero / sizeofColumn; 155 | ll yCoordinate = indexOfZero % sizeofColumn; 156 | 157 | // moving in all four directions 158 | for (ll i = 0; i < 4; i++) 159 | { 160 | ll newX = xCoordinate + X[i]; 161 | ll newY = yCoordinate + Y[i]; 162 | 163 | // if new cell is inside the matrix 164 | if (newX >= 0 && newX < sizeofRow && newY >= 0 && newY < sizeofColumn) 165 | { 166 | // moving the empty space 167 | swap(&initialState[newX * sizeofColumn + newY], &initialState[indexOfZero]); 168 | 169 | // checking if we have reached this state initially or not 170 | if (isPresent(initialState) == 0) 171 | { 172 | insert(initialState); 173 | enqueue(initialState, initialState[indexOfZero] - '0', parent); 174 | } 175 | 176 | // moving the empty space back to it's original position 177 | swap(&initialState[newX * sizeofColumn + newY], &initialState[indexOfZero]); 178 | } 179 | } 180 | } 181 | 182 | //---------------------Returns the number of minimum moves to solve the input grid--------------------------- 183 | //-----------------------------------Time Complexity : O((N*M)!)--------------------------------------------- 184 | ll minimumMoves() 185 | { 186 | // initializing queue and adding the initialState 187 | initializeQueue(); 188 | 189 | enqueue(initialState, -1, NULL); 190 | insert(initialState); 191 | 192 | // denotes moves until we find solution state 193 | ll movesTillNow = 0; 194 | 195 | // while there are more states to explore 196 | while (is_empty() == false) 197 | { 198 | ll size = queueSize(); 199 | 200 | // exploring all the states within one move 201 | while (size--) 202 | { 203 | char *currentState = (char *)malloc(sizeof(char) * 10); 204 | myQueue *currentNode = frontNode(); 205 | strcpy(currentState, frontVal()); 206 | 207 | dequeue(); 208 | 209 | if (reachedAnswerState(currentState)) 210 | { 211 | endNode = currentNode; 212 | return movesTillNow; 213 | } 214 | 215 | pushReachableStates(currentNode, currentState); 216 | } 217 | 218 | // incrementing number of moves to reach the solution state 219 | movesTillNow++; 220 | } 221 | 222 | // there is no solution for the input grid 223 | return -1; 224 | } 225 | 226 | int main() 227 | { 228 | takeInput(); 229 | convertMatrixToString(); 230 | 231 | ll result = minimumMoves(); 232 | 233 | // if there is no possible solution 234 | if (result == -1) 235 | { 236 | cout << "\nNot Possible"; 237 | } 238 | else 239 | { 240 | // shortest number of moves 241 | cout << "\nShortest number of moves = " << result << ln; 242 | 243 | // reversing the path of parents to print from front 244 | myQueue *startNode = reversePath(endNode); 245 | 246 | // until the end of the path 247 | while (startNode != NULL) 248 | { 249 | printMatrixFromString(startNode->val); 250 | ll toMove = startNode->valMoved; 251 | startNode = startNode->parent; 252 | 253 | if (startNode) 254 | { 255 | cout << "Press any key to continue\n"; 256 | 257 | cout << "\nMoving " << startNode->valMoved << " to reach next state:\n"; 258 | } 259 | } 260 | } 261 | return 0; 262 | } -------------------------------------------------------------------------------- /Sorting Algos/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i array[j+1]) { //when the current item is bigger than next 19 | swapping(array[j], array[j+1]); 20 | swaps = 1; 21 | } 22 | } 23 | if(!swaps) 24 | break; // No swap in this pass, so array is sorted 25 | } 26 | } 27 | int main() { 28 | int n; 29 | cout << "Enter the number of elements: "; 30 | cin >> n; 31 | int arr[n]; 32 | cout << "Enter elements:" << endl; 33 | for(int i = 0; i> arr[i]; 35 | } 36 | cout << "Array before Sorting: "; 37 | display(arr, n); 38 | bubbleSort(arr, n); 39 | cout << "Array after Sorting: "; 40 | display(arr, n); 41 | } -------------------------------------------------------------------------------- /Sorting Algos/Counting_Sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for counting sort 2 | #include 3 | #include 4 | using namespace std; 5 | #define RANGE 255 6 | 7 | // The main function that sort 8 | // the given string arr[] in 9 | // alphabetical order 10 | void countSort(char arr[]) 11 | { 12 | // The output character array 13 | // that will have sorted arr 14 | char output[strlen(arr)]; 15 | 16 | // Create a count array to store count of individual 17 | // characters and initialize count array as 0 18 | int count[RANGE + 1], i; 19 | memset(count, 0, sizeof(count)); 20 | 21 | // Store count of each character 22 | for (i = 0; arr[i]; ++i) 23 | ++count[arr[i]]; 24 | 25 | // Change count[i] so that count[i] now contains actual 26 | // position of this character in output array 27 | for (i = 1; i <= RANGE; ++i) 28 | count[i] += count[i - 1]; 29 | 30 | // Build the output character array 31 | for (i = 0; arr[i]; ++i) { 32 | output[count[arr[i]] - 1] = arr[i]; 33 | --count[arr[i]]; 34 | } 35 | 36 | /* 37 | For Stable algorithm 38 | for (i = sizeof(arr)-1; i>=0; --i) 39 | { 40 | output[count[arr[i]]-1] = arr[i]; 41 | --count[arr[i]]; 42 | } 43 | 44 | For Logic : See implementation 45 | */ 46 | 47 | // Copy the output array to arr, so that arr now 48 | // contains sorted characters 49 | for (i = 0; arr[i]; ++i) 50 | arr[i] = output[i]; 51 | } 52 | 53 | // Driver code 54 | int main() 55 | { 56 | char arr[] = "geeksforgeeks"; 57 | 58 | countSort(arr); 59 | 60 | cout << "Sorted character array is " << arr; 61 | return 0; 62 | } 63 | 64 | // This code is contributed by rathbhupendra 65 | 66 | -------------------------------------------------------------------------------- /Sorting Algos/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void heapify(int arr[], int n, int i) { 5 | // Find largest among root, left child and right child 6 | int largest = i; 7 | int left = 2 * i + 1; 8 | int right = 2 * i + 2; 9 | 10 | if (left < n && arr[left] > arr[largest]) 11 | largest = left; 12 | 13 | if (right < n && arr[right] > arr[largest]) 14 | largest = right; 15 | 16 | // Swap and continue heapifying if root is not largest 17 | if (largest != i) { 18 | swap(arr[i], arr[largest]); 19 | heapify(arr, n, largest); 20 | } 21 | } 22 | 23 | // main function to do heap sort 24 | void heapSort(int arr[], int n) { 25 | // Build max heap 26 | for (int i = n / 2 - 1; i >= 0; i--) 27 | heapify(arr, n, i); 28 | 29 | // Heap sort 30 | for (int i = n - 1; i >= 0; i--) { 31 | swap(arr[0], arr[i]); 32 | 33 | // Heapify root element to get highest element at root again 34 | heapify(arr, i, 0); 35 | } 36 | } 37 | 38 | // Print an array 39 | void display(int *array, int size) { 40 | for(int i = 0; i> n; 51 | int arr[n]; 52 | cout << "Enter elements:" << endl; 53 | for(int i = 0; i> arr[i]; 55 | } 56 | cout << "Array before Sorting: "; 57 | display(arr, n); 58 | heapSort(arr, n); 59 | cout << "Array after Sorting: "; 60 | display(arr, n); 61 | 62 | } -------------------------------------------------------------------------------- /Sorting Algos/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swapping(int &a, int &b) { //swap the content of a and b 5 | int temp; 6 | temp = a; 7 | a = b; 8 | b = temp; 9 | } 10 | 11 | void display(int *array, int size) { 12 | for(int i = 0; i> n; 70 | int arr[n]; 71 | cout << "Enter elements:" << endl; 72 | for(int i = 0; i> arr[i]; 74 | } 75 | cout << "Array before Sorting: "; 76 | display(arr, n); 77 | mergeSort(arr, 0, n-1); 78 | cout << "Array after Sorting: "; 79 | display(arr, n); 80 | } -------------------------------------------------------------------------------- /Sorting Algos/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Implementation of the Quick Sort Algorithm. 2 | #include 3 | using namespace std; 4 | 5 | void display(int *array, int size) { 6 | for(int i = 0; i pivotIndex) { 30 | 31 | while (arr[i] <= pivot) { 32 | i++; 33 | } 34 | 35 | while (arr[j] > pivot) { 36 | j--; 37 | } 38 | 39 | if (i < pivotIndex && j > pivotIndex) { 40 | swap(arr[i++], arr[j--]); 41 | } 42 | } 43 | 44 | return pivotIndex; 45 | } 46 | 47 | void quickSort(int arr[], int start, int end) 48 | { 49 | 50 | // base case 51 | if (start >= end) 52 | return; 53 | 54 | // partitioning the array 55 | int p = partition(arr, start, end); 56 | 57 | // Sorting the left part 58 | quickSort(arr, start, p - 1); 59 | 60 | // Sorting the right part 61 | quickSort(arr, p + 1, end); 62 | } 63 | 64 | int main() 65 | { 66 | int n; 67 | cout << "Enter the number of elements: "; 68 | cin >> n; 69 | int arr[n]; 70 | cout << "Enter elements:" << endl; 71 | for(int i = 0; i> arr[i]; 73 | } 74 | cout << "Array before Sorting: "; 75 | display(arr, n); 76 | quickSort(arr, 0,n-1); 77 | cout << "Array after Sorting: "; 78 | display(arr, n); 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /Sorting Algos/Selection sort.c: -------------------------------------------------------------------------------- 1 | // C program to implement selection sort 2 | // using recursion 3 | 4 | #include 5 | 6 | void SelectionSort(int arr[], int i, int j, int len, int flag) { 7 | if (i < len - 1) { 8 | if (flag) 9 | j = i + 1; 10 | 11 | if (j < len) { 12 | if (arr[i] > arr[j]) //Swap numbers 13 | { 14 | arr[i] = arr[i] + arr[j]; 15 | arr[j] = arr[i] - arr[j]; 16 | arr[i] = arr[i] - arr[j]; 17 | } 18 | SelectionSort(arr, i, j + 1, len, 0); 19 | } 20 | SelectionSort(arr, i + 1, 0, len, 1); 21 | } 22 | } 23 | 24 | int main() { 25 | int arr[] = { 26 | 23, 27 | 10, 28 | 46, 29 | 21, 30 | 75 31 | }; 32 | int i = 0; 33 | 34 | printf("Array before sorting: \n"); 35 | for (i = 0; i < 5; i++) 36 | printf("%d ", arr[i]); 37 | 38 | SelectionSort(arr, 0, 0, 5, 1); 39 | 40 | printf("\nArray after sorting: \n"); 41 | for (i = 0; i < 5; i++) 42 | printf("%d ", arr[i]); 43 | 44 | printf("\n"); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Sorting Algos/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // shell sort implementation 5 | int shellSort(int arr[], int N) 6 | { 7 | for (int gap = N/2; gap > 0; gap /= 2) 8 | { 9 | for (int i = gap; i < N; i += 1) 10 | { 11 | //sort sub lists created by applying gap 12 | int temp = arr[i]; 13 | 14 | int j; 15 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 16 | arr[j] = arr[j - gap]; 17 | 18 | arr[j] = temp; 19 | } 20 | } 21 | return 0; 22 | } 23 | 24 | int main() 25 | { 26 | int arr[] = {45,23,53,43,18,24,8,95,101}, i; 27 | //Calculate size of array 28 | int N = sizeof(arr)/sizeof(arr[0]); 29 | 30 | cout << "Array to be sorted: \n"; 31 | for (int i=0; i> ans; 3 | public List> findLadders(String beginWord, String endWord, List wordList) { 4 | ans=new ArrayList<>(); 5 | 6 | Map> graph = new HashMap<>(); 7 | for(String s: wordList) { 8 | graph.put(s, new ArrayList<>()); 9 | } 10 | //if beginword is not in graph then add it 11 | if(!graph.containsKey(beginWord)) { 12 | wordList.add(beginWord); 13 | graph.put(beginWord, new ArrayList<>()); 14 | } 15 | 16 | for(String s: wordList) { 17 | for(int i=0;i l=graph.get(s); 22 | l.add(checkWord); 23 | graph.put(s, l); 24 | } 25 | } 26 | } 27 | } 28 | 29 | Set visited=new HashSet<>(wordList.size()); 30 | Map distFromStarting = new HashMap<>(); //distance from begin node 31 | //will use it to calculate dfs in reverse order from endWord to beginWord 32 | 33 | 34 | int shortestLength = bfs(beginWord, endWord, graph, visited, distFromStarting); //for shortest path using bfs 35 | if(shortestLength==0) return ans; 36 | 37 | reverseDFS(endWord, beginWord, new ArrayList<>(), graph, distFromStarting); 38 | return ans; 39 | } 40 | 41 | //from source to destination bfs 42 | public int bfs(String src, String des, Map> graph, Set visited, Map distFromStarting) { 43 | List> ans=new ArrayList<>(); 44 | 45 | Queue queue=new LinkedList<>(); 46 | queue.add(src); 47 | visited.add(src); 48 | int level=0; 49 | distFromStarting.put(src, 0); 50 | 51 | while(!queue.isEmpty()) { 52 | int size=queue.size(); 53 | 54 | for(int i=0;i path, Map> graph, Map distFromStarting) { 74 | if(src.equals(des)) { 75 | path.add(des); 76 | List list=new ArrayList<>(path); 77 | Collections.reverse(list); 78 | 79 | ans.add(list); 80 | path.remove(path.size()-1); 81 | return; 82 | } 83 | 84 | path.add(src); 85 | 86 | 87 | for(String next: graph.get(src)) { 88 | if(distFromStarting.containsKey(next) && distFromStarting.get(next)+1==distFromStarting.get(src)) { 89 | reverseDFS(next, des, path, graph, distFromStarting); 90 | } 91 | } 92 | 93 | path.remove(path.size()-1); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /css bubbles in cup animation/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Basic Web Page 7 | 10 | 132 | 133 | 134 |
135 |
136 |
137 |
138 |
139 | 140 |
141 |
142 |
143 |
144 |
145 |
146 | 147 |
148 | 149 |
150 |
151 | 152 | 153 | -------------------------------------------------------------------------------- /lambda_in_cplusplus.cpp: -------------------------------------------------------------------------------- 1 | //lambda function in c++ 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int a=2,b=3; 7 | auto sum=[&a](int b){return a+b;}; //capture by reference in lambda function 8 | cout< &dp){ 4 | 5 | dp[0] = 1; 6 | dp[1] = 1; 7 | 8 | for(int i=2;i<=n;i++){ 9 | int left = dp[i-1]; 10 | int right = dp[i-2]; 11 | dp[i] = left+ right; 12 | } 13 | 14 | return dp[n-1]; 15 | } 16 | 17 | 18 | int climbStairs(int n) { 19 | 20 | vector dp(n+1, 0); 21 | 22 | dp[0] = 1; 23 | dp[1] = 1; 24 | 25 | for(int i=2;i<=n;i++){ 26 | int left = dp[i-1]; 27 | int right = dp[i-2]; 28 | dp[i] = left+ right; 29 | } 30 | 31 | return dp[n]; 32 | } 33 | 34 | }; 35 | -------------------------------------------------------------------------------- /leetcode q/FirstandLastPosition.java: -------------------------------------------------------------------------------- 1 | package com.binarysearch; 2 | 3 | import java.util.Arrays; 4 | 5 | public class FirstandLastPosition { 6 | public static void main(String[] args) { 7 | int[] Arr = {1}; 8 | int target = 1; 9 | System.out.println(Arrays.toString(Search(Arr, target))); 10 | } 11 | static int[] Search(int[] arr, int target) { 12 | int v1 = -1; 13 | int v2 = -1; 14 | for (int i = 0; i < arr.length; i++) { 15 | int i1 = arr[i]; 16 | if (i1 == target) { 17 | v1 = i; 18 | break; 19 | } else { 20 | v1 = -1; 21 | } 22 | } 23 | for (int i = arr.length - 1; i >= 0; i--) { 24 | if (arr[i] == target) { 25 | v2 = i; 26 | break; 27 | } else 28 | v2 = -1; 29 | } 30 | return new int[] {v1, v2}; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode q/Interleaving Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[1001][1001]; 4 | bool solve(string A, string B, string C, int n,int m,int len){ 5 | if(len==0) return 1; 6 | if(dp[n][m]!=-1) return dp[n][m]; 7 | int a,b; 8 | a=b=0; 9 | if(n-1>=0 && A[n-1]==C[len-1]) a=solve(A,B,C,n-1,m,len-1); 10 | if(m-1>=0 && B[m-1]==C[len-1]) b=solve(A,B,C,n,m-1,len-1); 11 | return dp[n][m]=a or b; 12 | } 13 | bool isInterleave(string A, string B, string C) 14 | { 15 | int n= A.length(); 16 | int m= B.length(); 17 | int len=C.length(); 18 | if(n+m!=len) return 0; 19 | dp[n][m]; 20 | memset(dp,-1,sizeof(dp)); 21 | return solve(A,B,C,n,m,len); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /leetcode q/Subarrays with K Different Integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //num with atmost k subarrays- atmost k-1 subarays 4 | int number(vector &nums, int k){ 5 | int ans=0, c=0, j=0; 6 | unordered_mapcnt; 7 | for(int i=0;ik){ 11 | cnt[nums[j]]--; 12 | if(cnt[nums[j]]==0) 13 | cnt.erase(nums[j]), c--; 14 | j++; 15 | } 16 | ans+=i-j+1; 17 | } 18 | 19 | return ans; 20 | } 21 | 22 | int subarraysWithKDistinct(vector& nums, int k) { 23 | return number(nums, k) - number(nums, k-1); 24 | } 25 | }; -------------------------------------------------------------------------------- /leetcode q/Zig_Zag_Conversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | string convert(string s, int numRows) 8 | { 9 | if (numRows == 1) 10 | { 11 | return s; 12 | } 13 | vector rows(min(numRows, int(s.size()))); 14 | int curRow = 0; 15 | bool goingDown = false; 16 | for (char c : s) 17 | { 18 | rows[curRow] += c; 19 | if (curRow == 0 || curRow == numRows - 1) 20 | { 21 | goingDown = !goingDown; 22 | } 23 | curRow += goingDown ? 1 : -1; 24 | } 25 | string ans; 26 | for (string row : rows) 27 | { 28 | ans += row; 29 | } 30 | return ans; 31 | } 32 | }; 33 | 34 | int main() 35 | { 36 | Solution s; 37 | cout << s.convert("PAYPALISHIRING", 3) << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /leetcode q/reverseNodes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverse(ListNode* head, ListNode* tail) { 4 | ListNode* current = head; 5 | ListNode *prev = NULL, *next = NULL; 6 | if(head==NULL) 7 | return head; 8 | if(head==tail) 9 | return head; 10 | ListNode* h1=reverse(head->next,tail); 11 | ListNode* nx=head->next; 12 | nx->next=head; 13 | head->next=NULL; 14 | return h1; 15 | } 16 | 17 | ListNode* reverseKGroup(ListNode* head, int k) 18 | { 19 | if(head==NULL) 20 | return head; 21 | int sz=1; 22 | ListNode* temp=head; 23 | while(temp&&sznext; 27 | 28 | 29 | } 30 | 31 | if(sznext,k); 35 | ListNode* rev=reverse(head,temp); 36 | head->next=nx; 37 | return rev; 38 | 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /leetcode q/twosumII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | vector ans(2); 5 | int i =0,j = nums.size()-1; 6 | 7 | while(itarget) 10 | { 11 | j--; 12 | } 13 | else if(nums[i]+nums[j]>& board) { 4 | vector> rows(9), cols(9), blocks(9); 5 | 6 | for (int i = 0; i < 9; i++) { 7 | for (int j = 0; j < 9; j++) { 8 | 9 | if (board[i][j] == '.') continue; 10 | 11 | int curr = board[i][j] - '0'; 12 | if (rows[i].count(curr) || cols[j].count(curr) || blocks[(i/3)*3+j/3].count(curr)) 13 | return false; 14 | 15 | rows[i].insert(curr); 16 | cols[j].insert(curr); 17 | blocks[(i/3)*3+j/3].insert(curr); 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /leetcode q/wildcard_matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | int m=s.size(); 5 | int n=p.size(); 6 | vector>dp(m+1,vector(n+1,0)); 7 | dp[0][0]=1; 8 | for(int i=1;i<=n;i++){ 9 | int f=0; 10 | for(int j=1;j<=i;j++){ 11 | if(p[j-1]!='*'){ 12 | f=1; 13 | dp[0][i]=0; 14 | } 15 | } 16 | if(f==0){ 17 | dp[0][i]=1; 18 | } 19 | } 20 | for(int i=1;i<=m;i++){ 21 | dp[i][0]=0; 22 | } 23 | for(int i=1;i<=m;i++){ 24 | for(int j=1;j<=n;j++){ 25 | if(p[j-1]=='?' || p[j-1] == s[i-1]){ 26 | dp[i][j] = dp[i-1][j-1]; 27 | }else if(p[j-1]=='*'){ 28 | dp[i][j] = dp[i-1][j] | dp[i][j-1]; 29 | }else{ 30 | dp[i][j] = 0; 31 | } 32 | } 33 | } 34 | return dp[m][n]; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /sort an array: -------------------------------------------------------------------------------- 1 | #include 2 | void main() 3 | { 4 | 5 | int i, j, a, n, number[30]; 6 | printf("Enter the value of N \n"); 7 | scanf("%d", &n); 8 | 9 | printf("Enter the numbers \n"); 10 | for (i = 0; i < n; ++i) 11 | scanf("%d", &number[i]); 12 | 13 | for (i = 0; i < n; ++i) 14 | { 15 | 16 | for (j = i + 1; j < n; ++j) 17 | { 18 | 19 | if (number[i] > number[j]) 20 | { 21 | 22 | a = number[i]; 23 | number[i] = number[j]; 24 | number[j] = a; 25 | 26 | } 27 | 28 | } 29 | 30 | } 31 | 32 | printf("The numbers arranged in ascending order are given below \n"); 33 | for (i = 0; i < n; ++i) 34 | printf("%d\n", number[i]); 35 | 36 | } 37 | --------------------------------------------------------------------------------