├── _config.yml ├── Swift ├── fibonacci.swift ├── permutations-and-combinations.swift ├── bubble-sort.swift ├── insertion-sort.swift ├── selection-sort.swift ├── count-sort.swift ├── shell-sort.swift ├── quick-sort.swift └── merge-sort.swift ├── Python ├── bubble-sort.py ├── insertion-sort.py ├── binary-search.py ├── floyds-triangle.py ├── knapsack.py ├── counting-sort.py ├── selection-sort.py ├── dijkstras-algorithm.py ├── cocktail-sort.py ├── radix-sort.py ├── merge-sort.py ├── first-unique-character.py ├── quicksort-sort.py ├── segment-tree.py ├── 8-queens.py ├── combinations.py ├── lazy-segment-tree.py ├── singly-linked-list.py └── avl-tree.py ├── C++ ├── check-prime ├── greedyalgo-coinchange.cpp ├── euclid-extended.cpp ├── sliding-window-tech.cpp ├── tower-of-hanoi.cpp ├── bubble-sort.cpp ├── dnf-sort.cpp ├── kanade-algorithm.cpp ├── insertion-sort.cpp ├── quick-sort.cpp ├── cocktail-sort.cpp ├── heap-sort.cpp ├── find-sum-at-level-k ├── selection-sort.cpp ├── n-queens-backtracking.cpp ├── tree-bfs.cpp ├── counting-sort.cpp ├── floyd-warshall-algorithm.cpp ├── binary-search.cpp ├── radix-sort.cpp ├── triplets.cpp ├── tree-dfs.cpp ├── string-match.cpp ├── dijkstras-algorithm.cpp ├── rabin-karp-algorithm ├── polygon-triangulation.cpp ├── edmonds-karp-algorithm.cpp ├── topological-sort.cpp ├── merge-sort.cpp ├── insertion-and-deletion-in-stack.cpp ├── infix-to-prefix-postfix.cpp ├── linked-list-insertion.cpp ├── circular-linked-list-insertion-deletion.cpp ├── linked-list-deletion.cpp ├── tic-tac-toe.cpp └── snake-game.cpp ├── .vscode ├── c_cpp_properties.json ├── settings.json └── launch.json ├── C ├── tower-of-hanoi.c ├── floyds-all-pair-shortest-path.c ├── traverse-singly-linked-list.c ├── quick-sort.c ├── count-sort.c ├── cocktail-sort.c ├── generic-tree.c ├── merge-sort.c └── hash-tables.c ├── Java ├── insertion-sort.java ├── binary-search.java ├── cyclic-sort.java ├── bubble-sort.java ├── selection-sort.java ├── cocktail-sort.java ├── merge-sort.java ├── heap-sort.java ├── quick-sort.java ├── hamiltonianCycle.java └── z-algorithm.java ├── HTML ├── digital-clock.html └── site-music.html ├── CONTRIBUTING.md ├── travelling.java └── README.md /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /Swift/fibonacci.swift: -------------------------------------------------------------------------------- 1 | func fibonacci(_ n: Int, _ a:Int=0, _ b:Int=1) -> Int{ 2 | if n==0 { return a } 3 | if n==1 { return b } 4 | return fibonacci(n-1, b, a+b) 5 | } 6 | 7 | for i in 0...12 { 8 | print(fibonacci(i)) 9 | } 10 | -------------------------------------------------------------------------------- /Python/bubble-sort.py: -------------------------------------------------------------------------------- 1 | 2 | l=[4,2,5,6,23,7,9,33,7,5,8,9,7,3] 3 | 4 | flag=True 5 | 6 | while(flag): 7 | flag=False 8 | j=0 9 | for i in range(len(l)-1-j): 10 | if(l[i]>l[i+1]): 11 | l[i],l[i+1]=l[i+1],l[i] 12 | flag=True 13 | 14 | print(l) -------------------------------------------------------------------------------- /Python/insertion-sort.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().split(" "))) 2 | 3 | for i in range(1, len(arr)): 4 | key = arr[i] 5 | j = i-1 6 | while j >= 0 and key < arr[j] : 7 | arr[j + 1] = arr[j] 8 | j -= 1 9 | arr[j + 1] = key 10 | 11 | for i in arr: 12 | print(i, end=" ") 13 | print() -------------------------------------------------------------------------------- /Python/binary-search.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, n): 2 | st = 0 3 | end = len(arr) - 1 4 | while(st < end): 5 | mid = (st+end)//2 6 | if arr[mid] == n: 7 | return True 8 | elif arr[mid] < n: 9 | end = mid-1 10 | else: 11 | st = mid+1 12 | return False 13 | -------------------------------------------------------------------------------- /Python/floyds-triangle.py: -------------------------------------------------------------------------------- 1 | def floyd(n): 2 | count = 1 3 | string = "" 4 | for i in range(1,n+2): 5 | for j in range(1,i): 6 | string = string + " " + str(count) 7 | count = count + 1 8 | print(string) 9 | string = "" 10 | n=int (input("Enter rows: ")) 11 | floyd(n) 12 | -------------------------------------------------------------------------------- /Python/knapsack.py: -------------------------------------------------------------------------------- 1 | value =[10, 40, 20, 30] 2 | weight =[60, 40, 100, 120] 3 | W =50 4 | n =len(value) 5 | A =[[0 for x in range(W + 1)] for x in range(n + 1)] 6 | for i in range(n + 1): 7 | for w in range(W + 1): 8 | if i == 0 or w == 0: 9 | A[i][w] = 0 10 | elif weight[i-1] <= w: 11 | A[i][w] = max(value[i-1] + A[i-1][w-weight[i-1]], A[i-1][w]) 12 | else: 13 | A[i][w] = A[i-1][w] 14 | print(A[n][W]) 15 | -------------------------------------------------------------------------------- /Python/counting-sort.py: -------------------------------------------------------------------------------- 1 | def counting_sort_op(arr): 2 | max_ele = max(arr) 3 | min_ele = min(arr) 4 | freq = {i:0 for i in range(min_ele,max_ele+1)} 5 | for i in arr: 6 | freq[i] += 1 7 | sorted = [] 8 | for k,v in freq.items(): 9 | if(v != 0): 10 | for j in range(v): 11 | sorted.append(k) 12 | return sorted 13 | 14 | print(counting_sort_op([1,-10,-1,-2,-2,2,2,1,3,4,5])) 15 | -------------------------------------------------------------------------------- /C++/check-prime: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | ios_base::sync_with_stdio(false); 6 | cin.tie(NULL); 7 | cout.tie(NULL); 8 | 9 | int n,i; 10 | cin>>n; 11 | for(i=2;i<=sqrt(n);i++) 12 | { 13 | if(n%i==0) 14 | { 15 | cout<<"Not Prime"; 16 | break; 17 | } 18 | } 19 | if(i>sqrt(n)) 20 | cout<<"Prime"; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "macos-gcc-x64", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "/usr/bin/clang", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "macos-gcc-x64", 12 | "compilerArgs": [ 13 | "-Wall", 14 | "-Wextra", 15 | "-Wpedantic" 16 | ] 17 | } 18 | ], 19 | "version": 4 20 | } -------------------------------------------------------------------------------- /C++/greedyalgo-coinchange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Author Lakshay Goel 3 | Github profile: https://github.com/MrLakshay 4 | Problem statement : Given coins worth 1 ,5 and 10 in unlimited quantity need to find 5 | minimum number of coins 'x' to make 'n' sum of money input by user. 6 | Input: n 7 | Output : x 8 | Exampple: 9 | 17 10 | 4 11 | */ 12 | #include 13 | using namespace std; 14 | int main(){ 15 | int t; 16 | cin>>t; 17 | cout< Int { 3 | if n==0 { return 1 } 4 | if n==1 { return a } 5 | return factorial(n-1, n*a) 6 | } 7 | 8 | func combinations(n: Int, r: Int) -> Int { 9 | return factorial(n)/(factorial(r)*factorial(n-r)) 10 | } 11 | 12 | func permutations(n: Int, r: Int) -> Int { 13 | return factorial(n)/factorial(n-r) 14 | } 15 | 16 | print(factorial(10)) 17 | print(combinations(n: 8, r: 4)) 18 | print(permutations(n: 8, r: 4)) 19 | -------------------------------------------------------------------------------- /Python/selection-sort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(itemsList): 2 | n = len(itemsList) 3 | for i in range(n - 1): 4 | minValueIndex = i 5 | 6 | for j in range(i + 1, n): 7 | if itemsList[j] < itemsList[minValueIndex]: 8 | minValueIndex = j 9 | 10 | if minValueIndex != i: 11 | temp = itemsList[i] 12 | itemsList[i] = itemsList[minValueIndex] 13 | itemsList[minValueIndex] = temp 14 | 15 | return itemsList 16 | 17 | 18 | el = [21, 6, 9, 33, 3] 19 | 20 | print(selectionSort(el)) -------------------------------------------------------------------------------- /C++/euclid-extended.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int gcdExtended(int a, int b, int *x, int *y) 5 | { 6 | if (a == 0) 7 | { 8 | *x = 0; 9 | *y = 1; 10 | return b; 11 | } 12 | 13 | int x1, y1; 14 | int gcd = gcdExtended(b%a, a, &x1, &y1); 15 | 16 | *x = y1 - (b/a) * x1; 17 | *y = x1; 18 | 19 | return gcd; 20 | } 21 | 22 | 23 | int main() 24 | { 25 | int x, y,a,b; 26 | cout<<"Enter the numbers : "<>a>>b; 28 | int g = gcdExtended(a, b, &x, &y); 29 | cout << "GCD(" << a << ", " << b<< ") = " << g << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Swift/bubble-sort.swift: -------------------------------------------------------------------------------- 1 | func bubbleSort(_ list: inout [T]) { 2 | let n = list.count 3 | for i in 0.. list[j+1] { 6 | let tmp = list[j] 7 | list[j] = list[j+1] 8 | list[j+1] = tmp 9 | } 10 | } 11 | } 12 | } 13 | 14 | func bubbleSort(_ list: [T]) -> [T] { 15 | var temp = list 16 | bubbleSort(&temp) 17 | return temp 18 | } 19 | 20 | var list = ["a", "d", "b", "c"] 21 | var list2 = [4, 2, 1, 3] 22 | bubbleSort(&list) 23 | print(list) 24 | print(bubbleSort(list2)) 25 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp_Runner.cCompilerPath": "/usr/bin/clang", 3 | "C_Cpp_Runner.cppCompilerPath": "/usr/bin/clang++", 4 | "C_Cpp_Runner.debuggerPath": "/usr/bin/lldb", 5 | "C_Cpp_Runner.makePath": "/usr/bin/make", 6 | "C_Cpp_Runner.warnings": [ 7 | "-Wall", 8 | "-Wextra", 9 | "-Wpedantic" 10 | ], 11 | "C_Cpp_Runner.compilerArgs": [], 12 | "C_Cpp_Runner.includePaths": [], 13 | "C_Cpp_Runner.linkerArgs": [], 14 | "C_Cpp_Runner.cStandard": "", 15 | "C_Cpp_Runner.cppStandard": "", 16 | "C_Cpp_Runner.excludeSearch": [], 17 | "C_Cpp_Runner.enableWarnings": true, 18 | "C_Cpp_Runner.warningsAsError": false 19 | } -------------------------------------------------------------------------------- /Python/dijkstras-algorithm.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import PriorityQueue, Graph, Vertex 2 | 3 | def dijkstra(aGraph,start): 4 | pq = PriorityQueue() 5 | start.setDistance(0) 6 | pq.buildHeap([(v.getDistance(),v) for v in aGraph]) 7 | while not pq.isEmpty(): 8 | currentVert = pq.delMin() 9 | for nextVert in currentVert.getConnections(): 10 | newDist = currentVert.getDistance() \ 11 | + currentVert.getWeight(nextVert) 12 | if newDist < nextVert.getDistance(): 13 | nextVert.setDistance( newDist ) 14 | nextVert.setPred(currentVert) 15 | pq.decreaseKey(nextVert,newDist) -------------------------------------------------------------------------------- /Swift/insertion-sort.swift: -------------------------------------------------------------------------------- 1 | func insertionSort(_ array: [T]) -> [T] { 2 | var sortedArray = array 3 | for index in 1.. 0 && temp < sortedArray[currentIndex - 1] { 7 | sortedArray[currentIndex] = sortedArray[currentIndex - 1] 8 | currentIndex -= 1 9 | } 10 | sortedArray[currentIndex] = temp 11 | } 12 | return sortedArray 13 | } 14 | 15 | let list1 = ["f", "e", "d", "b", "a", "c"] 16 | print(insertionSort(list1)) 17 | 18 | let list2 = [5, 2, 1, 6, 4, 3] 19 | print(insertionSort(list2)) -------------------------------------------------------------------------------- /Swift/selection-sort.swift: -------------------------------------------------------------------------------- 1 | func selectionSort(_ list: inout [T]) { 2 | let N = list.count 3 | for i in 0.. list[j] { 7 | minIndex = j 8 | } 9 | } 10 | let tmp = list[i] 11 | list[i] = list[minIndex] 12 | list[minIndex] = tmp 13 | } 14 | } 15 | 16 | func selectionSort(_ list: [T]) -> [T] { 17 | var temp = list 18 | selectionSort(&temp) 19 | return temp 20 | } 21 | 22 | var list = ["a", "d", "b", "c"] 23 | var list2 = [4,2,1,3] 24 | selectionSort(&list) 25 | print(list) 26 | print(selectionSort(list2)) 27 | -------------------------------------------------------------------------------- /C/tower-of-hanoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | void towers(int, char, char, char); 3 | int main() 4 | { 5 | int num; 6 | printf("Enter the Number of disks: "); 7 | scanf("%d", &num); 8 | printf("The Sequence of moves involved in the tower of hanoi are: "); 9 | towers(num, 'A', 'B', 'C'); 10 | return 0; 11 | } 12 | 13 | void towers(int num, char frompeg, char topeg, char auxpeg) 14 | { 15 | if (num == 1) 16 | { 17 | printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg); 18 | return; 19 | } 20 | towers(num - 1, frompeg, auxpeg, topeg); 21 | printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg); 22 | towers(num - 1, auxpeg, topeg, frompeg); 23 | } -------------------------------------------------------------------------------- /Java/insertion-sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | 4 | public class InsertionSort { 5 | public static void main(String[] args){ 6 | 7 | int[] array = {1,1,1,1,1,1}; 8 | 9 | insertion(array); 10 | System.out.println(Arrays.toString(array)); 11 | } 12 | static void insertion(int[] array){ 13 | int temp; 14 | for(int i=0;i0;j--){ 16 | if(array[j] 2 | using namespace std; 3 | 4 | 5 | int maxSum(int arr[], int n, int k) 6 | { 7 | // Initialize result 8 | int max_sum = INT_MIN; 9 | 10 | // Consider all blocks starting with i. 11 | for (int i = 0; i < n - k + 1; i++) { 12 | int curr_sum = 0; 13 | for (int j = 0; j < k; j++) 14 | curr_sum = curr_sum + arr[i + j]; 15 | 16 | // Update result if required. 17 | max_sum = max(curr_sum, max_sum); 18 | } 19 | 20 | return max_sum; 21 | } 22 | 23 | int main() 24 | { 25 | int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; 26 | int k = 4; 27 | int n = sizeof(arr) / sizeof(arr[0]); 28 | cout << maxSum(arr, n, k); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /C++/tower-of-hanoi.cpp: -------------------------------------------------------------------------------- 1 | // C++ recursive function to 2 | // solve tower of hanoi puzzle 3 | #include 4 | using namespace std; 5 | 6 | void towerOfHanoi(int n, char from_rod, 7 | char to_rod, char aux_rod) 8 | { 9 | if (n == 1) 10 | { 11 | cout << "Move disk 1 from rod " << from_rod << 12 | " to rod " << to_rod << endl; 13 | return; 14 | } 15 | towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); 16 | cout << "Move disk " << n << " from rod " << from_rod << 17 | " to rod " << to_rod << endl; 18 | towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); 19 | } 20 | 21 | // Driver code 22 | int main() 23 | { 24 | int n = 4; // Number of disks 25 | towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /C++/bubble-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n, i, arr[50], j, temp; 6 | cout<<"Enter the Size (max. 50): "; 7 | cin>>n; 8 | cout<<"Enter "<>arr[i]; 11 | cout<<"\nSorting the Array using Bubble Sort \n"; 12 | for(i=0; i<(n-1); i++) 13 | { 14 | for(j=0; j<(n-i-1); j++) 15 | { 16 | if(arr[j]>arr[j+1]) 17 | { 18 | temp = arr[j]; 19 | arr[j] = arr[j+1]; 20 | arr[j+1] = temp; 21 | } 22 | } 23 | } 24 | cout<<"\nArray Sorted Successfully!\n"; 25 | cout<<"\nThe New Array is: \n"; 26 | for(i=0; i 2 | #include 3 | using namespace std; 4 | 5 | void swap(vector &arr, int i, int j){ 6 | int temp = arr[i]; 7 | arr[i] = arr[j]; 8 | arr[j] = temp; 9 | } 10 | 11 | void dutchFlagSort(vector &arr){ 12 | int low = 0, high = arr.size() - 1; 13 | for(int i = 0; i <= high;){ 14 | if (arr[i] == 0){ 15 | swap(arr, i, low); 16 | i++; 17 | low++; 18 | } else if (arr[i] == 1){ 19 | i++; 20 | } else{ 21 | swap(arr,i,high); 22 | high--; 23 | } 24 | } 25 | } 26 | 27 | int main(){ 28 | 29 | vector arr = {1,0,2,1,0,2,1,0,2,2,1,0}; 30 | dutchFlagSort(arr); 31 | for(auto num : arr) 32 | cout << num << " "; 33 | 34 | cout << endl; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Swift/count-sort.swift: -------------------------------------------------------------------------------- 1 | 2 | func countSort(_ array: [Int]) -> [Int] { 3 | guard array.count > 0 else { 4 | return array 5 | } 6 | 7 | let maxElement = array.max() ?? 0 8 | 9 | var countArray = [Int](repeating: 0, count: Int(maxElement + 1)) 10 | for element in array { 11 | countArray[element] += 1 12 | } 13 | 14 | for index in 1 ..< countArray.count { 15 | let sum = countArray[index] + countArray[index - 1] 16 | countArray[index] = sum 17 | } 18 | 19 | var sortedArray = [Int](repeating: 0, count: array.count) 20 | for index in stride(from: array.count - 1, through: 0, by: -1) { 21 | let element = array[index] 22 | countArray[element] -= 1 23 | sortedArray[countArray[element]] = element 24 | } 25 | 26 | return sortedArray 27 | } 28 | 29 | let list1 = [5, 2, 1, 6, 4, 3] 30 | print(countSort(list1)) -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "cwd": "/Users/raj/Desktop/OpenSource/Hacktoberfest21_Algo_Collection", 11 | "environment": [], 12 | "program": "/Users/raj/Desktop/OpenSource/Hacktoberfest21_Algo_Collection/build/Debug/outDebug", 13 | "internalConsoleOptions": "openOnSessionStart", 14 | "MIMode": "lldb", 15 | "miDebuggerPath": "/usr/bin/lldb", 16 | "externalConsole": false, 17 | "setupCommands": [ 18 | { 19 | "description": "Enable pretty-printing for gdb", 20 | "text": "-enable-pretty-printing", 21 | "ignoreFailures": true 22 | } 23 | ] 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /C++/kanade-algorithm.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print largest contiguous array sum 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0; 9 | 10 | for (int i = 0; i < size; i++) 11 | { 12 | max_ending_here = max_ending_here + a[i]; 13 | if (max_so_far < max_ending_here) 14 | max_so_far = max_ending_here; 15 | 16 | if (max_ending_here < 0) 17 | max_ending_here = 0; 18 | } 19 | return max_so_far; 20 | } 21 | 22 | /*Driver program to test maxSubArraySum*/ 23 | int main() 24 | { 25 | int a[] = { -2, -3, 4, -1, -2, 1, 5, -3}; 26 | int n = sizeof(a) / sizeof(a[0]); 27 | int max_sum = maxSubArraySum(a, n); 28 | cout << "Maximum contiguous sum is " << max_sum; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Java/binary-search.java: -------------------------------------------------------------------------------- 1 | class BinarySearchAlgorithm{ 2 | 3 | public static void binarySearch(int arr[], int first, int last, int key){ 4 | int mid= (first + last)/2; 5 | 6 | while(first<=last){ 7 | if ( arr[mid] < key ){ 8 | first = mid + 1; 9 | }else if(arr[mid] == key){ 10 | System.out.println("Element is found at index: " + mid); 11 | break; 12 | }else{ 13 | last = mid - 1; 14 | } 15 | mid = (first + last)/2; 16 | } 17 | 18 | if (first>last){ 19 | System.out.println("Element not found!"); 20 | } 21 | 22 | } 23 | 24 | public static void main(String args[]){ 25 | int arr[] = {10, 20, 30, 40, 50}; 26 | int key = 30; 27 | int last=arr.length-1; 28 | binarySearch(arr, 0, last,key); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Python/cocktail-sort.py: -------------------------------------------------------------------------------- 1 | # Alogrithm for Cocktail Sort to sort element in ascending order 2 | 3 | def cocktailSort(array): 4 | arrayLen = len(array) 5 | check = 1 6 | while(check == 1): 7 | check = 0 8 | for x in range(arrayLen-1): 9 | if (array[x] > array[x+1]): 10 | check = 1 11 | array[x], array[x+1] = array[x+1], array[x] 12 | if (x == arrayLen - 1): 13 | break 14 | if (check == 1): 15 | check = 0 16 | for y in reversed(range(arrayLen -1)): 17 | if array[y] > array[y+1]: 18 | check = 1 19 | array[y], array[y+1] = array[y+1], array[y] 20 | if (y == 0): 21 | break 22 | 23 | numbers = [3,45,1,3,2,8,5,0] 24 | print("Unsorted Numbers: ", numbers) 25 | cocktailSort(numbers) 26 | print("Sorted Numbers: ", numbers) -------------------------------------------------------------------------------- /Swift/shell-sort.swift: -------------------------------------------------------------------------------- 1 | func insertionSort(_ list: inout [T], start: Int, gap: Int) { 2 | for i in stride(from: (start + gap), to: list.count, by: gap) { 3 | let currentValue = list[i] 4 | var pos = i 5 | while pos >= gap && list[pos - gap] > currentValue { 6 | list[pos] = list[pos - gap] 7 | pos -= gap 8 | } 9 | list[pos] = currentValue 10 | } 11 | } 12 | 13 | func shellSort(_ list: inout [T]) { 14 | var sublistCount = list.count / 2 15 | while sublistCount > 0 { 16 | for pos in 0.. 2 | #include 3 | #include 4 | 5 | void insertionSort(int arr[], int length) { 6 | int i, j, tmp; 7 | for (i = 1; i < length; i++) { 8 | j = i; 9 | while (j > 0 && arr[j - 1] > arr[j]) { 10 | tmp = arr[j]; 11 | arr[j] = arr[j - 1]; 12 | arr[j - 1] = tmp; 13 | j--; 14 | } 15 | } 16 | } 17 | 18 | int printArray( int arr[], int length ) { 19 | printf("{ "); 20 | for( int i=0; i 2 | using namespace std; 3 | int partition(int a[], int start, int end) 4 | { 5 | int x = a[start], i = start, k = start + 1, temp; 6 | for (; k <= end; k++) 7 | { 8 | if (a[k] = end) 23 | return; 24 | int i = partition(a, start, end); 25 | 26 | quick_sort(a, start, i); 27 | quick_sort(a, i + 1, end); 28 | } 29 | int main() 30 | { 31 | int a[] = {4, 1, 3, 9, 7}; 32 | int size = sizeof(a) / sizeof(a[0]); 33 | quick_sort(a, 0, size - 1); 34 | for (int i = 0; i < size; i++) 35 | { 36 | cout<arr[j]){ 24 | temp=arr[j-1]; 25 | arr[j-1]=arr[j]; 26 | arr[j]=temp; 27 | swapped=true; 28 | } 29 | } 30 | if(!swapped){ 31 | break; 32 | } 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java/selection-sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | public class SelectionSort { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | int l = in.nextInt(); 8 | int[] arr = new int[l]; 9 | int start=0; 10 | for(int i=0;iarr[max]){ 26 | max=i; 27 | } 28 | } 29 | return max; 30 | } 31 | static void swap(int[] arr,int maxi,int last){ 32 | int temp=arr[maxi]; 33 | arr[maxi]=arr[last]; 34 | arr[last]=temp; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /C++/cocktail-sort.cpp: -------------------------------------------------------------------------------- 1 | // Alogrithm for Cocktail Sort to sort element in ascending order 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void cocktailSort(vector&v, int n){ 8 | bool sorted = true; 9 | 10 | for(int i=0;iv[i+1]){ 12 | swap(v[i],v[i+1]); 13 | sorted = false; 14 | } 15 | } 16 | 17 | if(sorted) 18 | return; 19 | 20 | sorted = false; 21 | 22 | for(int i=n-1;i>0;i--){ 23 | if(v[i]>n; 39 | 40 | if(n<0){ 41 | return 0; 42 | } 43 | 44 | vector v(n,0); 45 | 46 | for(int i=0;i>v[i]; 48 | } 49 | 50 | cocktailSort(v,n); 51 | 52 | for(int i=0;i 2 | #include 3 | #define max 10 4 | void floyd(int [][max],int); 5 | int min(int,int); 6 | int main() 7 | { 8 | int n,d[max][max],i,j; 9 | printf("Enter the no of nodes: "); 10 | scanf("%d",&n); 11 | printf("Enter the weight matrix:\n"); 12 | for(i=1;i<=n;i++) 13 | { 14 | for(j=1;j<=n;j++) 15 | { 16 | scanf("%d",&d[i][j]); 17 | } 18 | } 19 | floyd(d,n); 20 | printf("Distance Mtarix\n"); 21 | for(i=1;i<=n;i++) 22 | { 23 | for(j=1;j<=n;j++) 24 | { 25 | printf("%d ",d[i][j]); 26 | } 27 | printf("\n"); 28 | } 29 | return 0; 30 | } 31 | void floyd(int d[][max],int n) 32 | { 33 | int i,j,k; 34 | for(k=1;k<=n;k++) 35 | { 36 | for(i=1;i<=n;i++) 37 | { 38 | for(j=1;j<=n;j++) 39 | { 40 | d[i][j]=min(d[i][j],(d[i][k]+d[k][j])); 41 | } 42 | } 43 | } 44 | } 45 | int min(int a,int b) 46 | { 47 | return (a>b)?b:a; 48 | } 49 | -------------------------------------------------------------------------------- /C++/heap-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int maxhepify(int a[],int n,int i) 5 | { 6 | int largest=i; 7 | int l=(2*i)+1; 8 | int r=(2*i)+2; 9 | while(la[largest]) 10 | {largest=l;} 11 | while(ra[largest]) 12 | {largest=r;} 13 | if(largest!=i) 14 | { 15 | swap(a[largest],a[i]); 16 | maxhepify(a,n,largest); 17 | } 18 | } 19 | int heap_sort(int a[],int n) 20 | { 21 | int i; 22 | for(i=n/2-1;i>=0;i--) 23 | maxhepify(a,n,i); 24 | for(i=n-1;i>=0;i--) 25 | { 26 | swap(a[0],a[i]); 27 | maxhepify(a,i,0); 28 | } 29 | } 30 | int main() 31 | { 32 | int i,n; 33 | cout<<"enter size of array:"; 34 | cin>>n; 35 | int a[n]; 36 | cout<<"enter elements of array:"; 37 | for(i=0;i>a[i]; 39 | cout<<"before sorting:"< 2 | using namespace std; 3 | class node{ 4 | public: 5 | int data; 6 | node* left; 7 | node* right; 8 | 9 | node(int d){ 10 | data = d; 11 | left = right = NULL; 12 | } 13 | }; 14 | node* buildTree(){ 15 | int d,c; 16 | cin>>d>>c; 17 | node* root = new node(d); 18 | if(c==0) 19 | { 20 | 21 | } 22 | else if(c==1) 23 | { 24 | root->left = buildTree(); 25 | } 26 | else if(c==2) 27 | { 28 | root->left = buildTree(); 29 | root->right = buildTree(); 30 | } 31 | return root; 32 | 33 | 34 | } 35 | void findSum(node* root , int k, int &sum){ 36 | 37 | if(root==NULL) 38 | return; 39 | 40 | if(k==0){ 41 | sum += root->data; 42 | return; 43 | } 44 | findSum(root->left,k-1,sum); 45 | findSum(root->right,k-1,sum); 46 | 47 | } 48 | 49 | 50 | 51 | int main(){ 52 | node* root = buildTree(); 53 | int k; 54 | cin>>k; 55 | int sum=0; 56 | findSum(root,k,sum); 57 | cout< 2 | using namespace std; 3 | 4 | void swap(int *a,int *b) 5 | { 6 | int tmp=*a; 7 | *a=*b; 8 | *b=tmp; 9 | 10 | } 11 | int Selection_Sort(int arr[],int n) 12 | { 13 | int i,j,min=arr[0]; 14 | for(i=0;i>SIZE; 41 | int arr[SIZE]; 42 | int n=sizeof(arr)/sizeof(arr[0]); 43 | cout<<"Enter elements for an array"<>arr[i]; 47 | } 48 | cout<<"Unsorted Array elements are:"<=0: 19 | idx = arr[i]//exp 20 | out_idx = count[idx%10]-1 21 | sorted[out_idx] = arr[i] 22 | count[idx%10] -= 1 23 | i -= 1 24 | 25 | # copy to main arr 26 | for i in range(len(arr)): 27 | arr[i] = sorted[i] 28 | print(f"Watch the sort exp : {exp} => {arr}") 29 | 30 | def radix_sort(arr): 31 | max_arr = max(arr) 32 | exp = 1 # it is 10^i where i is 0 right now. 33 | while max_arr//exp > 0: 34 | custom_count_sort(arr,exp) 35 | exp *= 10 36 | return arr 37 | arr = [170, 45, 75, 90, 802, 24, 2, 66] 38 | print(radix_sort(arr)) 39 | -------------------------------------------------------------------------------- /C/traverse-singly-linked-list.c: -------------------------------------------------------------------------------- 1 | # include 2 | # include 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node *link; 8 | }; 9 | struct node *insert_node_end(int data, struct node *head) 10 | { 11 | struct node *temp, *p=head; 12 | temp=(struct node*)malloc(sizeof(struct node)); 13 | temp->data=data; 14 | temp->link=NULL; 15 | if(head==NULL) 16 | { 17 | head=temp; 18 | } 19 | else 20 | { 21 | while(p->link!=NULL) 22 | { 23 | p=p->link; 24 | } 25 | p->link=temp; 26 | } 27 | return head; 28 | } 29 | int main() { 30 | int n, i; 31 | struct node *head=NULL; 32 | printf("Enter the number of nodes you want to enter\n"); 33 | scanf("%d",&n); 34 | for(i=0;idata); 45 | p1=p1->link; 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /C/quick-sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void quicksort(int number[25],int first,int last){ 3 | int i, j, pivot, temp; 4 | 5 | if(firstnumber[pivot]) 14 | j--; 15 | if(i 2 | using namespace std; 3 | 4 | int board[11][11]; 5 | 6 | bool isPossible(int n,int row,int col){ 7 | for(int i=row-1;i>=0;i--){ 8 | if(board[i][col]==1)return false; 9 | } 10 | for(int i=col-1,j=row-1;i>=0&&j>=0;i--,j--){ 11 | if(board[j][i]==1)return false; 12 | } 13 | for(int i=col+1,j=row-1;i=0;i++,j--){ 14 | if(board[j][i]==1)return false; 15 | } 16 | return true; 17 | 18 | } 19 | 20 | 21 | void nQueensHelper(int n, int row){ 22 | if(row==n){ 23 | for(int i=0;i>n; 49 | nQueens(n); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /HTML/digital-clock.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Digital Clock 8 | 21 | 22 | 23 |
24 | 39 | 40 | -------------------------------------------------------------------------------- /C++/tree-bfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printLevels(vector graph[], int V, int x) 5 | { 6 | int level[V]; 7 | bool marked[V]; 8 | 9 | queue que; 10 | 11 | que.push(x); 12 | 13 | level[x] = 0; 14 | 15 | marked[x] = true; 16 | 17 | while (!que.empty()) { 18 | 19 | x = que.front(); 20 | 21 | que.pop(); 22 | 23 | 24 | for (int i = 0; i < graph[x].size(); i++) { 25 | int b = graph[x][i]; 26 | if (!marked[b]) { 27 | 28 | que.push(b); 29 | 30 | level[b] = level[x] + 1; 31 | 32 | marked[b] = true; 33 | } 34 | } 35 | } 36 | 37 | cout << "Nodes" 38 | << " " 39 | << "Level" << endl; 40 | for (int i = 0; i < V; i++) 41 | cout << " " << i << " --> " << level[i] << endl; 42 | } 43 | 44 | 45 | int main() 46 | { 47 | 48 | int V = 8; 49 | vector graph[V]; 50 | 51 | graph[0].push_back(1); 52 | graph[0].push_back(2); 53 | graph[1].push_back(3); 54 | graph[1].push_back(4); 55 | graph[1].push_back(5); 56 | graph[2].push_back(5); 57 | graph[2].push_back(6); 58 | graph[6].push_back(7); 59 | 60 | printLevels(graph, V, 0); 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Python/merge-sort.py: -------------------------------------------------------------------------------- 1 | def merge(arr, l, m, r): 2 | n1 = m - l + 1 3 | n2 = r - m 4 | 5 | L = [0] * (n1) 6 | R = [0] * (n2) 7 | 8 | for i in range(0, n1): 9 | L[i] = arr[l + i] 10 | 11 | for j in range(0, n2): 12 | R[j] = arr[m + 1 + j] 13 | 14 | i = 0 15 | j = 0 16 | k = l 17 | 18 | while i < n1 and j < n2: 19 | if L[i] <= R[j]: 20 | arr[k] = L[i] 21 | i += 1 22 | else: 23 | arr[k] = R[j] 24 | j += 1 25 | k += 1 26 | 27 | while i < n1: 28 | arr[k] = L[i] 29 | i += 1 30 | k += 1 31 | 32 | 33 | while j < n2: 34 | arr[k] = R[j] 35 | j += 1 36 | k += 1 37 | 38 | 39 | def mergeSort(arr, l, r): 40 | if l < r: 41 | 42 | m = l+(r-l)//2 43 | 44 | mergeSort(arr, l, m) 45 | mergeSort(arr, m+1, r) 46 | merge(arr, l, m, r) 47 | 48 | arr = [12, 11, 13, 5, 6, 7] 49 | n = len(arr) 50 | print("Given array is") 51 | for i in range(n): 52 | print("%d" % arr[i]), 53 | 54 | mergeSort(arr, 0, n-1) 55 | print("\n\nSorted array is") 56 | for i in range(n): 57 | print("%d" % arr[i]), 58 | -------------------------------------------------------------------------------- /C++/counting-sort.cpp: -------------------------------------------------------------------------------- 1 | // Done by Sanjoy Saha 2 | // Github user link - https://github.com/SanjoySaha24 3 | // Counting Sort - Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. 4 | 5 | #include 6 | using namespace std; 7 | 8 | void countSort(int arr[], int n, int k) 9 | { 10 | int count[k]; 11 | for(int i=0;i=0;i--){ 21 | output[count[arr[i]]-1]=arr[i]; 22 | count[arr[i]]--; 23 | } 24 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | void floyds(int b[][7]) 5 | { 6 | int i, j, k; 7 | for (k = 0; k < 7; k++) 8 | { 9 | for (i = 0; i < 7; i++) 10 | { 11 | for (j = 0; j < 7; j++) 12 | { 13 | if ((b[i][k] * b[k][j] != 0) && (i != j)) 14 | { 15 | if ((b[i][k] + b[k][j] < b[i][j]) || (b[i][j] == 0)) 16 | { 17 | b[i][j] = b[i][k] + b[k][j]; 18 | } 19 | } 20 | } 21 | } 22 | } 23 | for (i = 0; i < 7; i++) 24 | { 25 | cout<<"\nMinimum Cost With Respect to Node:"<>b[i][j]; 43 | } 44 | } 45 | floyds(b); 46 | getch(); 47 | } 48 | -------------------------------------------------------------------------------- /C++/binary-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int arr[], int left, int right, int target) 5 | { 6 | if (right >= left) { 7 | int mid = left + (right - left) / 2; 8 | 9 | //If target is equal to middle element 10 | if (arr[mid] == target) 11 | return mid; 12 | 13 | // If element is smaller than mid, then it can only be present in left subarray 14 | if (arr[mid] > target) 15 | return binarySearch(arr, left, mid - 1, target); 16 | 17 | // Else the element can only be present 18 | // in right subarray 19 | return binarySearch(arr, mid + 1, right, target); 20 | } 21 | 22 | //If element is not present in array 23 | return -1; 24 | } 25 | 26 | int main(void) 27 | { 28 | int n; //size of array 29 | cin>>n; 30 | 31 | int arr[n]; 32 | for(int i=0;i>arr[i]; 35 | } 36 | 37 | int target; //that element which we have to find in the array 38 | cin>>target; 39 | 40 | int result = binarySearch(arr, 0, n - 1, target); 41 | (result == -1) ? cout << "Element is not present in array" : cout << "Element is present at index " << result; 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /C/count-sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 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 | printf("\n"); 12 | } 13 | int maximum(int A[], int n) 14 | { 15 | int max = INT_MIN; 16 | for(int i = 0; i < n; i++) 17 | { 18 | if(max < A[i]) 19 | { 20 | max = A[i]; 21 | } 22 | } 23 | return max; 24 | } 25 | 26 | void CountSort(int * A, int n) 27 | { 28 | int i, j; 29 | int max = maximum(A,n); 30 | int* count = (int *) malloc((max+1)*sizeof(int)); 31 | 32 | for(i = 0; i < max+1; i++) 33 | { 34 | count[i] = 0; 35 | } 36 | 37 | for(i = 0; i < n; i++) 38 | { 39 | count[A[i]] = count[A[i]]+1; 40 | } 41 | i = 0; 42 | j = 0; 43 | 44 | while(i <= max) 45 | { 46 | if(count[i]>0) 47 | { 48 | A[j] = i; 49 | count[i] = count[i] - 1; 50 | j++; 51 | } 52 | else 53 | { 54 | i++; 55 | } 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int A[] = {3, 5, 6, 1, 9, 13, 8}; 62 | int n = 7; 63 | CountSort(A, n); 64 | printArray(A, n); 65 | } 66 | -------------------------------------------------------------------------------- /Swift/quick-sort.swift: -------------------------------------------------------------------------------- 1 | func partition(_ list: inout [T], _ start: Int, _ end: Int) -> Int { 2 | var start = start 3 | var end = end 4 | let length = list.count 5 | let pivotIndex = start 6 | let pivot = list[pivotIndex] 7 | 8 | while start < end { 9 | while start < length && list[start] <= pivot { 10 | start += 1 11 | } 12 | while list[end] > pivot { 13 | end -= 1 14 | } 15 | if start < end { 16 | let tmp = list[start] 17 | list[start] = list[end] 18 | list[end] = tmp 19 | } 20 | } 21 | let tmp = list[end] 22 | list[end] = list[pivotIndex] 23 | list[pivotIndex] = tmp 24 | return end 25 | } 26 | 27 | 28 | func quickSort(_ list: inout [T], _ start: Int=0, _ end: Int? = nil) { 29 | let end = end ?? list.count - 1 30 | if start < end { 31 | let p = partition(&list, start, end) 32 | quickSort(&list, start, p-1) 33 | quickSort(&list, p+1, end) 34 | } 35 | } 36 | 37 | func quickSort(_ list: [T]) -> [T] { 38 | var temp = list 39 | quickSort(&temp) 40 | return temp 41 | } 42 | 43 | var list = ["a", "d", "b", "c"] 44 | var list2 = [4,2,1,3] 45 | quickSort(&list) 46 | print(list) 47 | print(quickSort(list2)) 48 | -------------------------------------------------------------------------------- /C++/radix-sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ implementation of Radix Sort 3 | #include 4 | using namespace std; 5 | 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | void countSort(int arr[], int n, int exp) 16 | { 17 | int output[n]; // output array 18 | int i, count[10] = { 0 }; 19 | 20 | for (i = 0; i < n; i++) 21 | count[(arr[i] / exp) % 10]++; 22 | 23 | for (i = 1; i < 10; i++) 24 | count[i] += count[i - 1]; 25 | 26 | for (i = n - 1; i >= 0; i--) { 27 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 28 | count[(arr[i] / exp) % 10]--; 29 | } 30 | 31 | for (i = 0; i < n; i++) 32 | arr[i] = output[i]; 33 | } 34 | 35 | void radixsort(int arr[], int n) 36 | { 37 | int m = getMax(arr, n); 38 | 39 | for (int exp = 1; m / exp > 0; exp *= 10) 40 | countSort(arr, n, exp); 41 | } 42 | 43 | void print(int arr[], int n) 44 | { 45 | for (int i = 0; i < n; i++) 46 | cout << arr[i] << " "; 47 | } 48 | int main() 49 | { 50 | int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; 51 | int n = sizeof(arr) / sizeof(arr[0]); 52 | 53 | // Function Call 54 | radixsort(arr, n); 55 | print(arr, n); 56 | return 0; 57 | } -------------------------------------------------------------------------------- /C/cocktail-sort.c: -------------------------------------------------------------------------------- 1 | // Alogrithm for Cocktail Sort to sort element in ascending order 2 | 3 | #include 4 | 5 | int main(void) 6 | { 7 | int i, j, start=0, n, end, flag; 8 | printf ("Enter value of n: "); 9 | scanf ("%d", &n); 10 | int a[n]; 11 | printf ("Please enter %d values\n",n); 12 | for(i=0; ia[i+1]) 23 | { 24 | int temp =a[i]; 25 | a[i] = a[i+1]; 26 | a[i+1] = temp; 27 | flag=1; 28 | } 29 | } 30 | if(flag==0) 31 | { 32 | break; 33 | } 34 | flag=0; 35 | end = end-1; 36 | for(i=end; i>start-1; i--) 37 | { 38 | if(a[i] 2 | using namespace std; 3 | 4 | 5 | // Function to efficiently find out three elements whose sum is equal to a given sum 6 | // Time complexity : O(n2) 7 | 8 | vector< vector > triplets(vector arr, int Sum) 9 | { 10 | vector < vector > res; 11 | 12 | int n = arr.size(); 13 | 14 | for (int i = 0; i <= n-3; ++i) 15 | { 16 | int j = i+1; 17 | int k = n-1; 18 | 19 | while(j < k) 20 | { 21 | int currsum = arr[i] + arr[j] + arr[k]; 22 | if(currsum == Sum){ 23 | res.push_back({arr[i] , arr[j] , arr[k]}); 24 | j++; 25 | k--; 26 | } 27 | else if(currsum > Sum) 28 | k--; 29 | else 30 | j++; 31 | } 32 | } 33 | return res; 34 | } 35 | 36 | int main() 37 | { 38 | // Example 39 | vector v = {1,2,3,4,5,6,7,8,9,15}; 40 | int Sum = 32; 41 | 42 | auto p = triplets(v,Sum); 43 | 44 | if(p.size()==0) 45 | cout << "No pair found" ; 46 | else 47 | { 48 | for (auto triplet : p) 49 | { 50 | // Outputting all valid triplet sets 51 | for(auto ans : triplet) 52 | cout << ans << " "; 53 | cout << endl; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /C++/tree-dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node* left, *right; 8 | Node(int data) 9 | { 10 | this->data = data; 11 | left = right = NULL; 12 | } 13 | }; 14 | 15 | void printPostorder(struct Node* node) 16 | { 17 | if (node == NULL) 18 | return; 19 | 20 | printPostorder(node->left); 21 | 22 | printPostorder(node->right); 23 | 24 | cout << node->data << " "; 25 | } 26 | 27 | void printInorder(struct Node* node) 28 | { 29 | if (node == NULL) 30 | return; 31 | 32 | printInorder(node->left); 33 | 34 | cout << node->data << " "; 35 | 36 | printInorder(node->right); 37 | } 38 | 39 | void printPreorder(struct Node* node) 40 | { 41 | if (node == NULL) 42 | return; 43 | 44 | cout << node->data << " "; 45 | 46 | printPreorder(node->left); 47 | 48 | printPreorder(node->right); 49 | } 50 | 51 | int main() 52 | { 53 | struct Node *root = new Node(1); 54 | root->left = new Node(2); 55 | root->right = new Node(3); 56 | root->left->left = new Node(4); 57 | root->left->right = new Node(5); 58 | 59 | cout << "\nPreorder traversal of binary tree is \n"; 60 | printPreorder(root); 61 | 62 | cout << "\nInorder traversal of binary tree is \n"; 63 | printInorder(root); 64 | 65 | cout << "\nPostorder traversal of binary tree is \n"; 66 | printPostorder(root); 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 📝 2 | 3 | ## Adding Algorithms & Data Structures 4 | 5 | Create a file with the algorithm and place it in the folder corresponding to the programming language used. Feel free to add a new folder if it does not exist already. 6 | 7 | Update the README.md file with the link of your file under the appropriate category. 8 | 9 | Please be sure to follow the guidelines below 👇 10 | 11 | ### 📁 File names 12 | 13 | Name the file with the name of the algorithm. Use all **lowercase** characters with the words separated by a hyphen (-). 14 | 15 | For example, if the name of your algorithm is _My Awesome Algorithm_, the file should be named as `my-awesome-algorithm.` where `` is the extension of the file. 16 | 17 | ### 📄 Updating README.md 18 | 19 | Add the relative link to your file to the list under the corresponding language heading. 20 | **The list is arranged in alphabetical order.** 21 | 22 | For example, for adding `my-awesome-algorithm.`, the list item will be 23 | 24 | ``` 25 | - [My Awesome Algorithm](language-folder/my-awesome-algorithm.) 26 | ``` 27 | 28 | The first _letter_ of each word in the link title should be in uppercase. 29 | 30 | If the language heading does not exist already then add a new heading in such a way that the headings remain in alphabetical order. 31 | 32 | Create a Pull Request after commiting the changes. 33 | 34 | Thank you in advance for your contribution 😊 35 | -------------------------------------------------------------------------------- /Java/cocktail-sort.java: -------------------------------------------------------------------------------- 1 | // Alogrithm for Cocktail Sort to sort element in ascending order 2 | 3 | import java.util.Arrays; 4 | 5 | public class CocktailSort { 6 | public static void sort(int[] array) { 7 | boolean swapped = true; 8 | int start = 0; 9 | int end = array.length; 10 | 11 | while (swapped) { 12 | swapped = false; 13 | for (int i = start; i < end - 1; i++) { 14 | if (array[i] > array[i + 1]) { 15 | int temp = array[i]; 16 | array[i] = array[i + 1]; 17 | array[i + 1] = temp; 18 | swapped = true; 19 | } 20 | } 21 | 22 | if (!swapped) { 23 | break; 24 | } 25 | 26 | swapped = false; 27 | end--; 28 | 29 | for (int i = end - 1; i >= start; i--) { 30 | if (array[i] > array[i + 1]) { 31 | int temp = array[i]; 32 | array[i] = array[i + 1]; 33 | array[i + 1] = temp; 34 | swapped = true; 35 | } 36 | } 37 | 38 | start++; 39 | } 40 | } 41 | } 42 | 43 | class CocktailSortEvaluator { 44 | public static void main(String[] args) { 45 | int[] array = {9,3,6,1,4}; 46 | CocktailSort.sort(array); 47 | System.out.println(Arrays.toString(array)); 48 | } 49 | } -------------------------------------------------------------------------------- /C++/string-match.cpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | 3 | String Matching Algorithm helps to find if two string matches or not || if a pattern 4 | can be found in a text or not. 5 | Brute-Force approach to match string is dicussed below. 6 | 7 | *******************************************************************************/ 8 | 9 | #include 10 | 11 | using namespace std; 12 | 13 | int stringMatch(string text, string pattern){ 14 | int text_size = text.size(); 15 | int pattern_size = pattern.size(); 16 | 17 | for(int i = 0; i<=(text_size - pattern_size); i++){ 18 | int j = 0; 19 | while(j(_ left: [T], _ right: [T]) -> [T] { 2 | var leftIndex = 0 3 | var rightIndex = 0 4 | 5 | var orderedArray: [T] = [] 6 | 7 | while leftIndex < left.count && rightIndex < right.count { 8 | let leftElement = left[leftIndex] 9 | let rightElement = right[rightIndex] 10 | 11 | if leftElement < rightElement { 12 | orderedArray.append(leftElement) 13 | leftIndex += 1 14 | } else if leftElement > rightElement { 15 | orderedArray.append(rightElement) 16 | rightIndex += 1 17 | } else { 18 | orderedArray.append(leftElement) 19 | leftIndex += 1 20 | orderedArray.append(rightElement) 21 | rightIndex += 1 22 | } 23 | } 24 | 25 | while leftIndex < left.count { 26 | orderedArray.append(left[leftIndex]) 27 | leftIndex += 1 28 | } 29 | 30 | while rightIndex < right.count { 31 | orderedArray.append(right[rightIndex]) 32 | rightIndex += 1 33 | } 34 | 35 | return orderedArray 36 | } 37 | 38 | func mergeSort(_ list: [T]) -> [T] { 39 | guard list.count > 1 else { return list } 40 | 41 | let middleIndex = list.count / 2 42 | 43 | let leftList = mergeSort(Array(list[0.. Array to be sorted, 29 | # low --> Starting index, 30 | # high --> Ending index 31 | 32 | # Function to do Quick sort 33 | 34 | 35 | def quickSort(arr, low, high): 36 | if len(arr) == 1: 37 | return arr 38 | if low < high: 39 | 40 | # pi is partitioning index, arr[p] is now 41 | # at right place 42 | pi = partition(arr, low, high) 43 | 44 | # Separately sort elements before 45 | # partition and after partition 46 | quickSort(arr, low, pi-1) 47 | quickSort(arr, pi+1, high) 48 | 49 | 50 | # Driver code to test above 51 | arr = [10, 7, 8, 9, 1, 5] 52 | n = len(arr) 53 | quickSort(arr, 0, n-1) 54 | print("Sorted array is:") 55 | for i in range(n): 56 | print("%d" % arr[i]), 57 | -------------------------------------------------------------------------------- /Python/segment-tree.py: -------------------------------------------------------------------------------- 1 | class SegmentTree: 2 | def __init__(self, data, default=0, func=lambda a, b: a + b): 3 | self._default = default 4 | self._func = func 5 | self._len = len(data) 6 | self._size = _size = 1 << (self._len - 1).bit_length() 7 | 8 | self.data = [default] * (2 * _size) 9 | self.data[_size:_size + self._len] = data 10 | for i in reversed(range(_size)): 11 | self.data[i] = func(self.data[i + i], self.data[i + i + 1]) 12 | 13 | def __delitem__(self, idx): 14 | self[idx] = self._default 15 | 16 | def __getitem__(self, idx): 17 | return self.data[idx + self._size] 18 | 19 | def __setitem__(self, idx, value): 20 | idx += self._size 21 | self.data[idx] = value 22 | idx >>= 1 23 | while idx: 24 | self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) 25 | idx >>= 1 26 | 27 | def __len__(self): 28 | return self._len 29 | 30 | def query(self, start, stop): 31 | if start == stop: 32 | return self.__getitem__(start) 33 | stop += 1 34 | start += self._size 35 | stop += self._size 36 | 37 | res = self._default 38 | while start < stop: 39 | if start & 1: 40 | res = self._func(res, self.data[start]) 41 | start += 1 42 | if stop & 1: 43 | stop -= 1 44 | res = self._func(res, self.data[stop]) 45 | start >>= 1 46 | stop >>= 1 47 | return res 48 | 49 | def __repr__(self): 50 | return "SegmentTree({0})".format(self.data) -------------------------------------------------------------------------------- /C++/dijkstras-algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define V 9 4 | 5 | int distance(int dist[], bool set[]) 6 | { 7 | int min = INT_MAX, index; 8 | for (int v = 0; v < V; v++) 9 | if (set[v] == false && dist[v] <= min) 10 | min = dist[v], index = v; 11 | 12 | return index; 13 | } 14 | 15 | int print(int dist[]) 16 | { 17 | printf("Vertex Distance from Source\n"); 18 | for (int i = 0; i < V; i++) 19 | printf("%d \t\t %d\n", i, dist[i]); 20 | return 0; 21 | } 22 | 23 | void dijkstra(int graph[V][V], int src) 24 | { 25 | int dist[V]; 26 | bool set[V]; 27 | for (int i = 0; i < V; i++) 28 | dist[i] = INT_MAX, set[i] = false; 29 | dist[src] = 0; 30 | for (int c = 0; c < V-1; c++) 31 | { 32 | int m = distance(dist, set); 33 | set[m] = true; 34 | for (int n = 0; n < V;n++) 35 | 36 | if (!set[n] && graph[m][n] && dist[m] != INT_MAX && dist[m]+graph[m][n] < dist[n]) 37 | dist[n] = dist[m] + graph[m][n]; 38 | } 39 | 40 | print(dist); 41 | } 42 | 43 | int main() 44 | { 45 | int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, 46 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 47 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 48 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 49 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 50 | {0, 0, 4, 0, 10, 0, 2, 0, 0}, 51 | {0, 0, 0, 14, 0, 2, 0, 1, 6}, 52 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 53 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 54 | }; 55 | 56 | dijkstra(graph, 0); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Java/merge-sort.java: -------------------------------------------------------------------------------- 1 | // Java program to perform Merge Sort algorithm on a array 2 | public class MergeSort 3 | { 4 | static void mergeSort(int arr[],int l,int r) 5 | { 6 | if(r>l) 7 | { 8 | int mid = l+(r-l)/2; 9 | mergeSort(arr,l,mid); 10 | mergeSort(arr,mid+1,r); 11 | merge(arr,l,mid,r); 12 | } 13 | } 14 | 15 | static void merge(int arr[],int l,int m,int r) 16 | { 17 | int l1 = m+1-l; 18 | int l2 = r-m; 19 | int[] arr1 = new int[l1]; 20 | int[] arr2 = new int[l2]; 21 | int i = 0,j = 0; 22 | for(int f=0;f0){ 5 | hamiltonCycle=Math.min(hamiltonCycle,cost+distance[currPos][0]); 6 | return hamiltonCycle; 7 | 8 | } 9 | for(int i=0;i0){ 11 | visitCity[i]=true; 12 | hamiltonCycle=FHamiltonCycle(distance, visitCity, i, cities, count+1, cost+distance[currPos][i], hamiltonCycle); 13 | visitCity[i]=false; 14 | } 15 | } 16 | return hamiltonCycle; 17 | } 18 | public static void main(String[] args){ 19 | int cities; 20 | Scanner sc=new Scanner(System.in); 21 | System.out.println("Enter total number of cities "); 22 | cities = sc.nextInt(); 23 | int distance[][] = new int[cities][cities]; 24 | 25 | for (int i = 0; i < cities; i++) { 26 | for (int j = 0; j < cities; j++) { 27 | System.out.println("Distance from " + (i + 1) + " to " + (j + 1) + ":"); 28 | distance[i][j] = sc.nextInt(); 29 | } 30 | } 31 | 32 | boolean[] visitCity = new boolean[cities]; 33 | 34 | visitCity[0] = true; 35 | 36 | int hamiltonianCycle = 999; 37 | 38 | hamiltonianCycle = FHamiltonCycle(distance, visitCity, 0, cities, 1, 0, hamiltonianCycle); 39 | 40 | System.out.println("Cost of the Path taken by TSP: " + hamiltonianCycle); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java/heap-sort.java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | 3 | public HeapSort() { 4 | 5 | } 6 | 7 | private void heap(int[] array, int length, int i) { 8 | int left = 2*i+1; 9 | int right = 2*i+2; 10 | int large = i; 11 | 12 | if (left < length && array[left] > array[large]) { 13 | large = left; 14 | } 15 | 16 | if (right < length && array[right] > array[large]) { 17 | large = right; 18 | } 19 | 20 | if (large != i) { 21 | int temp = array[i]; 22 | array[i] = array[large]; 23 | array[large] = temp; 24 | heap(array, length, large); 25 | } 26 | } 27 | 28 | private void sort(int[] array) { 29 | if (array.length == 0) return; 30 | 31 | int length = array.length; 32 | 33 | for (int i = length / 2-1; i >= 0; i--) 34 | heap(array, length, i); 35 | 36 | for (int i = length-1; i >= 0; i--) { 37 | int temp = array[0]; 38 | array[0] = array[i]; 39 | array[i] = temp; 40 | 41 | heap(array, i, 0); 42 | } 43 | } 44 | 45 | private int[] createIntArray(int size){ 46 | int[] data = new int[size]; 47 | for(int i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void RabinKarpAlgo(string strText, string PatternText) 7 | { 8 | if (strText.length() && PatternText.length()) 9 | { 10 | int lt = strText.length(); 11 | int mt = PatternText.length(); 12 | int i, j; 13 | int s = 0, p = 0; 14 | const int pm = 256; 15 | const int q = 101; 16 | int h = 1; 17 | bool flag = false; 18 | 19 | for (i = 0; i < mt - 1; i++) 20 | h = (h * pm) % q; 21 | 22 | for (i = 0; i < mt; i++) 23 | { 24 | s = (pm * s + strText[i]) % q; 25 | p = (pm * p + PatternText[i]) % q; 26 | } 27 | 28 | for (i = 0; i <= lt - mt; i++) 29 | { 30 | if (s == p) 31 | { 32 | for (j = 0; j < mt; j++) 33 | if (strText[i + j] != PatternText[j]) 34 | break; 35 | if (j == mt) 36 | { 37 | cout << "Pattern found at pos: " << i + 1 << endl; 38 | flag = true; 39 | } 40 | } 41 | 42 | s = (pm * (s - h * strText[i]) + strText[i + mt]) % q; 43 | if (s < 0) 44 | s = s + q; 45 | } 46 | if (!flag) 47 | cout << "Pattern not found.." << endl; 48 | return; 49 | } 50 | if ((strText.empty()) && (PatternText.empty())) 51 | { 52 | cout << "Text and pattern cannot be empty.." << endl; 53 | } 54 | else if (strText.empty()) 55 | { 56 | cout << "Text cannot be empty.." << endl; 57 | } 58 | else 59 | { 60 | cout << "Pattern cannot be empty.." << endl; 61 | } 62 | return; 63 | } 64 | 65 | int main() 66 | { 67 | freopen("input.txt", "r", stdin); 68 | 69 | string strText, PatternText; 70 | getline(cin, strText); 71 | getline(cin, PatternText); 72 | RabinKarpAlgo(strText, PatternText); 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /C/generic-tree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef int element; 7 | typedef struct node 8 | { 9 | element data; 10 | struct node *firstchild; 11 | struct node *nextsibling; 12 | }*GenericTree; 13 | 14 | GenericTree create() 15 | { 16 | return NULL; 17 | } 18 | 19 | int isEmpty(GenericTree gt) 20 | { 21 | return (gt==NULL); 22 | } 23 | 24 | GenericTree build(element e, GenericTree firstchild, GenericTree nextsibling) 25 | { 26 | GenericTree tree; 27 | tree=(GenericTree)malloc(sizeof(struct node)); 28 | if(!tree) 29 | return NULL; 30 | tree->data=e; 31 | tree->firstchild=firstchild; 32 | tree->nextsibling=nextsibling; 33 | return tree; 34 | } 35 | 36 | int nodeCount(GenericTree tree) 37 | { 38 | if(!tree) 39 | return 0; 40 | return 1+nodeCount(tree->firstchild)+nodeCount(tree->nextsibling); 41 | 42 | } 43 | 44 | int nodeSum(GenericTree tree) 45 | { 46 | if(!tree) 47 | return 0; 48 | return tree->data+nodeSum(tree->firstchild)+nodeSum(tree->nextsibling); 49 | } 50 | 51 | int nbS(GenericTree tree) 52 | { 53 | int count=0; 54 | while(tree) 55 | { 56 | tree=tree->nextsibling; 57 | count++; 58 | } 59 | return count; 60 | } 61 | 62 | int nbC(GenericTree tree) 63 | { 64 | int count=0; 65 | if(tree) 66 | tree=tree->firstchild; 67 | while(tree) 68 | { 69 | count++; 70 | tree=tree->nextsibling; 71 | } 72 | return count; 73 | } 74 | 75 | int main() 76 | { 77 | GenericTree sample=build(1,build(2,NULL,build(3,build(4,NULL,NULL), 78 | build(5,build(6,NULL,build(7,build(8,NULL, 79 | build(9,NULL,NULL)),NULL)),build(10,build(11,NULL, 80 | build(12,NULL,build(13,NULL,NULL))),NULL)))),NULL); 81 | printf("Number of nodes: %d\n",nodeCount(sample)); 82 | printf("Sum of nodes: %d\n",nodeSum(sample)); 83 | printf("Neighbour Siblings: %d\n",nbS(sample)); 84 | printf("Neighbour Children: %d\n",nbC(sample)); 85 | return 0; 86 | } -------------------------------------------------------------------------------- /Java/hamiltonianCycle.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | public class hamiltonianCycle { 5 | int count; 6 | int path = 1; 7 | 8 | void swap(int[] arr, int x, int y) { 9 | int temp = arr[x]; 10 | arr[x] = arr[y]; 11 | arr[y] = temp; 12 | } 13 | 14 | void permute(int[] arr, int[][] G) { 15 | permute(arr, 0, arr.length - 1, G); 16 | } 17 | 18 | void permute(int[] arr, int i, int n, int[][] cost) { 19 | int j; 20 | 21 | if (i == n) { 22 | HamilCycle(arr, cost); 23 | } else { 24 | for (j = i; j <= n; j++) { 25 | swap(arr, i, j); 26 | permute(arr, i + 1, n, cost); 27 | swap(arr, i, j); 28 | } 29 | } 30 | } 31 | 32 | void HamilCycle(int a[], int[][] G) { 33 | count = 0; 34 | 35 | for (int i = 0; i < a.length - 1; i++) { 36 | if (G[a[i]][a[i + 1]] != 0) 37 | count++; 38 | } 39 | 40 | if (count == a.length - 1 && G[a[a.length - 1]][a[0]] == 1) { 41 | System.out.print("Cycle No " + path + "----> "); 42 | 43 | for (int i = 0; i < a.length; i++) 44 | System.out.print(a[i] + " "); 45 | System.out.print(a[0]); 46 | System.out.println(); 47 | path++; 48 | } 49 | } 50 | 51 | public static void main(String[] args) { 52 | Scanner s = new Scanner(System.in); 53 | 54 | System.out.println("Enter the number of nodes in graph: "); 55 | 56 | int n = s.nextInt(); 57 | 58 | int graph[][] = new int[n][n]; 59 | 60 | System.out.println("Enter the adjacency matrix"); 61 | 62 | for (int i = 0; i < n; i++) { 63 | for (int j = 0; j < n; j++) { 64 | graph[i][j] = s.nextInt(); 65 | } 66 | 67 | } 68 | int arr[] = new int[n]; 69 | 70 | for (int i = 0; i < n; i++) 71 | arr[i] = i; 72 | 73 | System.out.println("All possible Hamiltonian Cycles in graph"); 74 | new hamiltonianCycle().permute(arr, graph); 75 | 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /C++/polygon-triangulation.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #define MAX 1000000.0 5 | using namespace std; 6 | 7 | 8 | struct Point 9 | { 10 | int x, y; 11 | }; 12 | 13 | 14 | double min(double x, double y) 15 | { 16 | return (x <= y)? x : y; 17 | } 18 | 19 | double dist(Point p1, Point p2) 20 | { 21 | return sqrt((p1.x - p2.x)*(p1.x - p2.x) + 22 | (p1.y - p2.y)*(p1.y - p2.y)); 23 | } 24 | 25 | // A utility function to find cost of a triangle. The cost is considered 26 | // as perimeter (sum of lengths of all edges) of the triangle 27 | double cost(Point points[], int i, int j, int k) 28 | { 29 | Point p1 = points[i], p2 = points[j], p3 = points[k]; 30 | return dist(p1, p2) + dist(p2, p3) + dist(p3, p1); 31 | } 32 | 33 | double mTCDP(Point points[], int n) 34 | { 35 | 36 | if (n < 3) 37 | return 0; 38 | 39 | double table[n][n]; 40 | 41 | for (int gap = 0; gap < n; gap++) 42 | { 43 | for (int i = 0, j = gap; j < n; i++, j++) 44 | { 45 | if (j < i+2) 46 | { 47 | table[i][j] = 0.0; 48 | //s[i][j]=0.0; 49 | } 50 | else 51 | { 52 | table[i][j] = MAX; 53 | //s[i][j]=MAX; 54 | for (int k = i+1; k < j; k++) 55 | { 56 | double val = table[i][k] + table[k][j] + cost(points,i,j,k); 57 | if (table[i][j] > val) 58 | { 59 | table[i][j] = val; 60 | //s[i][j]=k; 61 | } 62 | } 63 | } 64 | } 65 | } 66 | for(int i=0;i 4 | using namespace std; 5 | 6 | #define V 6 7 | 8 | bool bfs(int rgraph[V][V], int src, int t, int parent[]) 9 | { 10 | vectorvisited(V, false); 11 | queueq; 12 | q.push(src); 13 | visited[src] = true; 14 | parent[src] = -1; 15 | 16 | while(!q.empty()) { 17 | int u = q.front(); 18 | q.pop(); 19 | 20 | for(int v=0; v0) 23 | { 24 | if(v==t) 25 | { 26 | parent[v] = u; 27 | return true; 28 | } 29 | q.push(v); 30 | parent[v] = u; 31 | visited[v] = true; 32 | } 33 | } 34 | } 35 | 36 | return false; 37 | 38 | } 39 | 40 | int ford_fulk(int graph[V][V], int src, int t) 41 | { 42 | int u,v; 43 | int rgraph[V][V]; 44 | for(u=0; u 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Class to represent a graph 7 | class Graph 8 | { 9 | int V; // No. of vertices' 10 | 11 | // Pointer to an array containing adjacency listsList 12 | list *adj; 13 | 14 | // A function used by topologicalSort 15 | void topologicalSortUtil(int v, bool visited[], stack &Stack); 16 | public: 17 | Graph(int V); // Constructor 18 | 19 | // function to add an edge to graph 20 | void addEdge(int v, int w); 21 | 22 | // prints a Topological Sort of the complete graph 23 | void topologicalSort(); 24 | }; 25 | 26 | Graph::Graph(int V) 27 | { 28 | this->V = V; 29 | adj = new list[V]; 30 | } 31 | 32 | void Graph::addEdge(int v, int w) 33 | { 34 | adj[v].push_back(w); // Add w to v’s list. 35 | } 36 | 37 | // A recursive function used by topologicalSort 38 | void Graph::topologicalSortUtil(int v, bool visited[], 39 | stack &Stack) 40 | { 41 | // Mark the current node as visited. 42 | visited[v] = true; 43 | 44 | // Recur for all the vertices adjacent to this vertex 45 | list::iterator i; 46 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 47 | if (!visited[*i]) 48 | topologicalSortUtil(*i, visited, Stack); 49 | 50 | // Push current vertex to stack which stores result 51 | Stack.push(v); 52 | } 53 | 54 | // The function to do Topological Sort. It uses recursive 55 | // topologicalSortUtil() 56 | void Graph::topologicalSort() 57 | { 58 | stack Stack; 59 | 60 | // Mark all the vertices as not visited 61 | bool *visited = new bool[V]; 62 | for (int i = 0; i < V; i++) 63 | visited[i] = false; 64 | 65 | // Call the recursive helper function to store Topological 66 | // Sort starting from all vertices one by one 67 | for (int i = 0; i < V; i++) 68 | if (visited[i] == false) 69 | topologicalSortUtil(i, visited, Stack); 70 | 71 | // Print contents of stack 72 | while (Stack.empty() == false) 73 | { 74 | cout << Stack.top() << " "; 75 | Stack.pop(); 76 | } 77 | } 78 | 79 | // Driver program to test above functions 80 | int main() 81 | { 82 | // Create a graph given in the above diagram 83 | Graph g(6); 84 | g.addEdge(5, 2); 85 | g.addEdge(5, 0); 86 | g.addEdge(4, 0); 87 | g.addEdge(4, 1); 88 | g.addEdge(2, 3); 89 | g.addEdge(3, 1); 90 | 91 | cout << "Following is a Topological Sort of the given graph \n"; 92 | g.topologicalSort(); 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /Python/lazy-segment-tree.py: -------------------------------------------------------------------------------- 1 | from math import inf, log2 2 | 3 | class LazySegmentTree: 4 | def __init__(self, array, func=min): 5 | self.n = len(array) 6 | self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1 7 | self.func = func 8 | self.default = 0 if self.func != min else inf 9 | self.data = [self.default] * (2 * self.size) 10 | self.lazy = [0] * (2 * self.size) 11 | self.process(array) 12 | 13 | def process(self, array): 14 | self.data[self.size: self.size + self.n] = array 15 | for i in range(self.size - 1, -1, -1): 16 | self.data[i] = self.func(self.data[2 * i], self.data[2 * i + 1]) 17 | 18 | def push(self, index): 19 | """Push the information of the root to it's children!""" 20 | self.lazy[2 * index] += self.lazy[index] 21 | self.lazy[2 * index + 1] += self.lazy[index] 22 | self.data[2 * index] += self.lazy[index] 23 | self.data[2 * index + 1] += self.lazy[index] 24 | self.lazy[index] = 0 25 | 26 | def build(self, index): 27 | """Build data with the new changes!""" 28 | index >>= 1 29 | while index: 30 | self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1]) + self.lazy[index] 31 | index >>= 1 32 | 33 | def query(self, alpha, omega): 34 | """Returns the result of function over the range (inclusive)!""" 35 | res = self.default 36 | alpha += self.size 37 | omega += self.size + 1 38 | for i in range(len(bin(alpha)[2:]) - 1, 0, -1): 39 | self.push(alpha >> i) 40 | for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): 41 | self.push((omega - 1) >> i) 42 | while alpha < omega: 43 | if alpha & 1: 44 | res = self.func(res, self.data[alpha]) 45 | alpha += 1 46 | if omega & 1: 47 | omega -= 1 48 | res = self.func(res, self.data[omega]) 49 | alpha >>= 1 50 | omega >>= 1 51 | return res 52 | 53 | def update(self, alpha, omega, value): 54 | """Increases all elements in the range (inclusive) by given value!""" 55 | alpha += self.size 56 | omega += self.size + 1 57 | l, r = alpha, omega 58 | while alpha < omega: 59 | if alpha & 1: 60 | self.data[alpha] += value 61 | self.lazy[alpha] += value 62 | alpha += 1 63 | if omega & 1: 64 | omega -= 1 65 | self.data[omega] += value 66 | self.lazy[omega] += value 67 | alpha >>= 1 68 | omega >>= 1 69 | self.build(l) 70 | self.build(r - 1) -------------------------------------------------------------------------------- /C++/merge-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void merge(int array[], int const left, int const mid, int const right) 6 | { 7 | auto const subArrayOne = mid - left + 1; 8 | auto const subArrayTwo = right - mid; 9 | 10 | // Create temp arrays 11 | auto *leftArray = new int[subArrayOne], 12 | *rightArray = new int[subArrayTwo]; 13 | 14 | // Copy data to temp arrays leftArray[] and rightArray[] 15 | for (auto i = 0; i < subArrayOne; i++) 16 | leftArray[i] = array[left + i]; 17 | for (auto j = 0; j < subArrayTwo; j++) 18 | rightArray[j] = array[mid + 1 + j]; 19 | 20 | auto indexOfSubArrayOne = 0, // Initial index of first sub-array 21 | indexOfSubArrayTwo = 0; // Initial index of second sub-array 22 | int indexOfMergedArray = left; // Initial index of merged array 23 | 24 | // Merge the temp arrays back into array[left..right] 25 | while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { 26 | if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { 27 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 28 | indexOfSubArrayOne++; 29 | } 30 | else { 31 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 32 | indexOfSubArrayTwo++; 33 | } 34 | indexOfMergedArray++; 35 | } 36 | // Copy the remaining elements of 37 | // left[], if there are any 38 | while (indexOfSubArrayOne < subArrayOne) { 39 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 40 | indexOfSubArrayOne++; 41 | indexOfMergedArray++; 42 | } 43 | // Copy the remaining elements of 44 | // right[], if there are any 45 | while (indexOfSubArrayTwo < subArrayTwo) { 46 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 47 | indexOfSubArrayTwo++; 48 | indexOfMergedArray++; 49 | } 50 | } 51 | 52 | // begin is for left index and end is 53 | // right index of the sub-array 54 | // of arr to be sorted */ 55 | void mergeSort(int array[], int const begin, int const end) 56 | { 57 | if (begin >= end) 58 | return; // Returns recursively 59 | 60 | auto mid = begin + (end - begin) / 2; 61 | mergeSort(array, begin, mid); 62 | mergeSort(array, mid + 1, end); 63 | merge(array, begin, mid, end); 64 | } 65 | 66 | // Function to print an array 67 | void printArray(int A[], int size) 68 | { 69 | for (auto i = 0; i < size; i++) 70 | cout << A[i] << " "; 71 | } 72 | 73 | 74 | int main() 75 | { 76 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 77 | auto arr_size = sizeof(arr) / sizeof(arr[0]); 78 | 79 | cout << "Given array is \n"; 80 | printArray(arr, arr_size); 81 | 82 | mergeSort(arr, 0, arr_size - 1); 83 | 84 | cout << "\nSorted array is \n"; 85 | printArray(arr, arr_size); 86 | return 0; 87 | } -------------------------------------------------------------------------------- /C/merge-sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | int compare=0; 6 | 7 | int* generateUD(int size,int mean,int width) 8 | { 9 | int start,end; 10 | start=mean-width; 11 | end=mean+width; 12 | int* a=malloc(size*sizeof(int)); 13 | srand(time(0)); 14 | for(int i=0;iR nothing matches so we will calculate. 43 | // Z[i] using naive way. 44 | if(i > R){ 45 | 46 | L = R = i; 47 | 48 | // R-L = 0 in starting, so it will start 49 | // checking from 0'th index. For example, 50 | // for "ababab" and i = 1, the value of R 51 | // remains 0 and Z[i] becomes 0. For string 52 | // "aaaaaa" and i = 1, Z[i] and R become 5 53 | 54 | while(R < n && str.charAt(R - L) == str.charAt(R)) 55 | R++; 56 | 57 | Z[i] = R - L; 58 | R--; 59 | 60 | } 61 | else{ 62 | 63 | // k = i-L so k corresponds to number which 64 | // matches in [L,R] interval. 65 | int k = i - L; 66 | 67 | // if Z[k] is less than remaining interval 68 | // then Z[i] will be equal to Z[k]. 69 | // For example, str = "ababab", i = 3, R = 5 70 | // and L = 2 71 | if(Z[k] < R - i + 1) 72 | Z[i] = Z[k]; 73 | 74 | // For example str = "aaaaaa" and i = 2, R is 5, 75 | // L is 0 76 | else{ 77 | 78 | 79 | // else start from R and check manually 80 | L = i; 81 | while(R < n && str.charAt(R - L) == str.charAt(R)) 82 | R++; 83 | 84 | Z[i] = R - L; 85 | R--; 86 | } 87 | } 88 | } 89 | } 90 | 91 | public static void main(String[] args) 92 | { 93 | String text = "GEEKS FOR GEEKS"; 94 | String pattern = "GEEK"; 95 | 96 | search(text, pattern); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /C/hash-tables.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define SIZE 20 7 | 8 | struct DataItem { 9 | int data; 10 | int key; 11 | }; 12 | 13 | struct DataItem* hashArray[SIZE]; 14 | struct DataItem* dummyItem; 15 | struct DataItem* item; 16 | 17 | int hashCode(int key) { 18 | return key % SIZE; 19 | } 20 | 21 | struct DataItem *search(int key) { 22 | //get the hash 23 | int hashIndex = hashCode(key); 24 | 25 | //move in array until an empty 26 | while(hashArray[hashIndex] != NULL) { 27 | 28 | if(hashArray[hashIndex]->key == key) 29 | return hashArray[hashIndex]; 30 | 31 | //go to next cell 32 | ++hashIndex; 33 | 34 | //wrap around the table 35 | hashIndex %= SIZE; 36 | } 37 | 38 | return NULL; 39 | } 40 | 41 | void insert(int key,int data) { 42 | 43 | struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); 44 | item->data = data; 45 | item->key = key; 46 | 47 | //get the hash 48 | int hashIndex = hashCode(key); 49 | 50 | //move in array until an empty or deleted cell 51 | while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { 52 | //go to next cell 53 | ++hashIndex; 54 | 55 | //wrap around the table 56 | hashIndex %= SIZE; 57 | } 58 | 59 | hashArray[hashIndex] = item; 60 | } 61 | 62 | struct DataItem* delete(struct DataItem* item) { 63 | int key = item->key; 64 | 65 | //get the hash 66 | int hashIndex = hashCode(key); 67 | 68 | //move in array until an empty 69 | while(hashArray[hashIndex] != NULL) { 70 | 71 | if(hashArray[hashIndex]->key == key) { 72 | struct DataItem* temp = hashArray[hashIndex]; 73 | 74 | //assign a dummy item at deleted position 75 | hashArray[hashIndex] = dummyItem; 76 | return temp; 77 | } 78 | 79 | //go to next cell 80 | ++hashIndex; 81 | 82 | //wrap around the table 83 | hashIndex %= SIZE; 84 | } 85 | 86 | return NULL; 87 | } 88 | 89 | void display() { 90 | int i = 0; 91 | 92 | for(i = 0; ikey,hashArray[i]->data); 96 | else 97 | printf(" ~~ "); 98 | } 99 | 100 | printf("\n"); 101 | } 102 | 103 | int main() { 104 | dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); 105 | dummyItem->data = -1; 106 | dummyItem->key = -1; 107 | 108 | insert(1, 20); 109 | insert(2, 70); 110 | insert(42, 80); 111 | insert(4, 25); 112 | insert(12, 44); 113 | insert(14, 32); 114 | insert(17, 11); 115 | insert(13, 78); 116 | insert(37, 97); 117 | 118 | display(); 119 | item = search(37); 120 | 121 | if(item != NULL) { 122 | printf("Element found: %d\n", item->data); 123 | } else { 124 | printf("Element not found\n"); 125 | } 126 | 127 | delete(item); 128 | item = search(37); 129 | 130 | if(item != NULL) { 131 | printf("Element found: %d\n", item->data); 132 | } else { 133 | printf("Element not found\n"); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /HTML/site-music.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Aprendizado em HTML 6 | 7 | 8 | 9 |
10 | Ilustração do Felipe Gangorra 11 |

Feito por Felipe Gangorra👋

12 |
13 |
14 |
15 |

Playlist🎵

16 |
17 |
18 |
19 |

#1 Música✔

20 | Imagem da música 21 |
22 |

23 |

24 | A QUEDA DO CAPITÃO: 25 |

26 | 27 | Pelos sete mares naveguei
28 | E muitas coisas eu vi
29 | Por muitas meretrizes me apaixonei
30 | Mas ia embora após ela dormir
31 |
32 | Por todos os perigos que passei
33 | E os amigos que perdi
34 | Por todo o ouro que conquistei
35 | Pelo rum que bebi
36 |
37 | Ergam seus copos por quem vai partir
38 | Honrem os que não estão mais aqui
39 | Se afaste em respeito a tudo que eu vivi
40 | A morte está a me seguir
41 |
42 | Que o vento sopre forte pra onde você for
43 | Que a sorte esteja sempre ao seu favor
44 | Que nunca conheça todo esse horror
45 | Lute por amor!
46 |
47 | O Sol nasce e contrasta com a sentença
48 | E o carrasco da execução
49 | Vejo todo ódio de uma tormenta
50 | Explodindo em seu coração
51 |
52 | Não suo frio, o medo se esvai
53 | Quando não sinto os meus pés no chão
54 | Fecho os olhos e não vejo mais
55 | O monstro que criei com um canhão
56 |
57 | Ergam seus copos por quem vai partir
58 | Honrem os que não estão mais aqui
59 | Se afaste em respeito a tudo que vivi
60 | A morte está a me seguir
61 |
62 | Que o vento sopre forte pra onde você for
63 | Que a sorte esteja sempre ao seu favor
64 | Que nunca conheça todo esse horror
65 | Lute por amor!
66 |
67 | Escute essa música e mais como essa em:Tragam um copo de rum 68 |
69 |

70 |
71 |
72 | 73 | 86 | 87 | ​ 88 | -------------------------------------------------------------------------------- /C++/insertion-and-deletion-in-stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Stack 4 | { 5 | int size; 6 | int top ; 7 | int *arr; 8 | }; 9 | 10 | class Stack_Class 11 | { 12 | Stack *object; 13 | 14 | protected: 15 | bool isEmpty(); 16 | bool isFull(); 17 | 18 | public: 19 | void creation(); 20 | void push(); 21 | void pop(); 22 | void display(); 23 | }; 24 | 25 | bool Stack_Class ::isEmpty() 26 | { 27 | if (object->top == -1) 28 | { 29 | return true; 30 | } 31 | else 32 | { 33 | return false; 34 | } 35 | } 36 | 37 | bool Stack_Class ::isFull() 38 | { 39 | if (object->top == object->size-1) 40 | { 41 | return true; 42 | } 43 | else 44 | { 45 | return false; 46 | } 47 | } 48 | 49 | void Stack_Class ::creation() 50 | { 51 | int s; 52 | char ch = 'y'; 53 | object->top= -1; 54 | cout << "Enter the size of the stack: "; 55 | cin >> s; 56 | object->size = s; 57 | object->arr = new int[object->size]; 58 | while (ch == 'y' || ch == 'Y') 59 | { 60 | if (isFull()) 61 | { 62 | cout << "The Stack is Full"<top++; 69 | cout << "Enter the element " << object->top << " : "; 70 | cin >> object->arr[object->top]; 71 | cout << endl; 72 | cout << "Do you want to enter more: "; 73 | cin >> ch; 74 | } 75 | } 76 | } 77 | 78 | void Stack_Class::display() 79 | { 80 | for (int i = 0; i <=object->top; i++) 81 | { 82 | cout << object->arr[i] << " "; 83 | } 84 | cout << endl; 85 | } 86 | 87 | void Stack_Class ::push() 88 | { 89 | if (isFull()) 90 | { 91 | cout << "The stack is full"<> element; 98 | object->arr[object->top] = element; 99 | object->top++; 100 | } 101 | } 102 | 103 | void Stack_Class ::pop() 104 | { 105 | if (isEmpty()) 106 | { 107 | cout << "The Stack is empty"<top--; 112 | } 113 | } 114 | int main() 115 | { 116 | int choice; 117 | Stack_Class operations; 118 | do 119 | { 120 | cout << "1. Enter the array" << endl; 121 | cout << "2. Display the array" << endl; 122 | cout << "3. Push the element into the array" << endl; 123 | cout << "4. pop the value in the array" << endl; 124 | cout << "5. Exit" << endl; 125 | cout << endl; 126 | cout << "Enter your choice: "; 127 | cin >> choice; 128 | switch (choice) 129 | { 130 | case 1: 131 | { 132 | operations.creation(); 133 | break; 134 | } 135 | case 2: 136 | { 137 | operations.display(); 138 | break; 139 | } 140 | case 3: 141 | { 142 | operations.push(); 143 | break; 144 | } 145 | case 4: 146 | { 147 | operations.pop(); 148 | break; 149 | } 150 | case 5: 151 | { 152 | 153 | break; 154 | } 155 | 156 | default: 157 | { 158 | cout << "WRONG CHOICE !!!!!!!!!" << endl; 159 | break; 160 | } 161 | } 162 | } while (choice != 5); 163 | return 0; 164 | } -------------------------------------------------------------------------------- /Python/singly-linked-list.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = None 5 | 6 | class LinkedList: 7 | def __init__(self): 8 | self.head = None 9 | self._size = 0 10 | 11 | def __str__(self): 12 | if self.isEmpty(): 13 | return "Empty" 14 | cur, s = self.head, str(self.head.value) + " " 15 | while cur.next != None: 16 | s += str(cur.next.value) + " " 17 | cur = cur.next 18 | return s 19 | 20 | def isEmpty(self): 21 | return self.head == None 22 | 23 | def append(self, item): 24 | self._size += 1 25 | if self.isEmpty(): 26 | self.head = Node(item) 27 | return 28 | node = self.head 29 | while(node.next != None): 30 | node = node.next 31 | node.next = Node(item) 32 | #print(self) 33 | 34 | def addHead(self, item): 35 | self._size += 1 36 | if self.isEmpty(): 37 | self.head = Node(item) 38 | return 39 | node = self.head 40 | self.head = Node(item) 41 | self.head.next = node 42 | 43 | def search(self, item): 44 | node = self.head 45 | if self.isEmpty(): 46 | return "Not Found" 47 | 48 | while node.next != None: 49 | if node.value == item: 50 | return "Found" 51 | node = node.next 52 | if node.value == item: 53 | return "Found" 54 | return "Not Found" 55 | 56 | def index(self, item): 57 | index = 0 58 | node = self.head 59 | if self.isEmpty(): 60 | return -1 61 | 62 | if self.size() == 1: 63 | if node.value == item: 64 | return index 65 | 66 | while node.next != None : 67 | if node.value == item: 68 | return index 69 | node = node.next 70 | index += 1 71 | if node.value == item: 72 | return index 73 | return -1 74 | 75 | def size(self): 76 | return self._size 77 | 78 | def pop(self, pos): 79 | index = 0 80 | if pos >= self.size() or pos < 0: 81 | return "Out of Range" 82 | 83 | if pos == 0 and self.size() == 1: 84 | self.head = self.tail = None 85 | elif pos == 0: 86 | self.head.next.previous = None 87 | self.head = self.head.next 88 | else: 89 | node = self.head 90 | while index != pos - 1: 91 | index += 1 92 | node.next = node.next.next 93 | 94 | self._size -= 1 95 | return "Success" 96 | 97 | if __name__ == "__main__": 98 | L = LinkedList() 99 | inp = input('Enter Input : ').split(',') 100 | for i in inp: 101 | if i[:2] == "AP": 102 | L.append(i[3:]) 103 | elif i[:2] == "AH": 104 | L.addHead(i[3:]) 105 | elif i[:2] == "SE": 106 | print("{0} {1} in {2}".format(L.search(i[3:]), i[3:], L)) 107 | elif i[:2] == "SI": 108 | print("Linked List size = {0} : {1}".format(L.size(), L)) 109 | elif i[:2] == "ID": 110 | print("Index ({0}) = {1} : {2}".format(i[3:], L.index(i[3:]), L)) 111 | elif i[:2] == "PO": 112 | before = "{}".format(L) 113 | k = L.pop(int(i[3:])) 114 | print(("{0} | {1}-> {2}".format(k, before, L)) if k == "Success" else ("{0} | {1}".format(k, L))) 115 | print("Linked List :", L) -------------------------------------------------------------------------------- /C++/infix-to-prefix-postfix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct stack 6 | { 7 | int top; 8 | int size; 9 | char elements[100]; 10 | string str_ele[100]; 11 | }; 12 | void push_char(struct stack &s,char x) 13 | { 14 | if(s.top==s.size-1) 15 | cout<<"Stack is full \n"; 16 | else 17 | { 18 | s.elements[++s.top]=x; 19 | } 20 | } 21 | char peek_char(struct stack &s) 22 | { 23 | if(s.top==-1) 24 | return 'a' ; 25 | else 26 | return s.elements[s.top]; 27 | } 28 | char pop_char(struct stack &s) 29 | { 30 | if(s.top==-1) 31 | return 'a' ; 32 | else 33 | return s.elements[s.top--]; 34 | } 35 | void push_string(struct stack &s,string x) 36 | { 37 | if(s.top==s.size-1) 38 | cout<<"Stack is full \n"; 39 | else 40 | { 41 | s.str_ele[++s.top]=x; 42 | } 43 | } 44 | string peek_string(struct stack &s) 45 | { 46 | if(s.top==-1) 47 | return ".." ; 48 | else 49 | return s.str_ele[s.top]; 50 | } 51 | string pop_string(struct stack &s) 52 | { 53 | if(s.top==-1) 54 | return ".." ; 55 | else 56 | return s.str_ele[s.top--]; 57 | } 58 | bool isoperator(char a) 59 | { 60 | return (a=='*' || a=='/' || a=='-' || a=='+'); 61 | } 62 | bool isbracket(char a) 63 | { 64 | return (a=='(' || a==')'||a=='[' || a==']' || a=='{' ||a=='}' ); 65 | } 66 | int operation(char c) 67 | { 68 | switch(c){ 69 | case '(' : return 0; 70 | case '+' : return 1; 71 | case '-' : return 2; 72 | case '*' : return 3; 73 | case '/' : return 4; 74 | } 75 | return -1; 76 | } 77 | 78 | string ques1(string str) 79 | { 80 | string res=""; 81 | int i; 82 | for(i=str.size()-1;i>-1;i--) 83 | res+=str[i]; 84 | str=res; 85 | for(i=0;i=0) 121 | { 122 | res+=pop_char(s1); 123 | } 124 | str=""; 125 | for(i=res.size()-1;i>-1;i--) 126 | str+=res[i]; 127 | return str; 128 | } 129 | string ques2(string str) 130 | { 131 | int i,n=str.size(); 132 | string res=""; 133 | struct stack s2; 134 | s2.top=-1; 135 | s2.size=100; 136 | for(i=0;i=0) 161 | { 162 | res+=pop_char(s2); 163 | } 164 | return res; 165 | 166 | } 167 | 168 | 169 | 170 | int main() 171 | { 172 | string q1,q2,q3; 173 | cout<<"Enter a infix :\n"; 174 | cin>>q1; 175 | cout<<"infix to prefix : "< 2 | using namespace std; 3 | struct Node 4 | { 5 | string Name; 6 | int roll_number; 7 | Node *next; 8 | }; 9 | 10 | class Node_operations 11 | { 12 | Node *head; 13 | Node *ptr; 14 | protected: 15 | void reset_Position(){ 16 | ptr=head; 17 | } 18 | public: 19 | Node_operations(Node *ptr) 20 | { 21 | head = ptr; 22 | } 23 | void insertion(int number); 24 | void insertion_beginning(); 25 | void insertion_ending(); 26 | void insertion_afterNode(); 27 | void insertion_Node_given_position(); 28 | void display(); 29 | }; 30 | 31 | void Node_operations::display() // for displaying the node 32 | { 33 | 34 | 35 | reset_Position(); 36 | 37 | while (ptr != NULL) 38 | { 39 | cout << ptr->Name << endl; 40 | cout << ptr->roll_number << endl; 41 | cout << endl; 42 | ptr = ptr->next; 43 | } 44 | } 45 | void Node_operations::insertion(int number) // for creating the node and inserting the node. 46 | { 47 | 48 | string name; 49 | int roll_Number; 50 | Node *temp = new Node; 51 | 52 | for (int i = 0; i < number; i++) 53 | { 54 | Node *currentPointer = new Node; 55 | cout << "Enter the Roll Number of Student " << i + 1 << " : " << endl; 56 | cin >> roll_Number; 57 | cout << "Enter the Name of Student " << i + 1 << " : " << endl; 58 | cin >> name; 59 | if (i == 0) 60 | { 61 | head = temp = currentPointer; 62 | } 63 | 64 | currentPointer->Name = name; 65 | currentPointer->roll_number = roll_Number; 66 | currentPointer->next = NULL; 67 | 68 | temp->next = currentPointer; 69 | temp = currentPointer; 70 | } 71 | } 72 | 73 | void Node_operations::insertion_beginning() // for insertion of the node at the beginning 74 | { 75 | int number; 76 | string name; 77 | cout << "Enter the roll number of student which you want to insert in the beginning: "; 78 | cin >> number; 79 | 80 | cout << "Enter the name of student which you want to insert in the beginning: "; 81 | cin >> name; 82 | Node *ptr_beginning = new Node; 83 | ptr_beginning->Name = name; 84 | ptr_beginning->roll_number = number; 85 | 86 | ptr_beginning->next = head; 87 | head = ptr_beginning; 88 | } 89 | 90 | void Node_operations::insertion_ending() 91 | { 92 | Node *temp = new Node; 93 | Node *traversal_node = new Node; 94 | traversal_node = head; 95 | while (traversal_node->next != NULL) 96 | { 97 | traversal_node = traversal_node->next; 98 | } 99 | 100 | cout << "Enter the roll number of the Student: "; 101 | cin >> temp->roll_number; 102 | cout << "Enter the name: "; 103 | cin >> temp->Name; 104 | 105 | temp->next = NULL; 106 | traversal_node->next = temp; 107 | } 108 | 109 | void Node_operations::insertion_Node_given_position() 110 | { 111 | int position; 112 | cout << "Enter the position for which you want to place that Node:- "; 113 | cin >> position; 114 | Node *previous = new Node; 115 | Node *newNode = new Node; 116 | previous = head; 117 | 118 | cout << "Enter the Roll Number of the new node: "; 119 | cin >> newNode->roll_number; 120 | cout << "Enter the Name of the new node: "; 121 | cin >> newNode->Name; 122 | for (int i = 0; i < position - 2; i++) 123 | { 124 | previous = previous->next; 125 | } 126 | 127 | newNode->next = previous->next; 128 | previous->next = newNode; 129 | } 130 | 131 | void Node_operations::insertion_afterNode() 132 | { 133 | int position; 134 | cout << "Enter the position for which you want to place the Node Afterwards"; 135 | cin >> position; 136 | Node *previous = new Node; 137 | Node *newNode = new Node; 138 | previous = head; 139 | 140 | cout << "Enter the Roll No of Student: "; 141 | cin >> newNode->roll_number; 142 | cout << "Enter the name of the Student: "; 143 | cin >> newNode->Name; 144 | for (int i = 0; i < position - 1; i++) 145 | { 146 | previous = previous->next; 147 | } 148 | 149 | newNode->next = previous->next; 150 | previous->next = newNode; 151 | } 152 | 153 | int main() 154 | { 155 | int choice; 156 | int number_of_nodes; 157 | Node *head; 158 | Node_operations operations(head); 159 | do 160 | { 161 | cout << "1. Enter the No of elements in the linked list" << endl; 162 | cout << "2. Insert the Node in the beginning" << endl; 163 | cout << "3. Insert the node in the end" << endl; 164 | cout << "4. Insert the node at a given position" << endl; 165 | cout << "5. Insert the node after the particular node" << endl; 166 | cout << "6. Display the Linked List" << endl; 167 | cout << "7. Exit " << endl; 168 | 169 | cout << "Enter your choice: "; 170 | cin >> choice; 171 | switch (choice) 172 | { 173 | case 1: 174 | { 175 | 176 | cout << "Enter the No of nodes which you want to insert in the linked List: "; 177 | cin >> number_of_nodes; 178 | operations.insertion(number_of_nodes); 179 | break; 180 | } 181 | case 2: 182 | { 183 | operations.insertion_beginning(); 184 | break; 185 | } 186 | case 3: 187 | { 188 | operations.insertion_ending(); 189 | break; 190 | } 191 | case 4: 192 | { 193 | operations.insertion_Node_given_position(); 194 | break; 195 | } 196 | case 5: 197 | { 198 | operations.insertion_afterNode(); 199 | break; 200 | } 201 | case 6: 202 | { 203 | operations.display(); 204 | break; 205 | } 206 | case 7: 207 | { 208 | break; 209 | } 210 | 211 | default: 212 | { 213 | cout << "WRONG CHOICE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; 214 | break; 215 | } 216 | } 217 | } while (choice != 7); 218 | return 0; 219 | } -------------------------------------------------------------------------------- /C++/circular-linked-list-insertion-deletion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node 4 | { 5 | int data; 6 | Node *next; 7 | }; 8 | class Circular_linkedList 9 | { 10 | Node *head; 11 | 12 | public: 13 | void Insertion_at_a_given_Position(); 14 | void Deletion_at_a_given_Position(); 15 | void Deletion_of_a_given_value(); 16 | void LinkedList_Creation(); 17 | void Display(); 18 | }; 19 | 20 | void Circular_linkedList::LinkedList_Creation() 21 | { 22 | Node *ptr = new Node; 23 | int Number_of_nodes; 24 | int information; 25 | cout << "Enter the Number of Nodes you want to create: "; 26 | cin >> Number_of_nodes; 27 | for (int i = 0; i < Number_of_nodes; i++) 28 | { 29 | Node *currentNode = new Node; 30 | cout << "Enter the data of the node " << i + 1 << " : "; 31 | cin >> information; 32 | if (i == 0) 33 | { 34 | head = ptr = currentNode; 35 | } 36 | currentNode->data = information; 37 | currentNode->next = head; 38 | ptr->next = currentNode; 39 | ptr = currentNode; 40 | } 41 | ptr->next = head; 42 | } 43 | 44 | void Circular_linkedList ::Insertion_at_a_given_Position() 45 | { 46 | int data, position; 47 | Node *temp = head; 48 | Node *insertNode = new Node; 49 | 50 | cout << "Enter the position you want to enter the element: "; 51 | cin >> position; 52 | cout << "Enter the data for the node:"; 53 | cin >> data; 54 | insertNode->data = data; 55 | 56 | for (int i = 0; i < position - 2; i++) 57 | { 58 | temp = temp->next; 59 | } 60 | if (position == 1) 61 | { 62 | Node *ptr = head; 63 | ptr = ptr->next; 64 | while (ptr->next != head) // it will place the ptr node just before the next node. 65 | { 66 | ptr = ptr->next; 67 | } 68 | 69 | insertNode->next = ptr->next; 70 | ptr->next = insertNode; 71 | head = ptr->next; 72 | } 73 | else 74 | { 75 | insertNode->next = temp->next; 76 | temp->next = insertNode; 77 | } 78 | } 79 | 80 | void Circular_linkedList::Display() 81 | { 82 | Node *temp = head; 83 | if (head == NULL) 84 | { 85 | cout << "Linked List Empty"; 86 | } 87 | else 88 | { 89 | cout << head->data << " "; 90 | temp = temp->next; 91 | while (temp != head) 92 | { 93 | cout << temp->data << " "; 94 | temp = temp->next; 95 | } 96 | } 97 | 98 | cout << endl; 99 | } 100 | 101 | void Circular_linkedList ::Deletion_at_a_given_Position() 102 | { 103 | int position; 104 | Node *temp = head; 105 | Node *forwardTemp = head; 106 | cout << "Enter the given position: "; 107 | cin >> position; 108 | 109 | if (position == 1) 110 | { 111 | Node *ptr = head; 112 | Node *temp = head; 113 | ptr = ptr->next; 114 | while (ptr->next != head) 115 | { 116 | ptr = ptr->next; 117 | } 118 | ptr->next = head->next; 119 | head = head->next; 120 | temp->next = NULL; 121 | delete temp; 122 | } 123 | else 124 | { 125 | for (int i = 0; i < position - 2; i++) 126 | { 127 | temp = temp->next; 128 | forwardTemp = temp->next; 129 | } 130 | 131 | temp->next = forwardTemp->next; 132 | forwardTemp->next = NULL; 133 | delete forwardTemp; 134 | } 135 | } 136 | 137 | void Circular_linkedList ::Deletion_of_a_given_value() 138 | { 139 | int data,position,count=0; 140 | bool flag = false; 141 | cout << "Enter the data Which you want to delete: "; 142 | cin >> data; 143 | Node *temp = head; 144 | temp = temp->next; 145 | if (head->data == data) 146 | { 147 | Node *ptr = head; 148 | Node *temp = head; 149 | ptr = ptr->next; 150 | while (ptr->next != head) 151 | { 152 | ptr = ptr->next; 153 | } 154 | ptr->next = head->next; 155 | head = head->next; 156 | temp->next = NULL; 157 | delete temp; 158 | 159 | } 160 | else 161 | { 162 | Node *temp = head; 163 | temp=temp->next; 164 | Node *ptr=head; 165 | while (temp!=head) 166 | { 167 | if(temp->data==data){ 168 | break; 169 | } 170 | temp=temp->next; 171 | 172 | } 173 | while(ptr->next!=temp){ 174 | ptr=ptr->next; 175 | } 176 | 177 | ptr->next=temp->next; 178 | temp->next=NULL; 179 | delete temp; 180 | 181 | } 182 | } 183 | 184 | int main() 185 | { 186 | int choice; 187 | Circular_linkedList operations; 188 | do 189 | { 190 | cout << "1. Create the Linked List" << endl; 191 | cout << "2. Display the Linked List" << endl; 192 | cout << "3. Insert at a given position" << endl; 193 | cout << "4. Deletion at a given position" << endl; 194 | cout << "5. Deletion of a given value" << endl; 195 | cout << "6. Exit"; 196 | cout << endl; 197 | cout << "Enter your choice: "; 198 | cin >> choice; 199 | switch (choice) 200 | { 201 | case 1: 202 | { 203 | operations.LinkedList_Creation(); 204 | break; 205 | } 206 | case 2: 207 | { 208 | operations.Display(); 209 | break; 210 | } 211 | case 3: 212 | { 213 | operations.Insertion_at_a_given_Position(); 214 | break; 215 | } 216 | case 4: 217 | { 218 | operations.Deletion_at_a_given_Position(); 219 | break; 220 | } 221 | case 5: 222 | { 223 | operations.Deletion_of_a_given_value(); 224 | break; 225 | } 226 | 227 | case 6: 228 | { 229 | 230 | break; 231 | } 232 | 233 | default: 234 | cout<<"WRONG CHOICE !!!!!!!!!!!!!!!!!!!!!"; 235 | break; 236 | } 237 | } while (choice != 6); 238 | 239 | return 0; 240 | } -------------------------------------------------------------------------------- /C++/linked-list-deletion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node 4 | { 5 | int data; 6 | Node *next; 7 | }; 8 | 9 | class NodeClass 10 | { 11 | Node *head=NULL; 12 | Node *ptr; 13 | int data; 14 | 15 | protected: 16 | void Message(); 17 | void display_reset(); 18 | 19 | public: 20 | void LinkedListCreation(); 21 | void Deleting_the_First_node(); 22 | void Deleting_the_Last_node(); 23 | void Deleting_the_node_of_given_value(); 24 | void Deleting_the_node_of_given_position(); 25 | void Display(); 26 | }; 27 | 28 | 29 | void NodeClass :: Message(){ 30 | if (head == NULL){ 31 | cout<<"Linked List Empty"<> position; 41 | Message(); 42 | Node *traversal = head; 43 | Node *previous = head; 44 | 45 | for (int i = 0; i < position - 1; i++) 46 | { 47 | traversal = traversal->next; 48 | } 49 | for (int i = 0; i < position - 2; i++) 50 | { 51 | previous = previous->next; 52 | } 53 | 54 | if (traversal == head) 55 | { 56 | head=traversal->next; 57 | traversal->next=NULL; 58 | delete traversal; 59 | } 60 | else 61 | { 62 | previous->next = traversal->next; 63 | traversal->next = NULL; 64 | delete traversal; 65 | } 66 | } 67 | 68 | void NodeClass ::Deleting_the_node_of_given_value() // for deleting the node at the given value. 69 | { 70 | int value; 71 | bool flag = false; 72 | cout << "Enter the Value which you want to delete: "; 73 | cin >> value; 74 | Message(); 75 | if (head->data == value) 76 | { 77 | Node *headStore = head; 78 | head = head->next; 79 | delete headStore; 80 | } 81 | else 82 | { 83 | Node *traversal_Node = head; 84 | Node *previousNode = head; 85 | 86 | while (traversal_Node != NULL) 87 | { 88 | if (traversal_Node->data == value) 89 | { 90 | flag = true; 91 | break; 92 | } 93 | traversal_Node = traversal_Node->next; 94 | } 95 | 96 | while (previousNode->next != traversal_Node) 97 | { 98 | previousNode = previousNode->next; 99 | } 100 | 101 | if (flag) 102 | { 103 | previousNode->next = traversal_Node->next; 104 | traversal_Node->next = NULL; 105 | delete traversal_Node; 106 | } 107 | else 108 | { 109 | cout << "Value not present in the Linked List: "; 110 | } 111 | } 112 | } 113 | 114 | void NodeClass ::Deleting_the_Last_node() // for deleting the last node in the linked list 115 | { 116 | Message(); 117 | Node *traversal_Node = head; 118 | Node *previousNode = head; 119 | while (traversal_Node->next != NULL) 120 | { 121 | traversal_Node = traversal_Node->next; 122 | } 123 | while (previousNode->next != traversal_Node) 124 | { 125 | previousNode = previousNode->next; 126 | } 127 | 128 | previousNode->next = NULL; 129 | delete traversal_Node; 130 | } 131 | 132 | void NodeClass ::Deleting_the_First_node() // for deleting the node at the beginning. 133 | { 134 | Message(); 135 | Node *D = new Node; 136 | D = head; 137 | head = D->next; 138 | D->next = NULL; 139 | delete D; 140 | } 141 | 142 | void NodeClass ::display_reset() 143 | { 144 | ptr = head; 145 | } 146 | 147 | void NodeClass::LinkedListCreation() 148 | { 149 | int Number_Nodes, elemental_data; 150 | Node *ptr = new Node; 151 | cout << "Enter the number of nodes for which you want an Linked List: "; 152 | cin >> Number_Nodes; 153 | 154 | for (int i = 0; i < Number_Nodes; i++) 155 | { 156 | Node *currentNode = new Node; 157 | cout << "Enter the Data for the node " << i + 1 << " : "; 158 | cin >> elemental_data; 159 | if (i == 0) 160 | { 161 | head = ptr = currentNode; 162 | } 163 | currentNode->data = elemental_data; 164 | currentNode->next = NULL; 165 | ptr->next = currentNode; 166 | ptr = currentNode; 167 | } 168 | } 169 | void NodeClass ::Display() 170 | { 171 | Message(); 172 | display_reset(); 173 | while (ptr != NULL) 174 | { 175 | cout << ptr->data << endl; 176 | ptr = ptr->next; 177 | } 178 | } 179 | 180 | int main() 181 | { 182 | int choice; 183 | Node *ptr = new Node; 184 | NodeClass operations; 185 | do 186 | { 187 | /* code */ 188 | cout << "1. Enter the Numbers of Node you want in the Linked list" << endl; 189 | cout << "2. Display the Linked List" << endl; 190 | cout << "3. Delete the node from the beginning" << endl; 191 | cout << "4. Delete the node from the end" << endl; 192 | cout << "5. Delete the node of the given value" << endl; 193 | cout << "6. Delete the node at the given position in between" << endl; 194 | cout << "7. Exit" << endl; 195 | cout << endl; 196 | cout << "Enter your choice: "; 197 | cin >> choice; 198 | switch (choice) 199 | { 200 | case 1: 201 | { 202 | operations.LinkedListCreation(); 203 | break; 204 | } 205 | case 2: 206 | { 207 | operations.Display(); 208 | break; 209 | } 210 | case 3: 211 | { 212 | operations.Deleting_the_First_node(); 213 | break; 214 | } 215 | case 4: 216 | { 217 | operations.Deleting_the_Last_node(); 218 | break; 219 | } 220 | case 5: 221 | { 222 | operations.Deleting_the_node_of_given_value(); 223 | break; 224 | } 225 | case 6: 226 | { 227 | operations.Deleting_the_node_of_given_position(); 228 | break; 229 | } 230 | case 7: 231 | { 232 | break; 233 | } 234 | 235 | default: 236 | { 237 | cout << "Wrong choice!!!!!!!!"; 238 | } 239 | } 240 | } while (choice != 7); 241 | 242 | return 0; 243 | } -------------------------------------------------------------------------------- /C++/tic-tac-toe.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | char board[9] = {' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' '}; 7 | void show_board(); 8 | void get_x_player_choice(); 9 | void get_o_player_choice(); 10 | void get_computer_choice(); 11 | int count_board(char symbol); 12 | char check_winner(); 13 | void computer_vs_player(); 14 | void player_vs_player(); 15 | 16 | int main() 17 | { 18 | int mode; 19 | cout << "1. Computer VS Player." << endl; 20 | cout << "2. Player VS Player." << endl; 21 | cout << "Select Game Mode: 1/2?:" << endl; 22 | cin >> mode; 23 | switch(mode) { 24 | case 1 : 25 | computer_vs_player(); 26 | break; 27 | case 2: 28 | player_vs_player(); 29 | break; 30 | default : 31 | cout << "Please Select Valid Game Mode." << endl; 32 | break; 33 | } 34 | return 0; 35 | } 36 | 37 | void computer_vs_player() { 38 | string player_name; 39 | cout << "Enter Your Name: "; 40 | cin >> player_name; 41 | while(true) { 42 | system("cls"); 43 | show_board(); 44 | if(count_board('X') == count_board('O')) { 45 | cout << player_name << "'s Turn." << endl; 46 | get_x_player_choice(); 47 | } 48 | else{ 49 | get_computer_choice(); 50 | } 51 | char winner = check_winner(); 52 | if(winner == 'X') { 53 | system("cls"); 54 | show_board(); 55 | cout << player_name << " Won The Game." << endl; 56 | break; 57 | } 58 | else if(winner == 'O') { 59 | system("cls"); 60 | show_board(); 61 | cout << "Computer Won The Game." << endl; 62 | break; 63 | } 64 | else if(winner == 'D') { 65 | cout << "Game is Draw." << endl; 66 | break; 67 | } 68 | } 69 | } 70 | 71 | void get_computer_choice() { 72 | srand(time(0)); 73 | int choice; 74 | do{ 75 | choice = rand()%10; 76 | }while(board[choice] != ' '); 77 | board[choice] = 'O'; 78 | } 79 | 80 | void get_x_player_choice() { 81 | while(true) { 82 | cout << "Select Your Position (1 – 9): " ; 83 | int choice; 84 | cin >> choice; 85 | choice--; 86 | if(choice < 0 || choice > 8) { 87 | cout << "Please Select Your Choice From (1 – 9)." << endl; 88 | } 89 | else if(board[choice] != ' ') { 90 | cout << "Please Select An Empty Position." << endl; 91 | } 92 | else { 93 | board[choice] = 'X'; 94 | break; 95 | } 96 | } 97 | } 98 | 99 | void get_o_player_choice() { 100 | while(true) { 101 | cout << "Select Your Position (1 – 9): " ; 102 | int choice; 103 | cin >> choice; 104 | choice--; 105 | if(choice < 0 || choice > 8) { 106 | cout << "Please Select Your Choice From (1 – 9)." << endl; 107 | } 108 | else if(board[choice] != ' ') { 109 | cout << "Please Select An Empty Position." << endl; 110 | } 111 | else { 112 | board[choice] = 'O'; 113 | break; 114 | } 115 | } 116 | } 117 | 118 | void player_vs_player() { 119 | string x_player_name , o_player_name; 120 | cout << "Enter X Player Name: " ; 121 | cin >> x_player_name; 122 | cout << "Enter O Player Name: " ; 123 | cin >> o_player_name; 124 | while(true) { 125 | system("cls"); 126 | show_board(); 127 | if(count_board('X') == count_board('O')) { 128 | cout << x_player_name << "'s Turn." << endl; 129 | get_x_player_choice(); 130 | } 131 | else{ 132 | cout << o_player_name << "'s Turn." << endl; 133 | get_o_player_choice(); 134 | } 135 | char winner = check_winner(); 136 | if(winner == 'X') { 137 | system("cls"); 138 | show_board(); 139 | cout << x_player_name << " Won The Game." << endl; 140 | break; 141 | } 142 | else if(winner == 'O') { 143 | system("cls"); 144 | show_board(); 145 | cout << o_player_name << " Won The Game." << endl; 146 | break; 147 | } 148 | else if(winner == 'D') { 149 | cout << "Game is Draw." << endl; 150 | break; 151 | } 152 | } 153 | } 154 | 155 | int count_board(char symbol) { 156 | int total = 0; 157 | for(int i=0; i<9; i++) { 158 | if(board[i] == symbol) 159 | total += 1; 160 | } 161 | return total; 162 | } 163 | 164 | char check_winner() { 165 | // checking winner in horizontal/row 166 | if(board[0] == board[1] && board[1] == board[2] && board[0] != ' ') 167 | return board[0]; 168 | if(board[3] == board[4] && board[4] == board[5] && board[3] != ' ') 169 | return board[3]; 170 | if(board[6] == board[7] && board[7] == board[8] && board[6] != ' ') 171 | return board[6]; 172 | // checking winner in vertical/column 173 | if(board[0] == board[3] && board[3] == board[6] && board[0] != ' ') 174 | return board[0]; 175 | if(board[1] == board[4] && board[4] == board[7] && board[1] != ' ') 176 | return board[1]; 177 | if(board[2] == board[5] && board[5] == board[8] && board[2] != ' ') 178 | return board[2]; 179 | // checking winner in diagonal 180 | if(board[0] == board[4] && board[4] == board[8] && board[0] != ' ') 181 | return board[0]; 182 | if(board[2] == board[4] && board[4] == board[6] && board[2] != ' ') 183 | return board[2]; 184 | if(count_board('X') + count_board('O') < 9) 185 | return 'C'; 186 | else 187 | return 'D'; 188 | } 189 | 190 | void show_board() { 191 | 192 | cout << " " << " | " << " | " << endl; 193 | cout << " " << board[0] << " | " << board[1] << " | " << board[2] << endl; 194 | cout << " " << " | " << " | " << endl; 195 | cout << "--------------------------" << endl; 196 | cout << " " << " | " << " | " << endl; 197 | cout << " " << board[3] << " | " << board[4] << " | " << board[5] << endl; 198 | cout << " " << " | " << " | " << endl; 199 | cout << "--------------------------" << endl; 200 | cout << " " << " | " << " | " << endl; 201 | cout << " " << board[6] << " | " << board[7] << " | " << board[8] << endl; 202 | cout << " " << " | " << " | " << endl; 203 | 204 | } -------------------------------------------------------------------------------- /Python/avl-tree.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, k, v): 3 | self.key = k 4 | self.value = v 5 | self.left = None 6 | self.right = None 7 | self.parent = None 8 | self.height = 1 9 | self.num_left = 1 10 | self.num_total = 1 11 | 12 | 13 | class AvlTree: 14 | 15 | def __init__(self): 16 | self._tree = None 17 | 18 | def add(self, k, v): 19 | if not self._tree: 20 | self._tree = TreeNode(k, v) 21 | return 22 | node = self._add(k, v) 23 | if node: 24 | self._rebalance(node) 25 | 26 | def _add(self, k, v): 27 | node = self._tree 28 | while node: 29 | if k < node.key: 30 | if node.left: 31 | node = node.left 32 | else: 33 | node.left = TreeNode(k, v) 34 | node.left.parent = node 35 | return node.left 36 | elif node.key < k: 37 | if node.right: 38 | node = node.right 39 | else: 40 | node.right = TreeNode(k, v) 41 | node.right.parent = node 42 | return node.right 43 | else: 44 | node.value = v 45 | return 46 | 47 | @staticmethod 48 | def get_height(x): 49 | return x.height if x else 0 50 | 51 | @staticmethod 52 | def get_num_total(x): 53 | return x.num_total if x else 0 54 | 55 | def _rebalance(self, node): 56 | 57 | n = node 58 | while n: 59 | lh = self.get_height(n.left) 60 | rh = self.get_height(n.right) 61 | n.height = max(lh, rh) + 1 62 | balance_factor = lh - rh 63 | n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) 64 | n.num_left = 1 + self.get_num_total(n.left) 65 | 66 | if balance_factor > 1: 67 | if self.get_height(n.left.left) < self.get_height(n.left.right): 68 | self._rotate_left(n.left) 69 | self._rotate_right(n) 70 | elif balance_factor < -1: 71 | if self.get_height(n.right.right) < self.get_height(n.right.left): 72 | self._rotate_right(n.right) 73 | self._rotate_left(n) 74 | else: 75 | n = n.parent 76 | 77 | def _remove_one(self, node): 78 | """ 79 | Side effect!!! Changes node. Node should have exactly one child 80 | """ 81 | replacement = node.left or node.right 82 | if node.parent: 83 | if AvlTree._is_left(node): 84 | node.parent.left = replacement 85 | else: 86 | node.parent.right = replacement 87 | replacement.parent = node.parent 88 | node.parent = None 89 | else: 90 | self._tree = replacement 91 | replacement.parent = None 92 | node.left = None 93 | node.right = None 94 | node.parent = None 95 | self._rebalance(replacement) 96 | 97 | def _remove_leaf(self, node): 98 | if node.parent: 99 | if AvlTree._is_left(node): 100 | node.parent.left = None 101 | else: 102 | node.parent.right = None 103 | self._rebalance(node.parent) 104 | else: 105 | self._tree = None 106 | node.parent = None 107 | node.left = None 108 | node.right = None 109 | 110 | def remove(self, k): 111 | node = self._get_node(k) 112 | if not node: 113 | return 114 | if AvlTree._is_leaf(node): 115 | self._remove_leaf(node) 116 | return 117 | if node.left and node.right: 118 | nxt = AvlTree._get_next(node) 119 | node.key = nxt.key 120 | node.value = nxt.value 121 | if self._is_leaf(nxt): 122 | self._remove_leaf(nxt) 123 | else: 124 | self._remove_one(nxt) 125 | self._rebalance(node) 126 | else: 127 | self._remove_one(node) 128 | 129 | def get(self, k): 130 | node = self._get_node(k) 131 | return node.value if node else -1 132 | 133 | def _get_node(self, k): 134 | if not self._tree: 135 | return None 136 | node = self._tree 137 | while node: 138 | if k < node.key: 139 | node = node.left 140 | elif node.key < k: 141 | node = node.right 142 | else: 143 | return node 144 | return None 145 | 146 | def get_at(self, pos): 147 | x = pos + 1 148 | node = self._tree 149 | while node: 150 | if x < node.num_left: 151 | node = node.left 152 | elif node.num_left < x: 153 | x -= node.num_left 154 | node = node.right 155 | else: 156 | return (node.key, node.value) 157 | raise IndexError("Out of ranges") 158 | 159 | @staticmethod 160 | def _is_left(node): 161 | return node.parent.left and node.parent.left == node 162 | 163 | @staticmethod 164 | def _is_leaf(node): 165 | return node.left is None and node.right is None 166 | 167 | def _rotate_right(self, node): 168 | if not node.parent: 169 | self._tree = node.left 170 | node.left.parent = None 171 | elif AvlTree._is_left(node): 172 | node.parent.left = node.left 173 | node.left.parent = node.parent 174 | else: 175 | node.parent.right = node.left 176 | node.left.parent = node.parent 177 | bk = node.left.right 178 | node.left.right = node 179 | node.parent = node.left 180 | node.left = bk 181 | if bk: 182 | bk.parent = node 183 | node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 184 | node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) 185 | node.num_left = 1 + self.get_num_total(node.left) 186 | 187 | def _rotate_left(self, node): 188 | if not node.parent: 189 | self._tree = node.right 190 | node.right.parent = None 191 | elif AvlTree._is_left(node): 192 | node.parent.left = node.right 193 | node.right.parent = node.parent 194 | else: 195 | node.parent.right = node.right 196 | node.right.parent = node.parent 197 | bk = node.right.left 198 | node.right.left = node 199 | node.parent = node.right 200 | node.right = bk 201 | if bk: 202 | bk.parent = node 203 | node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 204 | node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) 205 | node.num_left = 1 + self.get_num_total(node.left) 206 | 207 | @staticmethod 208 | def _get_next(node): 209 | if not node.right: 210 | return node.parent 211 | n = node.right 212 | while n.left: 213 | n = n.left -------------------------------------------------------------------------------- /C++/snake-game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | class Snake 10 | { 11 | int p1,p2,v1,v2,v3,e1,e2,prev,now,n,colr,dsp,cnt,dly,m; 12 | int stp, egGen; 13 | int xr, yr; 14 | void caught(); 15 | public: 16 | long scr; 17 | int strtX,strtY,endX,endY; 18 | int pos[100][2]; 19 | void show(); 20 | void init(); 21 | void egg(); 22 | void transpose(); 23 | void gnrtCond(); 24 | void gnrtUnCond(); 25 | void check(); 26 | void checkEgg(); 27 | void move(); 28 | void chngDir(); 29 | void sndEt(); 30 | void sndCgt(); 31 | int test(); 32 | void score(); 33 | Snake(); 34 | Snake(Snake*); 35 | ~Snake(); 36 | }; 37 | Snake::Snake() 38 | { 39 | } 40 | Snake::~Snake() 41 | { 42 | } 43 | void Snake::checkEgg() 44 | { 45 | if((e1 == p1) && (e2 == p2)) 46 | { sndEt(); 47 | egg(); 48 | dly--; 49 | score(); 50 | n++; 51 | } 52 | } 53 | void Snake::sndEt() 54 | { nosound(); 55 | sound(2500); 56 | delay(2); 57 | nosound(); 58 | } 59 | void Snake::sndCgt() 60 | { nosound(); 61 | for(int x=1000;x>0;x--) 62 | { sound(x); 63 | delay(1); 64 | } 65 | nosound(); 66 | } 67 | void Snake::score() 68 | { char *p; 69 | ltoa(scr,p,10); 70 | settextstyle(8,0,1); 71 | setcolor(0); 72 | outtextxy(585,40,p); 73 | if(egGen != 1){ 74 | scr = scr + dly / 10; 75 | } 76 | ltoa(scr,p,10); 77 | setcolor(10); 78 | outtextxy(585,40,p); 79 | } 80 | void Snake::gnrtCond() 81 | { if(n < 367) 82 | { if(now == 8 && (prev != 8 && prev != 2)) 83 | { pos[0][0] = p1; 84 | pos[0][1] = p2 - dsp; 85 | prev = now; 86 | } 87 | if(now == 4 && (prev != 4 && prev != 1)) 88 | { pos[0][0] = p1 + dsp; 89 | pos[0][1] = p2; 90 | prev = now; 91 | } 92 | if(now == 2 && (prev != 8 && prev != 2)) 93 | { pos[0][0] = p1; 94 | pos[0][1] = p2 + dsp; 95 | prev = now; 96 | } 97 | if(now == 1 && (prev != 1 && prev != 4)) 98 | {pos[0][0] = p1 - dsp; 99 | pos[0][1] = p2; 100 | prev = now; 101 | } 102 | } 103 | } 104 | void Snake::gnrtUnCond() 105 | { 106 | if( prev == 8 ) 107 | { pos[0][0] = p1; 108 | pos[0][1] = p2 - dsp; 109 | } 110 | if( prev == 4 ) 111 | {pos[0][0] = p1 + dsp; 112 | pos[0][1] = p2; 113 | } 114 | if( prev == 2 ) 115 | { pos[0][0] = p1; 116 | pos[0][1] = p2 + dsp; 117 | } 118 | if( prev == 1 ) 119 | {pos[0][0] = p1 - dsp; 120 | pos[0][1] = p2; 121 | } 122 | p1 = pos[0][0]; 123 | p2 = pos[0][1]; 124 | } 125 | void Snake::check() 126 | { 127 | if(p1 > endX) 128 | {p1 = strtX;} 129 | else if(p1 < strtX) 130 | { p1 = endX;} 131 | if(p2 > endY) 132 | { p2 = strtY;} 133 | else if(p2 < strtY) 134 | { p2 = endY;} 135 | pos[0][0] = p1; 136 | pos[0][1] = p2; 137 | for(int i = 1;i < n;i++) 138 | { if(p1 == pos[i][0] && p2 == pos[i][1]) 139 | { caught(); 140 | break; 141 | } 142 | } 143 | } 144 | void Snake::show() 145 | { 146 | int x = getcolor(); 147 | if(egGen != 1) 148 | { 149 | setcolor(getbkcolor()); 150 | setfillstyle(1,getbkcolor()); 151 | fillellipse(v1,v2,yr,yr); 152 | } 153 | else 154 | egGen = 0; 155 | if(egGen == 2) 156 | egGen--; 157 | setcolor(colr); 158 | setfillstyle(1,9); 159 | if(now == 8 || now == 2) 160 | fillellipse(pos[0][0],pos[0][1],xr,yr); 161 | else if(now == 4 || now == 1) 162 | fillellipse(pos[0][0],pos[0][1],yr,xr); 163 | setcolor(x); 164 | } 165 | void Snake::transpose() 166 | { int i,j,x,y; 167 | p1 = pos[0][0]; 168 | p2 = pos[0][1]; 169 | if(!egGen){ 170 | v1 = pos[n-1][0]; 171 | v2 = pos[n-1][1]; 172 | } 173 | else 174 | egGen = 0; 175 | for(i = n-1;i >= 1;i--) 176 | {pos[i][0] = pos[i-1][0]; 177 | pos[i][1] = pos[i-1][1]; 178 | } 179 | } 180 | void Snake::move() 181 | { int st = 0; 182 | do{ 183 | if(!kbhit()) 184 | { checkEgg(); 185 | if(!st) 186 | show(); 187 | else 188 | st = 0; 189 | delay(dly/4); 190 | transpose(); 191 | delay(dly/4); 192 | gnrtUnCond(); 193 | delay(dly/4); 194 | check(); 195 | delay(dly/4); 196 | } 197 | else if(stp){ 198 | chngDir(); 199 | gnrtCond(); 200 | check(); 201 | show(); 202 | st = 1; 203 | } 204 | } while(stp); 205 | } 206 | void Snake::init() 207 | {time_t tm; 208 | srand(time(&tm)); 209 | dsp = 20; 210 | n = 5; 211 | prev = 4; 212 | for(int i = 4;i >= 0;i--) 213 | { pos[i][0] = 201 + (n - i - 1) * dsp; 214 | pos[i][1] = 301; 215 | } 216 | strtX = 21; 217 | strtY = 21; 218 | endX = 481; 219 | endY = 361; 220 | colr = 14; 221 | now = prev; 222 | dsp = 20; 223 | stp = 111; 224 | cnt = -1; 225 | scr = 0; 226 | dly = 150; 227 | xr = 3; 228 | yr = 9; 229 | egg(); 230 | egGen = 1; 231 | score(); 232 | int x = getcolor(); 233 | setlinestyle(0,1,3); 234 | setcolor(15); 235 | rectangle(strtX-15,strtY-15,endX+15,endY+15); 236 | rectangle(endX+25,strtY-15,getmaxx()-15,endY+15); 237 | rectangle(strtX-15,endY+25,getmaxx()-15,getmaxy()-5); 238 | line(endX+25,strtY+75,getmaxx()-15,strtY+75); 239 | line(endX+25,strtY+200,getmaxx()-15,strtY+200); 240 | line(endX+25,strtY+275,getmaxx()-15,strtY+275); 241 | setlinestyle(0,1,1); 242 | settextstyle(8,0,1); 243 | setcolor(11); 244 | outtextxy(514,40,"SCORE"); 245 | setcolor(14); 246 | settextstyle(11,0,5); 247 | outtextxy(524,110," CONTROLS "); 248 | outtextxy(522,135,"p = PAUSE"); 249 | outtextxy(522,155,"g = RESUME"); 250 | outtextxy(522,175,"e = EXIT"); 251 | outtextxy(513,195,"ARROWS"); 252 | outtextxy(512,205," -MOVEMENT"); 253 | setcolor(14); 254 | settextstyle(4,0,9); 255 | outtextxy(getmaxx()-500,getmaxy()-110,"SNAKE"); 256 | settextstyle(8,0,1); 257 | setcolor(x); 258 | } 259 | void Snake::caught() 260 | { 261 | stp = 0; 262 | sndCgt(); 263 | for(int i=0;i<=7;i++) 264 | { if(i%2) 265 | { setcolor(10); 266 | outtextxy(512,250,"GAME OVER"); 267 | delay(900); 268 | } 269 | else 270 | {setcolor(0); 271 | outtextxy(512,250,"GAME OVER"); 272 | delay(500); 273 | } 274 | } 275 | sleep(1); 276 | } 277 | void Snake::chngDir() 278 | { int clr; 279 | fillsettingstype *p; 280 | char x = getch(); 281 | if(x == 72) 282 | now = 8; 283 | else if(x == 77) 284 | now = 4; 285 | else if(x == 80) 286 | now = 2; 287 | else if(x == 75) 288 | now = 1; 289 | else if(x == 'e') 290 | caught(); 291 | else if(x == 'p') 292 | { //int y = getcolor(); 293 | int twnkl = 1; 294 | settextstyle(11,0,9); 295 | while(1) 296 | {if(kbhit()) 297 | { int c = getch(); 298 | if(c == 'g') 299 | { clr = getcolor(); 300 | setcolor(0); 301 | rectangle(endX+40,endY-10,getmaxx()-35,getmaxy()-160); 302 | outtextxy(endX+60,endY-29,"PAUSE"); 303 | break; 304 | } 305 | } 306 | else 307 | { if(twnkl%2) 308 | { clr = getcolor(); 309 | setcolor(10); 310 | rectangle(endX+40,endY-10,getmaxx()-35,getmaxy()-160); 311 | outtextxy(endX+60,endY-29,"PAUSE"); 312 | setcolor(clr); 313 | delay(1000); 314 | } 315 | else 316 | { 317 | clr = getcolor(); 318 | setcolor(0); 319 | rectangle(endX+40,endY-10,getmaxx()-35,getmaxy()-160); 320 | outtextxy(endX+60,endY-29,"PAUSE"); 321 | delay(1000); 322 | } 323 | } 324 | twnkl++; 325 | } 326 | settextstyle(8,0,1); 327 | } 328 | } 329 | Snake::Snake(Snake *p) 330 | { 331 | *p=NULL; 332 | } 333 | void Snake::egg() 334 | { do 335 | { e1 = (rand() % 100) * dsp + strtX; 336 | e2 = (rand() % 100) * dsp + strtY; 337 | } while(test()); 338 | int x = getcolor(); 339 | setcolor(7); 340 | setfillstyle(1,random(15)+1); 341 | fillellipse(e1,e2,xr+2,xr+2); 342 | setcolor(x); 343 | egGen = 2; 344 | } 345 | int Snake::test() 346 | { 347 | for(int i=0;i= endX+1) || (e2 >= endY+1)) 353 | break; 354 | } 355 | if(i != n) 356 | return 1; 357 | else 358 | return 0; 359 | } 360 | void main() 361 | { 362 | Snake snk; 363 | int gd=DETECT,gm,i,j,k,x,y; 364 | clrscr(); 365 | initgraph(&gd,&gm,"C:\\Turboc3\\bgi"); 366 | snk.init(); 367 | snk.move(); 368 | closegraph(); 369 | restorecrtmode(); 370 | } 371 | --------------------------------------------------------------------------------