diff --git a/4Sum.cpp b/4Sum.cpp new file mode 100644 index 0000000..5e1811d --- /dev/null +++ b/4Sum.cpp @@ -0,0 +1,80 @@ +// Question- + +// Suppose we have an array of numbers. It stores n integers, there are four elements a, b, c and d in the array. We have another target value, such that a + b + c + d = target. Find all unique quadruplets in the array which satisfies the situation. So if the array is like [-1,0,1,2,0,-2] and target is 0, then the result will be [[-1, 0, 0, 1],[-2, -1, 1, 2], [-2, 0, 0, 2]] +// Input- +// [1,0,-1,0,-2,2] +// 0 +// Output- +// [[1,2,-1,-2],[0,2,0,-2],[0,1,0,-1]] + + + +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} diff --git a/4_Sum.cpp b/4_Sum.cpp new file mode 100644 index 0000000..792ffaa --- /dev/null +++ b/4_Sum.cpp @@ -0,0 +1,92 @@ + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ +// Question- + +/* Suppose we have an array of numbers. It stores n integers, there are four elements a, b, c and d in the array. We have another target value, such that a + b + c + d = target. Find all the unique quadruplets in the array which satisfies the situation. So if the array is like [-1,0,1,2,0,-2] and target is 0, then the result will be [[-1, 0, 0, 1],[-2, -1, 1, 2], [-2, 0, 0, 2]] + Input- + [1,0,-1,0,-2,2] + 0 + Output +[[1,2,-1,-2],[0,2,0,-2],[0,1,0,-1]] */ + + + +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ diff --git a/Armstrongnumber.java b/Armstrongnumber.java new file mode 100644 index 0000000..141dda7 --- /dev/null +++ b/Armstrongnumber.java @@ -0,0 +1,22 @@ +//finding armstrong number in java +public class Armstrong { + + public static void main(String[] args) { + + int number = 371, originalNumber, remainder, result = 0; + + originalNumber = number; + + while (originalNumber != 0) + { + remainder = originalNumber % 10; + result += Math.pow(remainder, 3); + originalNumber /= 10; + } + + if(result == number) + System.out.println(number + " is an Armstrong number."); + else + System.out.println(number + " is not an Armstrong number."); + } +} diff --git a/C#/RadianDegreeConverter.cs b/C#/RadianDegreeConverter.cs new file mode 100644 index 0000000..3a638a8 --- /dev/null +++ b/C#/RadianDegreeConverter.cs @@ -0,0 +1,26 @@ +using System; + +namespace Conversions +{ + public static class RadianDegreeConverter + { + /// + /// Converts given degree to radian + /// + /// + /// + public static double DegreeToRadian(double degree) + { + return degree * (Math.PI / 180); + } + + /// + /// Converts given radian to degree + /// + /// + public static double RadianToDegree(double radian) + { + return radian * (180 / Math.PI); + } + } +} \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d6613c8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,2 @@ +this repository is only for algorithms in which you can upload any language's algorithms which will useful for many other people. +happy coading 👨‍💻. diff --git a/CPP/4sum.cpp b/CPP/4sum.cpp new file mode 100644 index 0000000..62233e4 --- /dev/null +++ b/CPP/4sum.cpp @@ -0,0 +1,143 @@ +// C++ program to find four +// elements with the given sum +#include + +using namespace std; + +// Function to find 4 elements that add up to +// given sum + +void fourSum(int X, int arr[], map> Map, int N) +{ + + int temp[N]; + + + // Iterate from 0 to temp.length + + for (int i = 0; i < N; i++) + + temp[i] = 0; + + + // Iterate from 0 to arr.length + + for (int i = 0; i < N - 1; i++) + + { + + + // Iterate from i + 1 to arr.length + + for (int j = i + 1; j < N; j++) + + { + + + // Store curr_sum = arr[i] + arr[j] + + int curr_sum = arr[i] + arr[j]; + + + // Check if X - curr_sum if present + + // in map + + if (Map.find(X - curr_sum) != Map.end()) + + { + + + // Store pair having map value + + // X - curr_sum + + pair p = Map[X - curr_sum]; + + + if (p.first != i && p.second != i + + && p.first != j && p.second != j + + && temp[p.first] == 0 + + && temp[p.second] == 0 && temp[i] == 0 + + && temp[j] == 0) + + { + + + // Print the output + + cout << arr[i] << "," << arr[j] << + + "," << arr[p.first] << "," << arr[p.second]; + + temp[p.second] = 1; + + temp[i] = 1; + + temp[j] = 1; + + break; + + } + + } + + } + + } +} + +// Program for two Sum + +map> twoSum(int nums[], int N) +{ + + map> Map; + + for (int i = 0; i < N - 1; i++) + + { + + for (int j = i + 1; j < N; j++) + + { + + Map[nums[i] + nums[j]].first = i; + + Map[nums[i] + nums[j]].second = j; + + } + + } + + return Map; +} + +// Driver code + +int main() +{ + + int arr[] = { 10, 20, 30, 40, 1, 2 }; + + int n = sizeof(arr) / sizeof(arr[0]); + + int X = 91; + + map> Map = twoSum(arr, n); + + + + // Function call + + fourSum(X, arr, Map, n); + + + return 0; +} diff --git a/CPP/Bike helmet tilt.dev b/CPP/Bike helmet tilt.dev new file mode 100644 index 0000000..c6a18be --- /dev/null +++ b/CPP/Bike helmet tilt.dev @@ -0,0 +1,51 @@ +[Project] +filename=Bike helmet tilt.dev +name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=1 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + diff --git a/CPP/FractionalKnapsack.cpp b/CPP/FractionalKnapsack.cpp new file mode 100644 index 0000000..b010496 --- /dev/null +++ b/CPP/FractionalKnapsack.cpp @@ -0,0 +1,87 @@ +// C++ program to solve fractional Knapsack Problem +#include + +using namespace std; + +// Structure for an item which stores weight & corresponding value of Item +struct Item { + int value, weight; + + // Constructor + Item(int value, int weight) + : value(value), weight(weight) + { + } +}; + +// Comparison function to sort Item according to val/weight ratio +bool cmp(struct Item a, struct Item b) +{ + double r1 = (double)a.value / a.weight; + double r2 = (double)b.value / b.weight; + return r1 > r2; +} + +// Main greedy function to solve problem +double fractionalKnapsack(struct Item arr[], + int N, int size) +{ + // Sort Item on basis of ratio + sort(arr, arr + size, cmp); + + // Current weight in knapsack + int curWeight = 0; + + // Result (value in Knapsack) + double finalvalue = 0.0; + + // Looping through all Items + for (int i = 0; i < size; i++) { + + // If adding Item won't overflow, + // add it completely + if (curWeight + arr[i].weight <= N) { + curWeight += arr[i].weight; + finalvalue += arr[i].value; + } + + // If we can't add current Item, + // add fractional part of it + else { + int remain = N - curWeight; + finalvalue += arr[i].value + * ((double)remain + / arr[i].weight); + + break; + } + } + + // Returning final value + return finalvalue; +} + +// Driver Code +int main() +{ + // Weight of knapsack + int N = 60; + + // Given weights and values as a pairs + Item arr[] = { { 100, 10 }, + { 280, 40 }, + { 120, 20 }, + { 120, 24 } }; + + int size = sizeof(arr) / sizeof(arr[0]); + + // Function Call + cout << "Maximum profit earned = " + << fractionalKnapsack(arr, N, size); + return 0; +} + + +Output: +Maximum profit earned = 440 + diff --git a/Hanoi Algorithm b/CPP/Hanoi Algorithm similarity index 100% rename from Hanoi Algorithm rename to CPP/Hanoi Algorithm diff --git a/CPP/Kadane.cpp b/CPP/Kadane.cpp new file mode 100644 index 0000000..1da78fd --- /dev/null +++ b/CPP/Kadane.cpp @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +// Driver Code +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + + // Function Call + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} diff --git a/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp b/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp new file mode 100644 index 0000000..63965e1 --- /dev/null +++ b/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp @@ -0,0 +1,40 @@ +/* Dynamic Programming C/C++ implementation of LIS problem */ +#include +#include + +/* lis() returns the length of the longest increasing + subsequence in arr[] of size n */ +int lis(int arr[], int n) +{ + int *lis, i, j, max = 0; + lis = (int*)malloc(sizeof(int) * n); + + /* Initialize LIS values for all indexes */ + for (i = 0; i < n; i++) + lis[i] = 1; + + /* Compute optimized LIS values in bottom up manner */ + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + + /* Pick maximum of all LIS values */ + for (i = 0; i < n; i++) + if (max < lis[i]) + max = lis[i]; + + /* Free memory to avoid memory leak */ + free(lis); + + return max; +} + +/* Driver program to test above function */ +int main() +{ + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; + int n = sizeof(arr) / sizeof(arr[0]); + printf("Length of lis is %d\n", lis(arr, n)); + return 0; +} diff --git a/CPP/Quick_Sort.cpp b/CPP/Quick_Sort.cpp new file mode 100644 index 0000000..5e164a4 --- /dev/null +++ b/CPP/Quick_Sort.cpp @@ -0,0 +1,83 @@ +// Quick Sort + +# include +using namespace std; + + +// Function to swap elements of array +void swap(int arr[], int a, int b) +{ + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + return; +} + + +// Function to partition around pivot, i.e, separate smaller and greater numbers into two arrays +// and return correct index of pivot +int partition(int arr[], int l, int r) +{ + // select pivot element, here, last element of array + int pivot = arr[r]; + // i = points to last number in array less than pivot + int i = l-1; + + // traverse array from l'th to r-1'th element + for (int j=l; j> n; + + int arr[n]; + cout << "\nEnter numbers to be sorted : " << endl; + for (int i=0; i> arr[i]; + } + + // Perform Quick Sort + quick_sort(arr, 0, n-1); + + // Output Sorted array + cout << "\nSorted Numbers : " << endl; + for (int i=0; i +using namespace std; + +// Standard Binary Search function +int binarySearch(int arr[], int low, int high, int key) +{ + if (high < low) + return -1; + + int mid = (low + high) / 2; + if (key == arr[mid]) + return mid; + + if (key > arr[mid]) + return binarySearch(arr, (mid + 1), high, key); + + return binarySearch(arr, low, (mid - 1), key); +} + +// Function to get pivot. For array 3, 4, 5, 6, 1, 2 +// it returns 3 (index of 6) +int findPivot(int arr[], int low, int high) +{ + // Base cases + if (high < low) + return -1; + if (high == low) + return low; + + // low + (high - low)/2; + int mid = (low + high) / 2; + if (mid < high && arr[mid] > arr[mid + 1]) + return mid; + + if (mid > low && arr[mid] < arr[mid - 1]) + return (mid - 1); + + if (arr[low] >= arr[mid]) + return findPivot(arr, low, mid - 1); + + return findPivot(arr, mid + 1, high); +} + +// Searches an element key in a pivoted +// sorted array arr[] of size n +int pivotedBinarySearch(int arr[], int n, int key) +{ + int pivot = findPivot(arr, 0, n - 1); + + // If we didn't find a pivot, + // then array is not rotated at all + if (pivot == -1) + return binarySearch(arr, 0, n - 1, key); + + // If we found a pivot, then first compare with pivot + // and then search in two subarrays around pivot + if (arr[pivot] == key) + return pivot; + + if (arr[0] <= key) + return binarySearch(arr, 0, pivot - 1, key); + + return binarySearch(arr, pivot + 1, n - 1, key); +} + +// Driver program to check above functions +int main() +{ + // Let us search 3 in below array + int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; + int n = sizeof(arr1) / sizeof(arr1[0]); + int key = 3; + + // Function calling + cout << "Index of the element is : " + << pivotedBinarySearch(arr1, n, key); + + return 0; +} diff --git a/CPP/Sieve_algorithm.cpp b/CPP/Sieve_algorithm.cpp new file mode 100644 index 0000000..aa44478 --- /dev/null +++ b/CPP/Sieve_algorithm.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +#define pb push_back +typedef long long ll; +typedef unsigned long int ull; + +int main() +{ + int n = 1e5 + 10; + vector cp(n, true); + cp[0] = cp[1] = false; + + for (int i = 2; i < n; i++) + { + if (cp[i]) + { + for (int j = i * 2; j < n; j += i) + { + cp[j] = false; + } + } + } + + int num; + cin >> num; + + if (cp[num]) + cout << "prime"; + else if(!cp[num]) + cout << "not prime"; +} \ No newline at end of file diff --git a/CPP/Single-Linked-List/readme.md b/CPP/Single-Linked-List/readme.md new file mode 100644 index 0000000..ce95b8f --- /dev/null +++ b/CPP/Single-Linked-List/readme.md @@ -0,0 +1,42 @@ +**Single Linked List** + + +**Single linked list is a sequence of elements in which every element has link to its next element in the sequence.** + +In any single linked list, the individual element is called as "Node". Every "Node" contains two fields, data field, and the next field. The data field is used to store actual value of the node and next field is used to store the address of next node in the sequence. + +The graphical representation of a node in a single linked list is as follows... + +![alt text](http://www.btechsmartclass.com/data_structures/ds_images/Linked_List_Node.png) + +**Example** + +![alt text](http://www.btechsmartclass.com/data_structures/ds_images/Linked_List_Example.png) + +**Operations on Single Linked List** + +The following operations are performed on a Single Linked List + +**1.Insertion** + +**2.Deletion** + +**3.Display** + +Before we implement actual operations, first we need to set up an empty list. First, perform the following steps before implementing actual operations. + +Step 1 - Include all the header files which are used in the program. + +Step 2 - Declare all the user defined functions. + +Step 3 - Define a Node structure with two members data and next + +Step 4 - Define a Node pointer 'head' and set it to NULL. + +Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main method to perform user selected operation. + +**Output** + + +![image](https://user-images.githubusercontent.com/103835667/193409700-2bb264c0-022a-4fe3-8acc-99853bc4ade9.png) + diff --git a/CPP/Single-Linked-List/singlelinkedlist.cpp b/CPP/Single-Linked-List/singlelinkedlist.cpp new file mode 100644 index 0000000..739d1a4 --- /dev/null +++ b/CPP/Single-Linked-List/singlelinkedlist.cpp @@ -0,0 +1,174 @@ +#include +using namespace std; + +// Node class to represent +// a node of the linked list. +class Node { +public: + int data; + Node* next; + + // Default constructor + Node() + { + data = 0; + next = NULL; + } + + // Parameterised Constructor + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +// Linked list class to +// implement a linked list. +class Linkedlist { + Node* head; + +public: + // Default constructor + Linkedlist() { head = NULL; } + + // Function to insert a + // node at the end of the + // linked list. + void insertNode(int); + + // Function to print the + // linked list. + void printList(); + + // Function to delete the + // node at given position + void deleteNode(int); +}; + +// Function to delete the +// node at given position +void Linkedlist::deleteNode(int nodeOffset) +{ + Node *temp1 = head, *temp2 = NULL; + int ListLen = 0; + + if (head == NULL) { + cout << "List empty." << endl; + return; + } + + // Find length of the linked-list. + while (temp1 != NULL) { + temp1 = temp1->next; + ListLen++; + } + + // Check if the position to be + // deleted is less than the length + // of the linked list. + if (ListLen < nodeOffset) { + cout << "Index out of range" + << endl; + return; + } + + // Declare temp1 + temp1 = head; + + // Deleting the head. + if (nodeOffset == 1) { + + // Update head + head = head->next; + delete temp1; + return; + } + + // Traverse the list to + // find the node to be deleted. + while (nodeOffset-- > 1) { + + // Update temp2 + temp2 = temp1; + + // Update temp1 + temp1 = temp1->next; + } + + // Change the next pointer + // of the previous node. + temp2->next = temp1->next; + + // Delete the node + delete temp1; +} + +// Function to insert a new node. +void Linkedlist::insertNode(int data) +{ + // Create the new Node. + Node* newNode = new Node(data); + + // Assign to head + if (head == NULL) { + head = newNode; + return; + } + + // Traverse till end of list + Node* temp = head; + while (temp->next != NULL) { + + // Update temp + temp = temp->next; + } + + // Insert at the last. + temp->next = newNode; +} + +// Function to print the +// nodes of the linked list. +void Linkedlist::printList() +{ + Node* temp = head; + + // Check for empty list. + if (head == NULL) { + cout << "List empty" << endl; + return; + } + + // Traverse the list. + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } +} + +// Driver Code +int main() +{ + Linkedlist list; + + // Inserting nodes + list.insertNode(1); + list.insertNode(2); + list.insertNode(3); + list.insertNode(4); + + cout << "Elements of the list are: "; + + // Print the list + list.printList(); + cout << endl; + + // Delete node at position 2. + list.deleteNode(2); + + cout << "Elements of the list are: "; + list.printList(); + cout << endl; + return 0; +} diff --git a/CPP/Student DBMS.cpp b/CPP/Student DBMS.cpp new file mode 100644 index 0000000..495fd12 --- /dev/null +++ b/CPP/Student DBMS.cpp @@ -0,0 +1,4144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + My-caption-Cpp/Student DBMS.cpp at main · Ankit-gurjar/My-caption-Cpp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Skip to content + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+ + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ +
+ + + + Ankit-gurjar  /   + My-caption-Cpp  /   + +
+
+ + + +
+ + +
+
+ Clear Command Palette +
+
+ + + +
+
+ Tip: + Type # to search pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search discussions +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type ! to search projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search teams +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search people and organizations +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type > to activate command mode +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Go to your accessibility settings to change your keyboard shortcuts +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type author:@me to search your content +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:pr to filter to pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:issue to filter to issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:project to filter to projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:open to filter to open content +
+
+ Type ? for help and tips +
+
+
+ +
+ +
+
+ We’ve encountered an error and some results aren't available at this time. Type a new search or try again later. +
+
+ + No results matched your search + + + + + + + + + + +
+ + + + + Search for issues and pull requests + + # + + + + Search for issues, pull requests, discussions, and projects + + # + + + + Search for organizations, repositories, and users + + @ + + + + Search for projects + + ! + + + + Search for files + + / + + + + Activate command mode + + > + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Filter to pull requests + + # is:pr + + + + Filter to issues + + # is:issue + + + + Filter to discussions + + # is:discussion + + + + Filter to projects + + # is:project + + + + Filter to open issues, pull requests, and discussions + + # is:open + + + + + + + + + + + + + + + + +
+
+
+ +
+ + + + + + + + + + +
+ + +
+
+
+ + + + + + + + + +
+ +
+ +
+ +
+ + + + / + + My-caption-Cpp + + + Public +
+ + +
+ +
    + +
  • +
    +
    +
    +
  • + + +
  • + +
    + + + + + Unwatch + + + + + 1 + + + +
    +
    +

    Notifications

    + +
    + +
    +
    + + + + + + + + +
    + + +
    + + + + + Get push notifications on iOS or Android. + +
    +
    +
    +
    + + + + +
    +
    +
    + + + +
  • + +
  • +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
  • + +
  • + + +
    +
    + + +
    +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
    +
  • + + + +
+ +
+ +
+
+ + + + +
+ + + + + +
+ Open in github.dev + Open in a new github.dev tab + + + + + + +
+ + +
+ + + + + + + + +Permalink + +
+ +
+
+ + + main + + + + +
+
+
+ Switch branches/tags + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + + + + + + + + + + + +
+ + +
+
+
+
+ +
+ +
+ + + Go to file + +
+ + + + +
+
+
+ + + + + + + + + +
+ +
+
+ + + + +
+ + Latest commit + ff210a6 + Oct 24, 2021 + + + + + + History + + +
+
+ +
+ +
+
+ + + 1 + + contributor + + +
+ +

+ Users who have contributed to this file +

+
+ + + + + + +
+
+
+
+ + + + + + + + + + + + + +
+ +
+ + +
+ + 286 lines (245 sloc) + + 6.34 KB +
+ +
+ + + + +
+ +
+
+
+
+ +
+ +
+
+
+ + + +
+ + + + + + + + + +
+ + +
+ +
+
+ +
+ +
+
+ + + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
// Include all the necessary libraries.
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
+
using namespace std;
+
int main()
{
// Considering the max length of data entered (name) to
// be 15.
char data[15];
int n = 0, option = 0, count_n = 0;
// This is the initial mark alloted to a subject.
string empty = "00";
string proctor = "";
// Name of the file in which DB is stored.
ifstream f("Example.txt");
string line;
+
// The following for loop counts the total number of
// lines in the file.
for (int i = 0; std::getline(f, line); ++i) {
count_n++;
}
+
while (option != 6) {
// This prints out all the available options in the
// DB
cout << "\nAvailable operations: \n1. Add New "
"Students\n2."
<< "Student Login\n3. Faculty Login\n4. "
"Proctor Login\n5. Admin View\n"
<< "6. Exit\nEnter option: ";
cin >> option;
+
if (option == 1) {
cout << "Enter the number of students: ";
cin >> n;
+
count_n = count_n + n;
+
for (int i = 0; i < n; i++) {
ofstream outfile;
outfile.open("Example.txt", ios::app);
// The entire data of a single student is
// stored line-by-line.
cout << "Enter your registration number: ";
cin >> data;
outfile << data << "\t";
+
cout << "Enter your name: ";
cin >> data;
int len = strlen(data);
+
while (len < 15) {
data[len] = ' ';
len = len + 1;
}
outfile << data << "\t";
// Inserting empty data initially into the
// file
outfile << empty << "\t";
outfile << empty << "\t";
+
cout << "Enter your proctor ID: ";
cin >> proctor;
+
outfile << proctor << endl;
}
}
+
else if (option == 2) {
char regno[9];
cout << "Enter your registration number: ";
cin >> regno;
ifstream infile;
int check = 0;
infile.open("Example.txt", ios::in);
+
// This loop prints out the data according to
// the registration number specified.
while (infile >> data) {
if (strcmp(data, regno) == 0) {
cout
<< "\nRegistration Number: " << data
<< endl;
infile >> data;
cout << "Name: " << data << endl;
+
infile >> data;
cout << "CSE1001 mark: " << data
<< endl;
+
infile >> data;
cout << "CSE1002 mark: " << data
<< endl;
+
infile >> data;
cout << "Proctor ID: " << data << endl;
+
infile.close();
check = 1;
}
}
+
if (check == 0) {
cout << "No such registration number found!"
<< endl;
}
}
+
// This loop is used to view and add marks to the
// database of a student.
else if (option == 3) {
char subcode[7];
cout << "Enter your subject code: ";
cin >> subcode;
string code1 = "CSE1001", code2 = "CSE1002",
mark = "";
ifstream infile;
int check = 0;
+
cout << "\nAvailable operations: \n1. Add data "
"about marks\n"
<< "2. View data\nEnter option: ";
cin >> option;
+
if (option == 1) {
cout
<< "Warning! You would need to add mark"
<< "details for all the students!"
<< endl;
for (int i = 0; i < count_n; i++) {
fstream file("Example.txt");
+
// The seek in file has been done
// according to the length
// of the data being inserted. It needs
// to adjusted accordingly for diffferent
// lengths of data.
+
if (strcmp(subcode, code1.c_str())
== 0) {
file.seekp(26 + 37 * i,
std::ios_base::beg);
cout << "Enter the mark of student#"
<< (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
+
if (strcmp(subcode, code2.c_str())
== 0) {
file.seekp(29 + 37 * i,
std::ios_base::beg);
cout << "Enter the mark of student#"
<< (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
}
}
+
// This loop is used to view marks of a student.
// The extra infile commands have been used to
// get a specific mark only since the data has
// been seperated by a tabspace.
+
else if (option == 2) {
infile.open("Example.txt", ios::in);
if (strcmp(subcode, code1.c_str()) == 0) {
cout << "Registration number - Marks\n"
<< endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
infile >> data;
check = 1;
}
}
+
infile.close();
infile.open("Example.txt", ios::in);
+
if (strcmp(subcode, code2.c_str()) == 0) {
cout << "Registration number - Marks\n"
<< endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
check = 1;
}
}
}
+
infile.close();
+
if (check == 0) {
cout << "No such subject code found!"
<< endl;
}
}
+
// This loop displays all the details of students
// under the same proctor ID.
+
else if (option == 4) {
char procid[7];
cout << "Enter your proctor ID: ";
cin >> procid;
int check = 0;
char temp1[100], temp2[100], temp3[100];
char temp4[100], id[100];
ifstream infile;
infile.open("Example.txt", ios::in);
+
while (infile >> temp1) {
infile >> temp2;
infile >> temp3;
infile >> temp4;
infile >> id;
+
if (strcmp(id, procid) == 0) {
cout << "\nRegistration Number: "
<< temp1 << endl;
cout << "Name: " << temp2 << endl;
cout << "CSE1001 Mark: " << temp3
<< endl;
cout << "CSE1002 Mark: " << temp4
<< endl;
check = 1;
}
}
+
if (check == 0) {
cout << "No such proctor ID found!" << endl;
}
}
+
// This loop acts as an admin view to see all the
// data in the file.
+
else if (option == 5) {
char password[25];
cout << "Enter the admin password: ";
cin >> password;
+
// This variable value can be changed according
// to your requirement of the administrator
// password.
+
string admin_pass = "admin";
+
if (strcmp(password, admin_pass.c_str()) == 0) {
cout << "Reg No. "
"\tName\tCSE1001\tCSE1002\tProctor "
"ID"
<< endl;
ifstream infile;
infile.open("Example.txt", ios::in);
char data[20];
+
while (infile >> data) {
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << endl;
}
}
}
}
}
+
+ + + +
+ +
+ + + + +
+ + +
+ + +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/CPP/Subarray sum equal to k.cpp b/CPP/Subarray sum equal to k.cpp new file mode 100644 index 0000000..6c7a9ea --- /dev/null +++ b/CPP/Subarray sum equal to k.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int subarraySum(vector& nums, int k) { + unordered_map mp; + int sum=0; + int ans =0 ; + for(int i=0;i + +using namespace std; + +#define N 9 + +void print(int arr[N][N]) +{ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + cout << arr[i][j] << " "; + cout << endl; + } +} + +bool isSafe(int grid[N][N], int row, + int col, int num) +{ + + for (int x = 0; x <= 8; x++) + if (grid[row][x] == num) + return false; + for (int x = 0; x <= 8; x++) + if (grid[x][col] == num) + return false; + int startRow = row - row % 3, + startCol = col - col % 3; + + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + if (grid[i + startRow][j + + startCol] == num) + return false; + + return true; +} + +bool solveSudoku(int grid[N][N], int row, int col) +{ + if (row == N - 1 && col == N) + return true; + if (col == N) { + row++; + col = 0; + } + if (grid[row][col] > 0) + return solveSudoku(grid, row, col + 1); + + for (int num = 1; num <= N; num++) + { + if (isSafe(grid, row, col, num)) + { + grid[row][col] = num; + + if (solveSudoku(grid, row, col + 1)) + return true; + } + grid[row][col] = 0; + } + return false; +} + +int main() +{ + int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; + + if (solveSudoku(grid, 0, 0)) + print(grid); + else + cout << "no solution exists " << endl; + + return 0; +} diff --git a/CPP/Transpose_of_Matrix.cpp b/CPP/Transpose_of_Matrix.cpp new file mode 100644 index 0000000..c067c73 --- /dev/null +++ b/CPP/Transpose_of_Matrix.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +int main() { + int a[10][10], transpose[10][10], row, column, i, j; + + cout << "Enter rows and columns of matrix: "; + cin >> row >> column; + + cout << "\nEnter elements of matrix: " << endl; + + // Storing matrix elements + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << "Enter element a" << i + 1 << j + 1 << ": "; + cin >> a[i][j]; + } + } + + // Printing the a matrix + cout << "\nEntered Matrix: " << endl; + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << " " << a[i][j]; + if (j == column - 1) + cout << endl << endl; + } + } diff --git a/CPP/activity_selection.cpp b/CPP/activity_selection.cpp new file mode 100644 index 0000000..66b0239 --- /dev/null +++ b/CPP/activity_selection.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; +struct Activity{ + int start,finish; +}; +bool ActivityCompare(Activity s1, Activity s2){ + return (s1.finish < s2.finish); +} +void printMaxActivities(Activity arr[],int n){ + sort(arr, arr+n, ActivityCompare); + + cout << "Following activities are selected n"; + + int i = 0; + cout << "(" << arr[i].start << ", " << arr[i].finish << "), "; + + for (int j = 1; j < n; j++) + { + if (arr[j].start >= arr[i].finish) + { + cout << "(" << arr[j].start << ", " + << arr[j].finish << "), "; + i = j; + } + } +} +int main(){ + Activity arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},{5, 7}, {8, 9}}; + int n = sizeof(arr)/sizeof(arr[0]); + printMaxActivities(arr, n); + return 0; +} \ No newline at end of file diff --git a/CPP/basic-string.cpp b/CPP/basic-string.cpp new file mode 100644 index 0000000..652d402 --- /dev/null +++ b/CPP/basic-string.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +int main() +{ + string str; + cout << "enter string"<> str; + string str_rev; + for (int i = str.size() - 1; i >= 0; i--) + { + str_rev.push_back(str[i]); + } + cout< +using namespace std; + +// defining the number of vertices +#define nV 4 + +#define INF 999 + +void printMatrix(int matrix[][nV]); + +// Implementing floyd warshall algorithm +void floydWarshall(int graph[][nV]) { + int matrix[nV][nV], i, j, k; + + for (i = 0; i < nV; i++) + for (j = 0; j < nV; j++) + matrix[i][j] = graph[i][j]; + + // Adding vertices individually + for (k = 0; k < nV; k++) { + for (i = 0; i < nV; i++) { + for (j = 0; j < nV; j++) { + if (matrix[i][k] + matrix[k][j] < matrix[i][j]) + matrix[i][j] = matrix[i][k] + matrix[k][j]; + } + } + } + printMatrix(matrix); +} + +void printMatrix(int matrix[][nV]) { + for (int i = 0; i < nV; i++) { + for (int j = 0; j < nV; j++) { + if (matrix[i][j] == INF) + printf("%4s", "INF"); + else + printf("%4d", matrix[i][j]); + } + printf("\n"); + } +} + +int main() { + int graph[nV][nV] = {{0, 3, INF, 5}, + {2, 0, INF, 4}, + {INF, 1, 0, INF}, + {INF, INF, 2, 0}}; + floydWarshall(graph); +} \ No newline at end of file diff --git a/CPP/hashing.cpp b/CPP/hashing.cpp new file mode 100644 index 0000000..4ff2033 --- /dev/null +++ b/CPP/hashing.cpp @@ -0,0 +1,135 @@ +#include +#include +#include +#include + +#define SIZE 20 + +struct DataItem { + int data; + int key; +}; + +struct DataItem* hashArray[SIZE]; +struct DataItem* dummyItem; +struct DataItem* item; + +int hashCode(int key) { + return key % SIZE; +} + +struct DataItem *search(int key) { + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) + return hashArray[hashIndex]; + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void insert(int key,int data) { + + struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); + item->data = data; + item->key = key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty or deleted cell + while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + hashArray[hashIndex] = item; +} + +struct DataItem* delete(struct DataItem* item) { + int key = item->key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) { + struct DataItem* temp = hashArray[hashIndex]; + + //assign a dummy item at deleted position + hashArray[hashIndex] = dummyItem; + return temp; + } + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void display() { + int i = 0; + + for(i = 0; ikey,hashArray[i]->data); + else + printf(" ~~ "); + } + + printf("\n"); +} + +int main() { + dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); + dummyItem->data = -1; + dummyItem->key = -1; + + insert(1, 20); + insert(2, 70); + insert(42, 80); + insert(4, 25); + insert(12, 44); + insert(14, 32); + insert(17, 11); + insert(13, 78); + insert(37, 97); + + display(); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } + + delete(item); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } +} diff --git a/CPP/infix_to_postfix.c b/CPP/infix_to_postfix.c new file mode 100644 index 0000000..8edc19d --- /dev/null +++ b/CPP/infix_to_postfix.c @@ -0,0 +1,123 @@ +#include +#define MAX 100 +char st[100]; +int top = -1; +char str[100]; +char str1[100]; + +int findchar(char ch) +{ + if (ch == '-' || ch == '+' || ch == '*' || ch == '/' || ch == '%' || ch == '^' || ch == '&') + { + return 1; + } + else + return 0; +} + +int precedence(char ch) +{ + if (ch == '^' || ch == '&') + { + return 3; + } + else if (ch == '*' || ch == '/') + { + return 2; + } + else if (ch == '+' || ch == '-') + { + return 1; + } + else if (ch == '(') + { + return -1; + } + return 0; +} + +char pop() +{ + if (top == -1) + { + return -1; + } + else + { + return st[top--]; + // top--; + } +} + +void push(char ch) +{ + // top++; + st[++top] = ch; +} + +int main() +{ + int i, j = 0, k; + printf("Enter the infix expression :\n"); + scanf("%s", str); + printf("It's postfix Expression is :\n"); + + for (i = 0; str[i] != '\0'; i++) + { + if (str[i] == '(') + { + push(str[i]); + } + else if (str[i] == ')') + { + for (k = top; st[top] != '('; k--) + { + // str1[j] = pop(); + // j++; + printf("%c", pop()); + } + pop(); + } + else if (!findchar(str[i])) + { + // str1[j] = str[i]; + // j++; + + printf("%c", str[i]); + } + else if (precedence(str[i])) + { + if (precedence(st[top]) == -1) + { + push(str[i]); + } + else if ((top != -1) && (precedence(st[top]) != -1) && precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + + if (precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + } + if (precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + } + push(str[i]); + } + + else if (precedence(str[i]) > precedence(st[top])) + { + push(str[i]); + } + } + } + + while (top >= 0) + { + printf("%c", pop()); + } + printf("\n"); + + return 0; +} diff --git a/insertion sort b/CPP/insertion sort similarity index 100% rename from insertion sort rename to CPP/insertion sort diff --git a/CPP/kadane.cpp b/CPP/kadane.cpp new file mode 100644 index 0000000..45fa5bc --- /dev/null +++ b/CPP/kadane.cpp @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} diff --git a/CPP/kadanes.cpp b/CPP/kadanes.cpp new file mode 100644 index 0000000..33cf57a --- /dev/null +++ b/CPP/kadanes.cpp @@ -0,0 +1,21 @@ +//KADANE,S ALGORITHM +#include +#define pb push_back +#define ll long long int +#define all(x) x.begin(), x.end() +using namespace std; + + int maxSubarraySum(int arr[], int n){ + + int local_max=0; + int global_max=INT_MIN; + + for(int i=0;iglobal_max) + global_max=local_max; + } + return global_max; + +} diff --git a/CPP/kruskal.cpp b/CPP/kruskal.cpp new file mode 100644 index 0000000..1672c32 --- /dev/null +++ b/CPP/kruskal.cpp @@ -0,0 +1,93 @@ +// Kruskal's algorithm in C++ + +#include +#include +#include +using namespace std; + +#define edge pair + +class Graph +{ +private: + vector > G; // graph + vector > T; // mst + int *parent; + int V; // number of vertices/nodes in graph +public: + Graph(int V){ + parent = new int[V]; + + // i 0 1 2 3 4 5 + // parent[i] 0 1 2 3 4 5 + for (int i = 0; i < V; i++) + parent[i] = i; + + G.clear(); + T.clear(); +} + void AddWeightedEdge(int u, int v, int w){ + G.push_back(make_pair(w, edge(u, v))); +} + int find_set(int i){ + // If i is the parent of itself + if (i == parent[i]) + return i; + else + return find_set(parent[i]); +} + void union_set(int u, int v){ + parent[u] = parent[v]; +} + void kruskal(){ + int i, uRep, vRep; + sort(G.begin(), G.end()); // increasing weight + for (i = 0; i < G.size(); i++) + { + uRep = find_set(G[i].second.first); + vRep = find_set(G[i].second.second); + if (uRep != vRep) + { + T.push_back(G[i]); // add to tree + union_set(uRep, vRep); + } + } +} + void print(){ + cout << "Edge :" + << " Weight" << endl; + for (int i = 0; i < T.size(); i++) + { + cout << T[i].second.first << " - " << T[i].second.second << " : " + << T[i].first; + cout << endl; + } +} +}; + + +int main() +{ + Graph g(6); + + g.AddWeightedEdge(0, 1, 4); + g.AddWeightedEdge(0, 2, 4); + g.AddWeightedEdge(1, 2, 2); + g.AddWeightedEdge(1, 0, 4); + g.AddWeightedEdge(2, 0, 4); + g.AddWeightedEdge(2, 1, 2); + g.AddWeightedEdge(2, 3, 3); + g.AddWeightedEdge(2, 5, 2); + g.AddWeightedEdge(2, 4, 4); + g.AddWeightedEdge(3, 2, 3); + g.AddWeightedEdge(3, 4, 3); + g.AddWeightedEdge(4, 2, 4); + g.AddWeightedEdge(4, 3, 3); + g.AddWeightedEdge(5, 2, 2); + g.AddWeightedEdge(5, 4, 3); + + g.kruskal(); + + g.print(); + return 0; +} \ No newline at end of file diff --git a/linear search b/CPP/linear search similarity index 100% rename from linear search rename to CPP/linear search diff --git a/link list insertion operations b/CPP/link list insertion operations similarity index 100% rename from link list insertion operations rename to CPP/link list insertion operations diff --git a/CPP/linkedListCycle.cpp b/CPP/linkedListCycle.cpp new file mode 100644 index 0000000..01ce102 --- /dev/null +++ b/CPP/linkedListCycle.cpp @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if(!head || !head->next) return 0; + ListNode* fast=head, *slow=head; + while(fast && fast->next){ + fast=fast->next->next; + slow=slow->next; + + if(fast==slow) + return 1; + } + return 0; + } +}; diff --git a/CPP/maxSum.cpp b/CPP/maxSum.cpp new file mode 100644 index 0000000..770fd46 --- /dev/null +++ b/CPP/maxSum.cpp @@ -0,0 +1,34 @@ +// C++ program to maximize the sum of difference +// between consecutive elements in circular array +#include +using namespace std; + +// Return the maximum Sum of difference between +// consecutive elements. +int maxSum(int arr[], int n) +{ + int sum = 0; + + // Sorting the array. + sort(arr, arr + n); + + // Subtracting a1, a2, a3,....., a(n/2)-1, an/2 + // twice and adding a(n/2)+1, a(n/2)+2, a(n/2)+3,. + // ...., an - 1, an twice. + for (int i = 0; i < n/2; i++) + { + sum -= (2 * arr[i]); + sum += (2 * arr[n - i - 1]); + } + + return sum; +} + +// Driver Program +int main() +{ + int arr[] = { 4, 2, 1, 8 }; + int n = sizeof(arr)/sizeof(arr[0]); + cout << maxSum(arr, n) << endl; + return 0; +} diff --git a/CPP/max_subarrray.cpp b/CPP/max_subarrray.cpp new file mode 100644 index 0000000..492a355 --- /dev/null +++ b/CPP/max_subarrray.cpp @@ -0,0 +1,69 @@ +// A Divide and Conquer based program for maximum subarray +// sum problem +#include +#include + +// A utility function to find maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// A utility function to find maximum of three integers +int max(int a, int b, int c) { return max(max(a, b), c); } + +// Find the maximum possible sum in arr[] auch that arr[m] +// is part of it +int maxCrossingSum(int arr[], int l, int m, int h) +{ + // Include elements on left of mid. + int sum = 0; + int left_sum = INT_MIN; + for (int i = m; i >= l; i--) { + sum = sum + arr[i]; + if (sum > left_sum) + left_sum = sum; + } + + // Include elements on right of mid + sum = 0; + int right_sum = INT_MIN; + for (int i = m + 1; i <= h; i++) { + sum = sum + arr[i]; + if (sum > right_sum) + right_sum = sum; + } + + // Return sum of elements on left and right of mid + // returning only left_sum + right_sum will fail for + // [-2, 1] + return max(left_sum + right_sum, left_sum, right_sum); +} + +// Returns sum of maximum sum subarray in aa[l..h] +int maxSubArraySum(int arr[], int l, int h) +{ + // Base Case: Only one element + if (l == h) + return arr[l]; + + // Find middle point + int m = (l + h) / 2; + + /* Return maximum of following three possible cases + a) Maximum subarray sum in left half + b) Maximum subarray sum in right half + c) Maximum subarray sum such that the subarray + crosses the midpoint */ + return max(maxSubArraySum(arr, l, m), + maxSubArraySum(arr, m + 1, h), + maxCrossingSum(arr, l, m, h)); +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int arr[] = { 2, 3, 4, 5, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + int max_sum = maxSubArraySum(arr, 0, n - 1); + printf("Maximum contiguous sum is %d\n", max_sum); + getchar(); + return 0; +} diff --git a/Merge short algorithm b/CPP/merge-sort.cpp similarity index 100% rename from Merge short algorithm rename to CPP/merge-sort.cpp diff --git a/CPP/minimum_extraction.cpp b/CPP/minimum_extraction.cpp new file mode 100644 index 0000000..5cfd470 --- /dev/null +++ b/CPP/minimum_extraction.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +#define MAX 10000 +#define ll long long +int main() { + int tt; + cin>>tt; + while(tt--) { + ll n; + cin>>n; + ll arr[n]; + for(int i=0;i>arr[i]; + } + sort(arr,arr+n); + ll curr = 0; + ll ans = arr[0]; + for(int i=0;i=0) + curr+=arr[i]; + else + curr += arr[i]; + ans = max(ans , arr[i+1] - curr); + arr[i+1] -= curr; + } + cout< +using namespace std; + +#define ROW_1 4 +#define COL_1 4 + +#define ROW_2 4 +#define COL_2 4 + +void print(string display, vector> matrix, + int start_row, int start_column, int end_row, + int end_column) +{ + cout << endl + << display << " =>" << endl; + for (int i = start_row; i <= end_row; i++) + { + for (int j = start_column; j <= end_column; j++) + { + cout << setw(10); + cout << matrix[i][j]; + } + cout << endl; + } + cout << endl; + return; +} + +void add_matrix(vector> matrix_A, + vector> matrix_B, + vector> &matrix_C, + int split_index) +{ + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j]; +} + +vector> +multiply_matrix(vector> matrix_A, + vector> matrix_B) +{ + int col_1 = matrix_A[0].size(); + int row_1 = matrix_A.size(); + int col_2 = matrix_B[0].size(); + int row_2 = matrix_B.size(); + + if (col_1 != row_2) + { + cout << "\nError: The number of columns in Matrix " + "A must be equal to the number of rows in " + "Matrix B\n"; + return {}; + } + + vector result_matrix_row(col_2, 0); + vector> result_matrix(row_1, + result_matrix_row); + + if (col_1 == 1) + result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; + else + { + int split_index = col_1 / 2; + + vector row_vector(split_index, 0); + vector> result_matrix_00(split_index, + row_vector); + vector> result_matrix_01(split_index, + row_vector); + vector> result_matrix_10(split_index, + row_vector); + vector> result_matrix_11(split_index, + row_vector); + + vector> a00(split_index, row_vector); + vector> a01(split_index, row_vector); + vector> a10(split_index, row_vector); + vector> a11(split_index, row_vector); + vector> b00(split_index, row_vector); + vector> b01(split_index, row_vector); + vector> b10(split_index, row_vector); + vector> b11(split_index, row_vector); + + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + { + a00[i][j] = matrix_A[i][j]; + a01[i][j] = matrix_A[i][j + split_index]; + a10[i][j] = matrix_A[split_index + i][j]; + a11[i][j] = matrix_A[i + split_index] + [j + split_index]; + b00[i][j] = matrix_B[i][j]; + b01[i][j] = matrix_B[i][j + split_index]; + b10[i][j] = matrix_B[split_index + i][j]; + b11[i][j] = matrix_B[i + split_index] + [j + split_index]; + } + + add_matrix(multiply_matrix(a00, b00), + multiply_matrix(a01, b10), + result_matrix_00, split_index); + add_matrix(multiply_matrix(a00, b01), + multiply_matrix(a01, b11), + result_matrix_01, split_index); + add_matrix(multiply_matrix(a10, b00), + multiply_matrix(a11, b10), + result_matrix_10, split_index); + add_matrix(multiply_matrix(a10, b01), + multiply_matrix(a11, b11), + result_matrix_11, split_index); + + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + { + result_matrix[i][j] = result_matrix_00[i][j]; + result_matrix[i][j + split_index] = result_matrix_01[i][j]; + result_matrix[split_index + i][j] = result_matrix_10[i][j]; + result_matrix[i + split_index] + [j + split_index] = result_matrix_11[i][j]; + } + + result_matrix_00.clear(); + result_matrix_01.clear(); + result_matrix_10.clear(); + result_matrix_11.clear(); + a00.clear(); + a01.clear(); + a10.clear(); + a11.clear(); + b00.clear(); + b01.clear(); + b10.clear(); + b11.clear(); + } + return result_matrix; +} + +int main() +{ + vector> matrix_A = {{1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {2, 2, 2, 2}}; + + print("Array A", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); + + vector> matrix_B = {{1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {2, 2, 2, 2}}; + + print("Array B", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); + + vector> result_matrix( + multiply_matrix(matrix_A, matrix_B)); + + print("Result Array", result_matrix, 0, 0, ROW_1 - 1, + COL_2 - 1); +} diff --git a/CPP/nqueens.cpp b/CPP/nqueens.cpp new file mode 100644 index 0000000..35deeb3 --- /dev/null +++ b/CPP/nqueens.cpp @@ -0,0 +1,176 @@ +/* C++ program to solve N Queen Problem using + + backtracking */ +#include + +using namespace std; +#define N 4 +/* ld is an array where its indices indicate row-col+N-1 + + (N-1) is for shifting the difference to store negative + + indices */ + +int ld[30] = { 0 }; +/* rd is an array where its indices indicate row+col + + and used to check whether a queen can be placed on + + right diagonal or not*/ + +int rd[30] = { 0 }; +/*column array where its indices indicates column and + + used to check whether a queen can be placed in that + + row or not*/ + +int cl[30] = { 0 }; +/* A utility function to print solution */ + +void printSolution(int board[N][N]) +{ + + for (int i = 0; i < N; i++) { + + for (int j = 0; j < N; j++) + + cout<<" "<< board[i][j]<<" "; + + cout<= N) + + return true; + + + + /* Consider this column and try placing + + this queen in all rows one by one */ + + for (int i = 0; i < N; i++) { + + /* Check if the queen can be placed on + + board[i][col] */ + + /* A check if a queen can be placed on + + board[row][col].We just need to check + + ld[row-col+n-1] and rd[row+coln] where + + ld and rd are for left and right + + diagonal respectively*/ + + if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { + + /* Place this queen in board[i][col] */ + + board[i][col] = 1; + + ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; + + + + /* recur to place rest of the queens */ + + if (solveNQUtil(board, col + 1)) + + return true; + + + + /* If placing queen in board[i][col] + + doesn't lead to a solution, then + + remove queen from board[i][col] */ + + board[i][col] = 0; // BACKTRACK + + ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; + + } + + } + + + + /* If the queen cannot be placed in any row in + + this column col then return false */ + + return false; +} +/* This function solves the N Queen problem using + + Backtracking. It mainly uses solveNQUtil() to + + solve the problem. It returns false if queens + + cannot be placed, otherwise, return true and + + prints placement of queens in the form of 1s. + + Please note that there may be more than one + + solutions, this function prints one of the + + feasible solutions.*/ + +bool solveNQ() +{ + + int board[N][N] = { { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 } }; + + + + if (solveNQUtil(board, 0) == false) { + + cout<<"Solution does not exist"; + + return false; + + } + + + + printSolution(board); + + return true; +} + + +// driver program to test above function + +int main() +{ + + solveNQ(); + + return 0; +} diff --git a/CPP/poi_dyn_str.cpp b/CPP/poi_dyn_str.cpp new file mode 100644 index 0000000..b98eff1 --- /dev/null +++ b/CPP/poi_dyn_str.cpp @@ -0,0 +1,47 @@ +//Dynamic memory allocation for strings +#include +#include +using namespace std; +int main() +{ + char name[20]; + char *p;//char pointer + int l,i; + + cout<<"\n enter string :"; + cin>> name; + l=strlen(name); + p = new char[l+1]; //dynamic memory allocation (Base address of memory) + + for(i=0;name[i]!='\0';i++) + { + p[i]=name[i]; + //*(p+i)= name[i]; + + }//end of for + + p[i]='\0';//end of string + + cout<<"\n Copied Sring :"< +using namespace std; +#define endl "\n" +class Queue{ + private: + int front; + int rear; + char arr[4]; + + public: + Queue() { + front = -1; + rear = -1; + for (int i = 0; i < 5; i++) { + arr[i] = 0; + } + } + + bool isEmpty() { + if (front == -1 && rear == -1) + return true; + else + return false; + } + + bool isFull(){ + if(rear==4) + return true; + else + return false; + } + + void enqueue(int val){ + if(isFull()){ + cout<<"Queue Full"<> value; + s1.enqueue(value); + + cout<<"Enter second char"<> value; + s1.enqueue(value); + + cout<<"Enter third char"<> value; + s1.enqueue(value); + + cout<<"Enter fourth char"<> value; + s1.enqueue(value); + + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.dequeue(); + + return 0; +} \ No newline at end of file diff --git a/CPP/ratInAMaze.cpp b/CPP/ratInAMaze.cpp new file mode 100644 index 0000000..194a5cd --- /dev/null +++ b/CPP/ratInAMaze.cpp @@ -0,0 +1,148 @@ +// C++ program to solve Rat in a Maze problem using +// backtracking +#include + +using namespace std; +// Maze size +#define N 4 + + +bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); + +// A utility function to print solution matrix sol[N][N] + +void printSolution(int sol[N][N]) +{ + + for (int i = 0; i < N; i++) { + + for (int j = 0; j < N; j++) + + cout<<" "<= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) + + return true; + + return false; +} + +// This function solves the Maze problem using Backtracking. +// It mainly uses solveMazeUtil() to solve the problem. It +// returns false if no path is possible, otherwise return +// true and prints the path in the form of 1s. Please note +// that there may be more than one solutions, this function +// prints one of the feasible solutions. + +bool solveMaze(int maze[N][N]) +{ + + int sol[N][N] = { { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 } }; + + if (solveMazeUtil(maze, 0, 0, sol) == false) { + + cout<<"Solution doesn't exist"; + + return false; + + } + + printSolution(sol); + + return true; +} + +// A recursive utility function to solve Maze problem + +bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) +{ + + // if (x, y is goal) return true + + if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { + + sol[x][y] = 1; + + return true; + + } + + // Check if maze[x][y] is valid + + if (isSafe(maze, x, y) == true) { + + // Check if the current block is already part of + + // solution path. + + if (sol[x][y] == 1) + + return false; + + // mark x, y as part of solution path + + sol[x][y] = 1; + + /* Move forward in x direction */ + + if (solveMazeUtil(maze, x + 1, y, sol) == true) + + return true; + + // If moving in x direction doesn't give solution + + // then Move down in y direction + + if (solveMazeUtil(maze, x, y + 1, sol) == true) + + return true; + + // If none of the above movements work then + + // BACKTRACK: unmark x, y as part of solution path + + sol[x][y] = 0; + + return false; + + } + + return false; +} + +// driver program to test above function + +int main() +{ + + int maze[N][N] = { { 1, 0, 0, 0 }, + + { 1, 1, 0, 1 }, + + { 0, 1, 0, 0 }, + + { 1, 1, 1, 1 } }; + + solveMaze(maze); + + return 0; +} diff --git a/Selection sort b/CPP/selection-sort.cpp similarity index 100% rename from Selection sort rename to CPP/selection-sort.cpp diff --git a/singly link list b/CPP/singly-linked-list.cpp similarity index 100% rename from singly link list rename to CPP/singly-linked-list.cpp diff --git a/stack all operation b/CPP/stack all operation similarity index 100% rename from stack all operation rename to CPP/stack all operation diff --git a/CPP/tree.cpp b/CPP/tree.cpp new file mode 100644 index 0000000..610f2f9 --- /dev/null +++ b/CPP/tree.cpp @@ -0,0 +1,264 @@ +#include +using namespace std; + +class Node { +private: + int data; + Node *left; + Node * right; + +public: + Node(int data) { + this->data = data; + left = NULL; + right = NULL; + } + + int getData() { + return data; + } + + Node *getLeft() { + return left; + } + + Node *setLeft(Node *node) { + return left = node; + } + + Node *getRight() { + return right; + } + + Node *setRight(Node *node) { + return right = node; + } +}; + +class Tree { +private: + Node *root; +public: + Tree() { + root = NULL; + } + + Node *getRoot() { + return root; + } + + void insert(int data) { + if (root == NULL) { + root = new Node(data); + } else { + auxInsert(root, data); + } + } + + void auxInsert(Node *node, int data) { + if (data < node->getData()) { + if (node->getLeft() == NULL) { + Node *new_node = new Node(data); + node->setLeft(new_node); + } else { + auxInsert(node->getLeft(), data); + } + } else { + if (node->getRight() == NULL) { + Node *new_node = new Node(data); + node->setRight(new_node); + } else { + auxInsert(node->getRight(), data); + } + } + } + + void pre_order(Node *node) { + cout << node->getData() << " "; + if (node->getLeft() != NULL) { + pre_order(node->getLeft()); + } + if (node->getRight() != NULL) { + pre_order(node->getRight()); + } + } + + Node *findNode(Node *node, int element) { + if (node == nullptr) return nullptr; + if (node->getData() == element) return node; + + Node *nodeFound = findNode(node->getLeft(), element); + if (nodeFound != nullptr) return nodeFound; + + return findNode(node->getRight(), element); + } + + void getLeaf(Node *node) { + if (node->getLeft() == NULL && node->getRight() == NULL) { + cout << node->getData() << endl; + } else { + if (node->getLeft() != NULL) { + getLeaf(node->getLeft()); + } + if (node->getRight() != NULL) { + getLeaf(node->getRight()); + } + } + } + + void getGrade(Node *node, int element) { + Node *nodeFound = findNode(node, element); + + if (nodeFound == 0) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + if (nodeFound->getLeft() == NULL && nodeFound->getRight() == NULL ) { + cout << "Grade is 0"; + } else if (nodeFound->getLeft() != NULL && nodeFound->getRight() != NULL) { + cout << "Grade is 2"; + } else { + cout << "Grade is 1"; + } + } + } + + void getAllGrade(Node *node) { + if (node->getRight() == NULL && node->getLeft() == NULL) { + cout << node->getData() << ": 0" << endl; + } else if (node->getRight() != NULL && node->getLeft() != NULL) { + cout << node->getData() << ": 2" << endl; + if (node->getLeft() != NULL) { + getAllGrade(node->getLeft()); + } + if (node->getRight() != NULL) { + getAllGrade(node->getRight()); + } + } else { + cout << node->getData() << ": 1" << endl; + if(node->getRight() != NULL) { + getAllGrade(node->getRight()); + } else { + getAllGrade(node->getLeft()); + } + } + } + + int getNodeHeight(Node *node) { + int leftHeigt = -1; + int rightHeigt = -1; + + if(root != NULL) { + if (node->getLeft() != NULL) { + leftHeigt = getNodeHeight(node->getLeft()); + } + if (node->getRight() != NULL) { + rightHeigt = getNodeHeight(node->getRight()); + } + + return max(leftHeigt, rightHeigt) + 1; + } + return 0; + } + + int getHeight(Node *node, int element) { + Node *nodeFound = findNode(node, element); + + if (nodeFound == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + return getNodeHeight(nodeFound); + } + return 0; + } + + void getAllHeights(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + cout << node->getData() << ": " << getNodeHeight(node) << endl; + if (node->getLeft() != NULL) { + getAllHeights(node->getLeft()); + } + if (node->getRight() != NULL) { + getAllHeights(node->getRight()); + } + + } + } + + void getAncestors(Node *node, int ancestors) { + if (node == NULL) { + cout << ""; + } else { + cout << node->getData() << ": " << ancestors << endl; + + if (node->getLeft() != NULL || node->getRight() != NULL) { + getAncestors(node->getLeft(), ancestors + 1); + getAncestors(node->getRight(), ancestors + 1); + } + } + } + + void getAllDepths(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + getAncestors(node, 0); + } + } + + void getSubtree(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + pre_order(node); + } + } + + void getAllSubtrees(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + pre_order(node); + cout << endl; + if (node->getLeft()) { + getAllSubtrees(node->getLeft()); + } + if (node->getRight()) { + getAllSubtrees(node->getRight()); + } + } + } +}; + +int main() { + Tree t = Tree(); + + t.insert(10); + t.insert(8); + t.insert(9); + t.insert(12); + t.insert(11); + t.insert(14); + t.insert(20); + t.insert(13); + t.insert(7); + + cout << "a) "; + t.pre_order(t.getRoot()); + cout << endl << "b) "; + t.getLeaf(t.getRoot()); + cout << endl << "c) "; + //t.getGrade(t.getRoot(), 10); + t.getAllGrade(t.getRoot()); + cout << endl << "d) "; + t.getAllHeights(t.getRoot()); + cout << endl << "e,f) "; + //cout << t.getDepth(t.getRoot()); + t.getAllDepths(t.getRoot()); + cout << endl << "g) "; + //t.getSubtree(t.getRoot(), 14); + t.getAllSubtrees(t.getRoot()); + + return 0; +} diff --git a/CPP/wildcardmatching.cpp b/CPP/wildcardmatching.cpp new file mode 100644 index 0000000..fea93de --- /dev/null +++ b/CPP/wildcardmatching.cpp @@ -0,0 +1,86 @@ +// C++ program to implement wildcard +// pattern matching algorithm +#include +using namespace std; + +// Function that matches input str with +// given wildcard pattern +bool strmatch(char str[], char pattern[], int n, int m) +{ + // empty pattern can only match with + // empty string + if (m == 0) + return (n == 0); + + // lookup table for storing results of + // subproblems + bool lookup[n + 1][m + 1]; + + // initialize lookup table to false + memset(lookup, false, sizeof(lookup)); + + // empty pattern can match with empty string + lookup[0][0] = true; + + // Only '*' can match with empty string + for (int j = 1; j <= m; j++) + if (pattern[j - 1] == '*') + lookup[0][j] = lookup[0][j - 1]; + + // fill the table in bottom-up fashion + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + // Two cases if we see a '*' + // a) We ignore ‘*’ character and move + // to next character in the pattern, + // i.e., ‘*’ indicates an empty sequence. + // b) '*' character matches with ith + // character in input + if (pattern[j - 1] == '*') + lookup[i][j] + = lookup[i][j - 1] || lookup[i - 1][j]; + + // Current characters are considered as + // matching in two cases + // (a) current character of pattern is '?' + // (b) characters actually match + else if (pattern[j - 1] == '?' + || str[i - 1] == pattern[j - 1]) + lookup[i][j] = lookup[i - 1][j - 1]; + + // If characters don't match + else + lookup[i][j] = false; + } + } + + return lookup[n][m]; +} + +int main() +{ + char str[] = "baaabab"; + char pattern[] = "*****ba*****ab"; + // char pattern[] = "ba*****ab"; + // char pattern[] = "ba*ab"; + // char pattern[] = "a*ab"; + // char pattern[] = "a*****ab"; + // char pattern[] = "*a*****ab"; + // char pattern[] = "ba*ab****"; + // char pattern[] = "****"; + // char pattern[] = "*"; + // char pattern[] = "aa?ab"; + // char pattern[] = "b*b"; + // char pattern[] = "a*a"; + // char pattern[] = "baaabab"; + // char pattern[] = "?baaabab"; + // char pattern[] = "*baaaba*"; + + if (strmatch(str, pattern, strlen(str), + strlen(pattern))) + cout << "Yes" << endl; + else + cout << "No" << endl; + + return 0; +} diff --git a/CQueue.java b/CQueue.java new file mode 100644 index 0000000..800cdca --- /dev/null +++ b/CQueue.java @@ -0,0 +1,110 @@ +public class CQueue { + int SIZE = 5; // Size of Circular Queue + int front, rear; + int items[] = new int[SIZE]; + + CQueue() { + front = -1; + rear = -1; + } + + // Check if the queue is full + boolean isFull() { + if (front == 0 && rear == SIZE - 1) { + return true; + } + if (front == rear + 1) { + return true; + } + return false; + } + + // Check if the queue is empty + boolean isEmpty() { + if (front == -1) + return true; + else + return false; + } + + // Adding an element + void enQueue(int element) { + if (isFull()) { + System.out.println("Queue is full"); + } else { + if (front == -1) + front = 0; + rear = (rear + 1) % SIZE; + items[rear] = element; + System.out.println("Inserted " + element); + } + } + + // Removing an element + int deQueue() { + int element; + if (isEmpty()) { + System.out.println("Queue is empty"); + return (-1); + } else { + element = items[front]; + if (front == rear) { + front = -1; + rear = -1; + } /* Q has only one element, so we reset the queue after deleting it. */ + else { + front = (front + 1) % SIZE; + } + return (element); + } + } + + void display() { + /* Function to display status of Circular Queue */ + int i; + if (isEmpty()) { + System.out.println("Empty Queue"); + } else { + System.out.println("Front -> " + front); + System.out.println("Items -> "); + for (i = front; i != rear; i = (i + 1) % SIZE) + System.out.print(items[i] + " "); + System.out.println(items[i]); + System.out.println("Rear -> " + rear); + } + } + + public static void main(String[] args) { + + CQueue q = new CQueue(); + + // Fails because front = -1 + q.deQueue(); + + q.enQueue(1); + q.enQueue(2); + q.enQueue(3); + q.enQueue(4); + q.enQueue(5); + + // Fails to enqueue because front == 0 && rear == SIZE - 1 + q.enQueue(6); + + q.display(); + + int elem = q.deQueue(); + + if (elem != -1) { + System.out.println("Deleted Element is " + elem); + } + q.display(); + + q.enQueue(7); + + q.display(); + + // Fails to enqueue because front == rear + 1 + q.enQueue(8); + } + +} diff --git a/First and last occurance binary search b/First and last occurance binary search new file mode 100644 index 0000000..57770ef --- /dev/null +++ b/First and last occurance binary search @@ -0,0 +1,56 @@ +#include +using namespace std; +int firstOcc(vector& arr, int n, int key) { + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + e = mid - 1; + } + else if(key > arr[mid]) {//Right me jao + s = mid + 1; + } + else if(key < arr[mid]) {//left me jao + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +int lastOcc(vector& arr, int n, int key) { + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + s = mid + 1; + } + else if(key > arr[mid]) {//Right me jao + s = mid + 1; + } + else if(key < arr[mid]) {//left me jao + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +pair firstAndLastPosition(vector& arr, int n, int k) +{ + pair p; + p.first = firstOcc(arr, n, k); + p.second = lastOcc(arr, n, k); + + return p; +} diff --git a/Java Games/SimpleSnake.java b/Java Games/SimpleSnake.java new file mode 100644 index 0000000..babcbf8 --- /dev/null +++ b/Java Games/SimpleSnake.java @@ -0,0 +1,319 @@ +package Sb; + +import java.awt.*; +import java.awt.event.*; +import static java.lang.String.format; +import java.util.*; +import java.util.List; +import javax.swing.*; + +public class SimpleSnake extends JPanel implements Runnable { + enum Dir { + up(0, -1), right(1, 0), down(0, 1), left(-1, 0); + + Dir(int x, int y) { + this.x = x; this.y = y; + } + + final int x, y; + } + + static final Random rand = new Random(); + static final int WALL = -1; + static final int MAX_ENERGY = 1500; + + volatile boolean gameOver = true; + + Thread gameThread; + int score, hiScore; + int nRows = 44; + int nCols = 64; + Dir dir; + int energy; + + int[][] grid; + List snake, treats; + Font smallFont; + + public SimpleSnake() { + setPreferredSize(new Dimension(640, 440)); + setBackground(Color.WHITE); + setFont(new Font("TimesNewRoman", Font.BOLD, 48)); + setFocusable(true); + + smallFont = getFont().deriveFont(Font.BOLD, 18); + initGrid(); + + addMouseListener( + new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (gameOver) { + startNewGame(); + repaint(); + } + } + }); + + addKeyListener( + new KeyAdapter() { + + @Override + public void keyPressed(KeyEvent e) { + + switch (e.getKeyCode()) { + + case KeyEvent.VK_UP: + if (dir != Dir.down) + dir = Dir.up; + break; + + case KeyEvent.VK_LEFT: + if (dir != Dir.right) + dir = Dir.left; + break; + + case KeyEvent.VK_RIGHT: + if (dir != Dir.left) + dir = Dir.right; + break; + + case KeyEvent.VK_DOWN: + if (dir != Dir.up) + dir = Dir.down; + break; + } + repaint(); + } + }); + } + + void startNewGame() { + gameOver = false; + + stop(); + initGrid(); + treats = new LinkedList<>(); + + dir = Dir.left; + energy = MAX_ENERGY; + + if (score > hiScore) + hiScore = score; + score = 0; + + snake = new ArrayList<>(); + for (int x = 0; x < 7; x++) + snake.add(new Point(nCols / 2 + x, nRows / 2)); + + do + addTreat(); + while(treats.isEmpty()); + + (gameThread = new Thread(this)).start(); + } + + void stop() { + if (gameThread != null) { + Thread tmp = gameThread; + gameThread = null; + tmp.interrupt(); + } + } + + void initGrid() { + grid = new int[nRows][nCols]; + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1) + grid[r][c] = WALL; + } + } + } + + @Override + public void run() { + + while (Thread.currentThread() == gameThread) { + + try { + Thread.sleep(Math.max(75 - score, 25)); + } catch (InterruptedException e) { + return; + } + + if (energyUsed() || hitsWall() || hitsSnake()) { + gameOver(); + } else { + if (eatsTreat()) { + score++; + energy = MAX_ENERGY; + growSnake(); + } + moveSnake(); + addTreat(); + } + repaint(); + } + } + + boolean energyUsed() { + energy -= 10; + return energy <= 0; + } + + boolean hitsWall() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + return grid[nextRow][nextCol] == WALL; + } + + boolean hitsSnake() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + for (Point p : snake) + if (p.x == nextCol && p.y == nextRow) + return true; + return false; + } + + boolean eatsTreat() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + for (Point p : treats) + if (p.x == nextCol && p.y == nextRow) { + return treats.remove(p); + } + return false; + } + + void gameOver() { + gameOver = true; + stop(); + } + + void moveSnake() { + for (int i = snake.size() - 1; i > 0; i--) { + Point p1 = snake.get(i - 1); + Point p2 = snake.get(i); + p2.x = p1.x; + p2.y = p1.y; + } + Point head = snake.get(0); + head.x += dir.x; + head.y += dir.y; + } + + void growSnake() { + Point tail = snake.get(snake.size() - 1); + int x = tail.x + dir.x; + int y = tail.y + dir.y; + snake.add(new Point(x, y)); + } + + void addTreat() { + if (treats.size() < 3) { + + if (rand.nextInt(10) == 0) { // 1 in 10 + + if (rand.nextInt(4) != 0) { // 3 in 4 + int x, y; + while (true) { + + x = rand.nextInt(nCols); + y = rand.nextInt(nRows); + if (grid[y][x] != 0) + continue; + + Point p = new Point(x, y); + if (snake.contains(p) || treats.contains(p)) + continue; + + treats.add(p); + break; + } + } else if (treats.size() > 1) + treats.remove(0); + } + } + } + + void drawGrid(Graphics2D g) { + g.setColor(Color.black); + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (grid[r][c] == WALL) + g.fillRect(c * 10, r * 10, 10, 10); + } + } + } + + void drawSnake(Graphics2D g) { + g.setColor(Color.red); + for (Point p : snake) + g.fillRect(p.x * 10, p.y * 10, 10, 10); + + g.setColor(energy < 500 ? Color.red : Color.orange); + Point head = snake.get(0); + g.fillRect(head.x * 10, head.y * 10, 10, 10); + } + + void drawTreats(Graphics2D g) { + g.setColor(Color.green); + for (Point p : treats) + g.fillRect(p.x * 10, p.y * 10, 10, 10); + } + + void drawStartScreen(Graphics2D g) { + g.setColor(Color.red); + g.setFont(getFont()); + g.drawString("SNAKE", 240, 190); + g.setColor(Color.orange); + g.setFont(smallFont); + g.drawString("(Click To START)", 250, 240); + } + + void drawScore(Graphics2D g) { + int h = getHeight(); + g.setFont(smallFont); + g.setColor(getForeground()); + String s = format("Hi-Score: %d Score: %d", hiScore, score); + g.drawString(s, 30, h - 30); + g.drawString(format("Energy: %d", energy), getWidth() - 150, h - 30); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + drawGrid(g); + + if (gameOver) { + drawStartScreen(g); + } else { + drawSnake(g); + drawTreats(g); + drawScore(g); + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater( + () -> { + JFrame mainFrame = new JFrame(); + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mainFrame.setTitle("SNAKE"); + mainFrame.setResizable(true); + mainFrame.add(new SimpleSnake(), BorderLayout.CENTER); + mainFrame.pack(); + mainFrame.setLocationRelativeTo(null); + mainFrame.setVisible(true); + }); + } +} diff --git a/AreaOfCircle.java b/Java/AreaOfCircle.java similarity index 100% rename from AreaOfCircle.java rename to Java/AreaOfCircle.java diff --git a/BMI.java b/Java/BMI.java similarity index 100% rename from BMI.java rename to Java/BMI.java diff --git a/Java/BinarySearch.java b/Java/BinarySearch.java new file mode 100644 index 0000000..eeffdf1 --- /dev/null +++ b/Java/BinarySearch.java @@ -0,0 +1,65 @@ +import java.util.Scanner; + +/* + * Java Program to implement binary search without using recursion + */ +public class BinarySearch { + + public static void main(String[] args) { + + Scanner commandReader = new Scanner(System.in); + System.out.println("Welcome to Java Program to perform + binary search on int array"); + System.out.println("Enter total number of elements : "); + int length = commandReader.nextInt(); + int[] input = new int[length]; + + System.out.printf("Enter %d integers %n", length); + for (int i = 0; i < length; i++) { + input[i] = commandReader.nextInt(); + } + + System.out.println("Please enter number to be searched in array + (sorted order)"); + int key = commandReader.nextInt(); + + int index = performBinarySearch(input, key); + + if (index == -1) { + System.out.printf("Sorry, %d is not found in array %n", key); + } else { + System.out.printf("%d is found in array at index %d %n", key, + index); + } + + commandReader.close(); + + } + + /** + * Java method to perform binary search. It accept an integer array and a + * number and return the index of number in the array. If number doesn't + * exists in array then it return -1 + * + * @param input + * @param number + * @return index of given number in array or -1 if not found + */ + public static int performBinarySearch(int[] input, int number) { + int low = 0; + int high = input.length - 1; + + while (high >= low) { + int middle = (low + high) / 2; + if (input[middle] == number) { + return middle; + } else if (input[middle] < number) { + low = middle + 1; + } else if (input[middle] > number) { + high = middle - 1; + } + } + return -1; + } + +} diff --git a/ConMetToFeet.java b/Java/ConMetToFeet.java similarity index 100% rename from ConMetToFeet.java rename to Java/ConMetToFeet.java diff --git a/Java/Determinant_of_Matrix.java b/Java/Determinant_of_Matrix.java new file mode 100644 index 0000000..bf856b9 --- /dev/null +++ b/Java/Determinant_of_Matrix.java @@ -0,0 +1,94 @@ +// Java program to find Determinant of a matrix +class GFG { + + // Dimension of input square matrix + static final int N = 4; + + // Function to get determinant of matrix + static int determinantOfMatrix(int mat[][], int n) + { + int num1, num2, det = 1, index, + total = 1; // Initialize result + + // temporary array for storing row + int[] temp = new int[n + 1]; + + // loop for traversing the diagonal elements + for (int i = 0; i < n; i++) { + index = i; // initialize the index + + // finding the index which has non zero value + while (mat[index][i] == 0 && index < n) { + index++; + } + if (index == n) // if there is non zero element + { + // the determinant of matrix as zero + continue; + } + if (index != i) { + // loop for swaping the diagonal element row + // and index row + for (int j = 0; j < n; j++) { + swap(mat, index, j, i, j); + } + // determinant sign changes when we shift + // rows go through determinant properties + det = (int)(det * Math.pow(-1, index - i)); + } + + // storing the values of diagonal row elements + for (int j = 0; j < n; j++) { + temp[j] = mat[i][j]; + } + + // traversing every row below the diagonal + // element + for (int j = i + 1; j < n; j++) { + num1 = temp[i]; // value of diagonal element + num2 = mat[j] + [i]; // value of next row element + + // traversing every column of row + // and multiplying to every row + for (int k = 0; k < n; k++) { + // multiplying to make the diagonal + // element and next row element equal + mat[j][k] = (num1 * mat[j][k]) + - (num2 * temp[k]); + } + total = total * num1; // Det(kA)=kDet(A); + } + } + + // multiplying the diagonal elements to get + // determinant + for (int i = 0; i < n; i++) { + det = det * mat[i][i]; + } + return (det / total); // Det(kA)/k=Det(A); + } + + static int[][] swap(int[][] arr, int i1, int j1, int i2, + int j2) + { + int temp = arr[i1][j1]; + arr[i1][j1] = arr[i2][j2]; + arr[i2][j2] = temp; + return arr; + } + + // Driver code + public static void main(String[] args) + { + int mat[][] = { { 1, 0, 2, -1 }, + { 3, 0, 0, 5 }, + { 2, 1, 4, -3 }, + { 1, 0, 5, 0 } }; + + // Function call + System.out.printf( + "Determinant of the matrix is : %d", + determinantOfMatrix(mat, N)); + } +} diff --git a/Java/LinearSearch.java b/Java/LinearSearch.java new file mode 100644 index 0000000..a6aa4b7 --- /dev/null +++ b/Java/LinearSearch.java @@ -0,0 +1,66 @@ +import javax.swing.*; + +public class BuscaLinear { + + public static void linearSearchNumber(int[] listaNum, int numDigitado) { + int i = 0; + + while(true) { + if (numDigitado == listaNum[i]) { + JOptionPane.showMessageDialog(null, "O número " + numDigitado + " está na posição: " + i); + break; + } else if(numDigitado != listaNum[i]) { + i++; + } + } + } + + + public static void linearSearchString(String[] listaString, String strDigitada) { + int i = 0; + + while(!listaString[i].equals(strDigitada)) { + i++; + } + + if(listaString[i].equals(strDigitada)) { + JOptionPane.showMessageDialog(null, "A palavra '"+ strDigitada + "' está na posição: " + i); + } + } + + + public static void main(String[] args) { + int opc; + + int[] listaNum = new int[5]; + String[] listaString = new String[5]; + Object[] options = {"Número", "String"}; + + opc = JOptionPane.showOptionDialog(null, "Escolha o tipo de lista que deseja criar:", "Busca Linear", + JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, options, options[0]); + + switch (opc){ + case 0: + + for(int i = 0; i < listaNum.length; i++) { + listaNum[i] = Integer.parseInt(JOptionPane.showInputDialog("Digite o " + (i+1) +"/5 número: ")); + } + int numDigitado = Integer.parseInt(JOptionPane.showInputDialog("Qual número deseja Buscar: ")); + + linearSearchNumber(listaNum, numDigitado); + + break; + + case 1: + + for(int i = 0; i < listaString.length; i++) { + listaString[i] = JOptionPane.showInputDialog("Digite a " + (i+1) +"/5 palavra: "); + } + String strDigitada = JOptionPane.showInputDialog("Qual palavra deseja Buscar: "); + + linearSearchString(listaString, strDigitada); + + break; + } + } +} diff --git a/Java/Main.class b/Java/Main.class new file mode 100644 index 0000000..bbba926 Binary files /dev/null and b/Java/Main.class differ diff --git a/Overidding.java b/Java/Overidding.java similarity index 100% rename from Overidding.java rename to Java/Overidding.java diff --git a/Java/QuickSortAlogorithem.java b/Java/QuickSortAlogorithem.java new file mode 100644 index 0000000..b91430b --- /dev/null +++ b/Java/QuickSortAlogorithem.java @@ -0,0 +1,73 @@ +import java.util.Arrays; + +class Quicksort { + + // method to find the partition position + static int partition(int array[], int low, int high) { + + // choose the rightmost element as pivot + int pivot = array[high]; + + // pointer for greater element + int i = (low - 1); + + // traverse through all elements + // compare each element with pivot + for (int j = low; j < high; j++) { + if (array[j] <= pivot) { + + // if element smaller than pivot is found + // swap it with the greater element pointed by i + i++; + + // swapping element at i with element at j + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + } + + // swapt the pivot element with the greater element specified by i + int temp = array[i + 1]; + array[i + 1] = array[high]; + array[high] = temp; + + // return the position from where partition is done + return (i + 1); + } + + static void quickSort(int array[], int low, int high) { + if (low < high) { + + // find pivot element such that + // elements smaller than pivot are on the left + // elements greater than pivot are on the right + int pi = partition(array, low, high); + + // recursive call on the left of pivot + quickSort(array, low, pi - 1); + + // recursive call on the right of pivot + quickSort(array, pi + 1, high); + } + } +} + +// Main class +class Main { + public static void main(String args[]) { + + int[] data = { 8, 7, 2, 1, 0, 9, 6 }; + System.out.println("Unsorted Array"); + System.out.println(Arrays.toString(data)); + + int size = data.length; + + // call quicksort() on array data + Quicksort.quickSort(data, 0, size - 1); + + System.out.println("Sorted Array in Ascending Order "); + System.out.println(Arrays.toString(data)); + } +} diff --git a/Java/RadixSort.java b/Java/RadixSort.java new file mode 100644 index 0000000..baa82a0 --- /dev/null +++ b/Java/RadixSort.java @@ -0,0 +1,66 @@ +class RadixSort { + + int getMax(int a[], int n) { + int max = a[0]; + for(int i = 1; i max) + max = a[i]; + } + return max; //maximum element from the array + } + + void countingSort(int a[], int n, int place) // function to implement counting + + sort + { + int[] output = new int[n+1]; + int[] count = new int[10]; + + // Calculate count of elements + for (int i = 0; i < n; i++) + count[(a[i] / place) % 10]++; + + // Calculate cumulative frequency + for (int i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Place the elements in sorted order + for (int i = n - 1; i >= 0; i--) { + output[count[(a[i] / place) % 10] - 1] = a[i]; + count[(a[i] / place) % 10]--; + } + + for (int i = 0; i < n; i++) + a[i] = output[i]; + } + + // function to implement radix sort + void radixsort(int a[], int n) { + + // get maximum element from array + int max = getMax(a, n); + + // Apply counting sort to sort elements based on place value + for (int place = 1; max / place > 0; place *= 10) + countingSort(a, n, place); + } + + // function to print array elements + void printArray(int a[], int n) { + for (int i = 0; i < n; ++i) + System.out.print(a[i] + " "); + } + + public static void main(String args[]) { + int a[] = {151, 259, 360, 91, 115, 706, 34, 858, 2}; + int n = a.length; + RadixSort r1 = new RadixSort(); + System.out.print("Before sorting array elements are - \n"); + r1.printArray(a,n); + r1.radixsort(a, n); + System.out.print("\n\nAfter applying Radix sort, the array elements are - + + \n"); + r1.printArray(a, n); + } + } \ No newline at end of file diff --git a/Java/SortingusingSort.java b/Java/SortingusingSort.java new file mode 100644 index 0000000..f5248c7 --- /dev/null +++ b/Java/SortingusingSort.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + + ArrayList numbers = new ArrayList<>(); + + + numbers.add(4); + numbers.add(2); + numbers.add(3); + System.out.println("Unsorted ArrayList: " + numbers); + + + Collections.sort(numbers); + System.out.println("Sorted ArrayList: " + numbers); + + } +} diff --git a/Java/algorithms.java b/Java/algorithms.java new file mode 100644 index 0000000..f98d595 --- /dev/null +++ b/Java/algorithms.java @@ -0,0 +1,35 @@ +// Java program for implementation of Bubble Sort +class BubbleSort { + void bubbleSort(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n - 1; i++) + for (int j = 0; j < n - i - 1; j++) + if (arr[j] > arr[j + 1]) { + // swap arr[j+1] and arr[j] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + + /* Prints the array */ + void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver method to test above + public static void main(String args[]) + { + BubbleSort ob = new BubbleSort(); + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + ob.bubbleSort(arr); + System.out.println("Sorted array"); + ob.printArray(arr); + } +} +/* This code is contributed by Rajat Mishra */ diff --git a/Java/bubble_sort.java b/Java/bubble_sort.java new file mode 100644 index 0000000..ae1ceaa --- /dev/null +++ b/Java/bubble_sort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/Java/bubblesort.java b/Java/bubblesort.java new file mode 100644 index 0000000..436662e --- /dev/null +++ b/Java/bubblesort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/Java/bucketsort.java b/Java/bucketsort.java new file mode 100644 index 0000000..ecd7e3a --- /dev/null +++ b/Java/bucketsort.java @@ -0,0 +1,39 @@ +import java.util.*; +public class Main +{ +public static int[] bucketsort(int[] array, int maximum_value) +{ +//creating an empty array called newbucket which is considered as bucket array +int[] newbucket = new int[maximum_value + 1]; +//creating another empty array called sorted_array to store the result array +int[] sorted_array = new int[array.length]; +//traversing through the input array to add each element to the bucket array +for (int a= 0; a maximum_value) +maximum_value = array[d]; +return maximum_value; +} +//main function is called within which we display the resulting array +public static void main(String args[]) +{ +int[] array ={100, 90, 80, 70, 60, 50, 40, 30, 20, 10}; +int maximum_value = maximumValue(array); +System.out.print("\nThe elements of the array to be sorted are:\n "); +System.out.println(Arrays.toString(array)); +System.out.print("\nThe elements of the sorted array sorted using bucket sort algorithm are:\n "); +System.out.println(Arrays.toString(bucketsort(array,maximum_value))); +} +} \ No newline at end of file diff --git a/Java/complex-string.java b/Java/complex-string.java new file mode 100644 index 0000000..690c8b0 --- /dev/null +++ b/Java/complex-string.java @@ -0,0 +1,19 @@ +public class StringComparison { + public static void main(String a[]){ + String str = "JavaTpoint is a great website to acquire knowledge"; + StringBuffer obj = + new StringBuffer("JavaTpoint is a great website to acquire knowledge"); + if(str.contentEquals(obj)){ + System.out.println("The content of the string is equal"); + } else { + System.out.println("The content of the string is not equal"); + } + StringBuffer obj1 = + new StringBuffer("It is another string"); + if(str.contentEquals(obj1)){ + System.out.println("The content of the string is equal"); + } else { + System.out.println("The content of the string is not equal"); + } + } +} diff --git a/Java/countingSort.java b/Java/countingSort.java new file mode 100644 index 0000000..6dbd2da --- /dev/null +++ b/Java/countingSort.java @@ -0,0 +1,52 @@ +// Java implementation of Counting Sort +class CountingSort { + void sort(char arr[]) + { + int n = arr.length; + + // The output character array that will have sorted arr + char output[] = new char[n]; + + // Create a count array to store count of individual + // characters and initialize count array as 0 + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + // store count of each character + for (int i = 0; i < n; ++i) + ++count[arr[i]]; + + // Change count[i] so that count[i] now contains actual + // position of this character in output array + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + // Build the output character array + // To make it stable we are operating in reverse order. + for (int i = n - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + // Driver method + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' }; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} +/*This code is contributed by Rajat Mishra */ diff --git a/Java/heapsort.java b/Java/heapsort.java new file mode 100644 index 0000000..3d31a22 --- /dev/null +++ b/Java/heapsort.java @@ -0,0 +1,74 @@ +package Sorting; + +public class heapify { + + public void sort(int a[]) + { + int n=a.length; + for(int i=(n/2)-1;i>=0;i--) + { + hepify(a,n,i); + } + for(int i=n-1;i>=0;i--) { + + int temp=a[0]; + a[0]=a[i]; + a[i]=temp; + + hepify(a,i,0); + } + } + + + + + + static void hepify(int a[],int n,int i) + { + int larest; + + int left=(2*i)+1; + int right=(2*i)+2; + + if(lefta[i]) + { + larest=left; + } + else{ + larest=i; + } + if(righta[larest]) + { + larest=right; + } + if(larest!=i) + { + int temp; + temp=a[i]; + a[i]=a[larest]; + a[larest]=temp; + + hepify(a,n,larest); + } + } + + static void display(int a[]) + { + for(int i=0;i 0 ? "Yes" : "No"); + System.out.println(capitalize(A) + " " + capitalize(B)); + } + + private static String capitalize(String word) { + return word.substring(0, 1).toUpperCase() + word.substring(1, word.length()); + } +} \ No newline at end of file diff --git a/Java/merge.java b/Java/merge.java new file mode 100644 index 0000000..0741042 --- /dev/null +++ b/Java/merge.java @@ -0,0 +1,106 @@ +// C++ program for Merge Sort +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(int array[], int const left, int const mid, + int const right) +{ + auto const subArrayOne = mid - left + 1; + auto const subArrayTwo = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArrayOne], + *rightArray = new int[subArrayTwo]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (auto i = 0; i < subArrayOne; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArrayTwo; j++) + rightArray[j] = array[mid + 1 + j]; + + auto indexOfSubArrayOne + = 0, // Initial index of first sub-array + indexOfSubArrayTwo + = 0; // Initial index of second sub-array + int indexOfMergedArray + = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (indexOfSubArrayOne < subArrayOne + && indexOfSubArrayTwo < subArrayTwo) { + if (leftArray[indexOfSubArrayOne] + <= rightArray[indexOfSubArrayTwo]) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + } + else { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + } + indexOfMergedArray++; + } + // Copy the remaining elements of + // left[], if there are any + while (indexOfSubArrayOne < subArrayOne) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + indexOfMergedArray++; + } + // Copy the remaining elements of + // right[], if there are any + while (indexOfSubArrayTwo < subArrayTwo) { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + indexOfMergedArray++; + } + delete[] leftArray; + delete[] rightArray; +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int array[], int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + auto arr_size = sizeof(arr) / sizeof(arr[0]); + + cout << "Given array is \n"; + printArray(arr, arr_size); + + mergeSort(arr, 0, arr_size - 1); + + cout << "\nSorted array is \n"; + printArray(arr, arr_size); + return 0; +} + +// This code is contributed by Mayank Tyagi +// This code was revised by Joshua Estes diff --git a/Java/mergeSort.class b/Java/mergeSort.class new file mode 100644 index 0000000..a4529d7 Binary files /dev/null and b/Java/mergeSort.class differ diff --git a/Java/mergeSort.java b/Java/mergeSort.java new file mode 100644 index 0000000..e41958d --- /dev/null +++ b/Java/mergeSort.java @@ -0,0 +1,68 @@ +import java.util.Arrays; + +class mergeSort { + + static void merge(int array[], int p, int q, int r) { + + int n1 = q - p + 1; + int n2 = r - q; + + int L[] = new int[n1]; + int M[] = new int[n2]; + + for (int i = 0; i < n1; i++) + L[i] = array[p + i]; + for (int j = 0; j < n2; j++) + M[j] = array[q + 1 + j]; + + int i, j, k; + i = 0; + j = 0; + k = p; + + while (i < n1 && j < n2) { + if (L[i] <= M[j]) { + array[k] = L[i]; + i++; + } else { + array[k] = M[j]; + j++; + } + k++; + } + + while (i < n1) { + array[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + array[k] = M[j]; + j++; + k++; + } + } + + static void mergeSort(int array[], int left, int right) { + if (left < right) { + + int mid = (left + right) / 2; + + mergeSort(array, left, mid); + mergeSort(array, mid + 1, right); + + merge(array, left, mid, right); + } + } + + public static void main(String args[]) { + + int[] array = { 5, 2, 3, 4, 1, 6 }; + + mergeSort(array, 0, array.length - 1); + + System.out.println("Sorted Array:"); + System.out.println(Arrays.toString(array)); + } +} diff --git a/Javascript/binarySearch.js b/Javascript/binarySearch.js new file mode 100644 index 0000000..b0c3a4f --- /dev/null +++ b/Javascript/binarySearch.js @@ -0,0 +1,28 @@ +let iterativeFunction = function (arr, x) { + + let start = 0 + let end = arr.length-1 + + while (start<=end){ + + let mid = Math.floor((start + end)/2); + + if (arr[mid]===x) return true; + + else if (arr[mid] < x) + start = mid + 1; + else + end = mid - 1; + } + + return false; +} + +let arr = [1, 3, 5, 7, 8, 9]; +let x = 5; + +if (iterativeFunction(arr, x)) + console.log('Element found!') +else { + console.log('Element not found!') +} diff --git a/Javascript/bubbleSort.js b/Javascript/bubbleSort.js new file mode 100644 index 0000000..76c82ba --- /dev/null +++ b/Javascript/bubbleSort.js @@ -0,0 +1,32 @@ +function bubbleSort(arr){ + + let i, j; + let len = arr.length; + + let isSwapped = false; + + for(i =0; i < len; i++){ + + isSwapped = false; + + for(j = 0; j < len; j++){ + if(arr[j] > arr[j + 1]){ + var temp = arr[j] + arr[j] = arr[j+1]; + arr[j+1] = temp; + isSwapped = true; + } + } + + if(!isSwapped){ + break; + } + } + + console.log(arr) +} + + +const arr = [243, 45, 23, 356, 3, 5346, 35, 5]; + +bubbleSort(arr) diff --git a/Javascript/getProviderName.js b/Javascript/getProviderName.js new file mode 100644 index 0000000..5b3768d --- /dev/null +++ b/Javascript/getProviderName.js @@ -0,0 +1,15 @@ +let input = 'arie@hacktober.com' +let provider = ''; + +for (let i = 0; i < input.length; i++) { + if (input[i - 1] === '@') { + for (let j = i; j < input.length; j++) { + if (input[j] === '.') { + break; + } + provider += input[j]; + } + break; + } +} +console.log(`Your email provider is ${provider}`); diff --git a/Javascript/selectionSort.js b/Javascript/selectionSort.js new file mode 100644 index 0000000..2527c73 --- /dev/null +++ b/Javascript/selectionSort.js @@ -0,0 +1,18 @@ +function selectionSort(arr) { + let min; + for (let i = 0; i < arr.length; i++) { + // Assume a minimum value + min = i; + for (let j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[min]) { + min = j; + } + } + + // Swap if new minimun value found + if (min !== i) { + [arr[i], arr[min]] = [arr[min], arr[i]]; + } + } + return arr; +} \ No newline at end of file diff --git a/Permutation in String.cpp b/Permutation in String.cpp new file mode 100644 index 0000000..22d1de0 --- /dev/null +++ b/Permutation in String.cpp @@ -0,0 +1,41 @@ +Question- + +Suppose we have two strings s1 and s2, we have to write a function to return true if s2 contains the permutation of s1. So we can say that one of the first string's permutations is the substring of the second string. + +Input- +"abc" +"findcab" +Output- +1 + + +Solution- + +#include +using namespace std; +class Solution { +public: + bool checkInclusion(string s1, string s2) { + vector cnt1(26), cnt2(26); + for(int i = 0; i < s1.size(); i++)cnt1[s1[i] - 'a']++; + int j = 0; + int required = s1.size(); + for(int i = 0; i < s2.size(); i++){ + char x = s2[i]; + cnt2[x - 'a']++; + if(cnt1[x - 'a'] && cnt2[x - 'a'] <= cnt1[x - 'a']) required--; + while(j <= i && cnt2[s2[j] - 'a'] - 1 >= cnt1[s2[j] - 'a']){ + cnt2[s2[j] - 'a']--; + j++; + } + if(i - j + 1 == s1.size() && required == 0){ + return true; + } + } + return false; + } +}; +main(){ + Solution ob; + cout << (ob.checkInclusion("abc", "findcab")); +} diff --git a/Permutations in string.cpp b/Permutations in string.cpp new file mode 100644 index 0000000..0e15f8a --- /dev/null +++ b/Permutations in string.cpp @@ -0,0 +1,43 @@ +// edited by - batrakeshav10 +/* dear sir you are doing a great job on youtube by creating videos for newbies and i am really inspired from the same. please accept my pull request so i can win a tshirt in hacktoberfest. thank you sir */ + +Question- + +Suppose we have two strings s1 and s2, we have to write a function to return true if s2 contains the permutation of s1. So we can say that one of the first string's permutations is the substring of the second string. +Input- +"abc" +"findcab" +Output- +1 +Solution- +#include +using namespace std; +class Solution { +public: + bool checkInclusion(string s1, string s2) { + vector cnt1(26), cnt2(26); + for(int i = 0; i < s1.size(); i++)cnt1[s1[i] - 'a']++; + int j = 0; + int required = s1.size(); + for(int i = 0; i < s2.size(); i++){ + char x = s2[i]; + cnt2[x - 'a']++; + if(cnt1[x - 'a'] && cnt2[x - 'a'] <= cnt1[x - 'a']) required--; + while(j <= i && cnt2[s2[j] - 'a'] - 1 >= cnt1[s2[j] - 'a']){ + cnt2[s2[j] - 'a']--; + j++; + } + if(i - j + 1 == s1.size() && required == 0){ + return true; + } + } + return false; + } +}; +main(){ + Solution ob; + cout << (ob.checkInclusion("abc", "findcab")); +} + +// edited by - batrakeshav10 +/* dear sir you are doing a great job on youtube by creating videos for newbies and i am really inspired from the same. please accept my pull request so i can win a tshirt in hacktoberfest. thank you sir */ diff --git a/Python/1_Singly_Linked_List.py b/Python/1_Singly_Linked_List.py new file mode 100644 index 0000000..7453d11 --- /dev/null +++ b/Python/1_Singly_Linked_List.py @@ -0,0 +1,98 @@ +#Node Datatype creation +from os import remove + + +class Node: + def __init__(self,data): #Initialization + self.data = data #assigning data + self.next = None #assigning the next pointer to be null + +class SingleLinkedList: + def __init__(self): + self.head = None #assigning the head to be null + + def insertion_at_beg(self, newNode): + if self.head: #if head pointer is not empty + temp = self.head + self.head = newNode + self.head.next = temp + else: #if head pointer is empty + self.head = newNode + + def insertion_at_end(self,newNode): + if self.head: #if head pointer is not empty + temp = self.head #copy the head pointer + while temp.next != None: #traverse through the list till the end + temp = temp.next + temp.next = newNode #assign the new node in the last + newNode.next = None #make the next pointer to be null + else: #if head pointer is empty + self.head = newNode #assign the node as the head node + + def deletion_at_beg(self): + if self.head: + self.head = self.head.next + else: + print("No elements are present") + + def deletion_at_end(self): + if self.head: #if head pointer is not empty + if self.head.next == None: + self.head = None + else: + temp = self.head + while temp.next.next != None: + temp = temp.next + temp.next = None + else: + print("No elements are present") + + def reverse(self): + if self.head: #if head pointer is not empty + previous = self.head + current = self.head.next + self.head = self.head.next + + previous.next = None + while self.head != None: + self.head = self.head.next + current.next = previous + previous = current + current = self.head + + self.head = previous + + print("List Reversed") + else: #if head pointer is empty + print("List Empty") + + def display(self): + ptr = self.head + if ptr == None: #when the head is empty + print("No Elements Present") + else: #print the values present + print("The Values are: ") + while ptr != None: #traverse till end of the list + print(ptr.data, end = "->") + ptr = ptr.next + print("Null") + +if __name__ == "__main__": + listObject = SingleLinkedList() + listObject.insertion_at_end(Node(1)) + listObject.insertion_at_end(Node(2)) + listObject.insertion_at_end(Node(3)) + listObject.insertion_at_end(Node(4)) + listObject.insertion_at_end(Node(5)) + listObject.insertion_at_end(Node(6)) + listObject.insertion_at_end(Node(7)) + listObject.display() + listObject.reverse() + listObject.display() + listObject.deletion_at_beg() + listObject.display() + listObject.insertion_at_beg(Node(8)) + listObject.insertion_at_beg(Node(10)) + listObject.display() + listObject.deletion_at_end() + listObject.display() \ No newline at end of file diff --git a/Python/Basic.py b/Python/Basic.py new file mode 100644 index 0000000..316f831 --- /dev/null +++ b/Python/Basic.py @@ -0,0 +1,29 @@ +import pygame +pygame.init() + +#creating window +gamewindow = pygame.display.set_mode((600,400)) +pygame.display.set_caption("Flappy bird") + +# creating specific variables + +exit_game = False +game_over = False + +# creating game loop + +while not exit_game: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + exit_game = True + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_RIGHT: + print("your pressed right arrow key") + if event.key == pygame.K_LEFT: + print("your pressed Left arrow key") + if event.key == pygame.K_UP: + print("your pressed up arrow key") + if event.key == pygame.K_DOWN: + print("you pressed down arrow key") +pygame.quit() +quit() \ No newline at end of file diff --git a/Python/fibonacci.py b/Python/fibonacci.py new file mode 100644 index 0000000..e63c049 --- /dev/null +++ b/Python/fibonacci.py @@ -0,0 +1,15 @@ +def fibonacci(n): + l=[] + for i in range(n): + if(i==0): + l.append(0) + elif(i==1): + l.append(1) + else: + l.append(l[i-1]+l[i-2]) + return l + # return a list of fibonacci numbers + +if __name__ == '__main__': + n = int(input())#number of terms + print(fibonacci(n)) \ No newline at end of file diff --git a/practical1.py b/Python/math-basic.py similarity index 100% rename from practical1.py rename to Python/math-basic.py diff --git a/Python/triangle.py b/Python/triangle.py new file mode 100644 index 0000000..5ba10fd --- /dev/null +++ b/Python/triangle.py @@ -0,0 +1,6 @@ +rows = int(input("Enter number of rows: ")) + +for i in range(rows): + for j in range(i+1): + print(j+1, end=" ") + print("\n") \ No newline at end of file diff --git a/Python/web-scrapping.py b/Python/web-scrapping.py new file mode 100644 index 0000000..5ab7bc2 --- /dev/null +++ b/Python/web-scrapping.py @@ -0,0 +1,6 @@ +import requests +from bs4 import BeautifulSoup + +page = requests.get('http://corona.sumselprov.go.id/index.php?module=home&id=1') + +print(page.content) \ No newline at end of file diff --git a/README.md b/README.md index 274352b..74af6af 100644 --- a/README.md +++ b/README.md @@ -1 +1,9 @@ # Algorithms 🅰️^_^ + + +# Contributing: +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. + +> Please use latest pull and create file under specific language. \ No newline at end of file diff --git a/ReverseOfArray.java b/ReverseOfArray.java new file mode 100644 index 0000000..9430ecf --- /dev/null +++ b/ReverseOfArray.java @@ -0,0 +1,38 @@ +public class GFG { + + static void rvereseArray(int arr[], + int start, int end) + { + int temp; + + while (start < end) + { + temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } + } + + static void printArray(int arr[], + int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + + public static void main(String args[]) { + + int arr[] = {1, 2, 3, 4, 5, 6}; + printArray(arr, 6); + rvereseArray(arr, 0, 5); + System.out.print("Reversed array is \n"); + printArray(arr, 6); + + } +} + diff --git a/Sedgwik.cpp b/Sedgwik.cpp new file mode 100644 index 0000000..548f08e --- /dev/null +++ b/Sedgwik.cpp @@ -0,0 +1,2506 @@ + +C++ Programs from Algorithms 2nd edition + +Copyright 1992. Addison-Wesley Publishing Company, Inc. +All Rights Reserved. + + +-------------------------------- +CHAPTER 1 Introduction + + +-------------------------------- +CHAPTER 2 C++ (and C) + +#include +int gcd(int u, int v) + { + int t; + while (u > 0) + { + if (u < v) { t = u; u = v; v = t; } + u = u - v; + } + return v; + } +main() + { + int x, y; + while (cin >> x && cin >> y) + if (x>0 && y>0) cout << x << ' ' << y << ' ' + << gcd(x,y) << '\n'; + } + +-------------------------------- +CHAPTER 3 Elementary Data Structures + +const int N = 1000; +main() + { + int i, j, a[N+1]; + for (a[1] = 0, i = 2; i <= N; i++) a[i] = 1; + for (i = 2; i <= N/2; i++) + for (j = 2; j <= N/i; j++) + a[i*j] = 0; + for (i = 1; i <= N; i++) + if (a[i]) cout << i << ' '; + cout << '\n'; + } + + struct node + { int key; struct node *next; }; + + struct node *head, *z; + head = new node; z = new node; + head->next = z; z->next = z; + +struct node + { int key; struct node *next; }; +main() + { + int i, N, M; + struct node *t, *x; + cin >> N >> M; + t = new node; t->key = 1; x = t; + for (i = 2; i <= N; i++) + { + t->next = new node; + t = t->next; t->key = i; + } + t->next = x; + while (t != t->next) + { + for (i = 1; i < M; i++) t = t->next; + cout << t->next->key << ' '; + x = t->next; t->next = x->next; + delete x; + } + cout << t->key << '\n'; + } + + key[x] = v; next[x] = next[t]; next[t] = x++; + +class Stack + { + private: + itemType *stack; + int p; + public: + Stack(int max=100) + { stack = new itemType[max]; p = 0; } + ~Stack() + { delete stack; } + inline void push(itemType v) + { stack[p++] = v; } + inline itemType pop() + { return stack[--p]; } + inline int empty() + { return !p; } + }; + + char c; Stack acc(50); int x; + while (cin.get(c)) + { + x = 0; + while (c == ' ') cin.get(c); + if (c == '+') x = acc.pop() + acc.pop(); + if (c == '*') x = acc.pop() * acc.pop(); + while (c>='0' && c<='9') + { x = 10*x + (c-'0'); cin.get(c); } + acc.push(x); + } + cout << acc.pop() << '\n'; + + char c; Stack save(50); + while (cin.get(c)) + { + if (c == ')') cout.put(save.pop()); + if (c == '+') save.push(c); + if (c == '*') save.push(c); + while (c>='0' && c<='9') + { cout.put(c); cin.get(c); } + if (c != '(') cout << ' '; + } + cout << '\n'; + +class Stack + { + public: + Stack(int max); + ~Stack(); + void push(itemType v); + itemType pop(); + int empty(); + private: + struct node + { itemType key; struct node *next; }; + struct node *head, *z; + }; + +Stack::Stack(int max) + { + head = new node; z = new node; + head->next = z; z->next = z; + } +Stack::~Stack() + { + struct node *t = head; + while (t != z) + { head = t; t = t->next; delete head; } + } + +void Stack::push(itemType v) + { + struct node *t = new node; + t->key = v; t->next = head->next; + head->next = t; + } +itemType Stack::pop() + { + itemType x; + struct node *t = head->next; + head->next = t->next; x = t->key; + delete t; return x; + } +int Stack::empty() + { return head->next == z; } + +void Queue::put(itemType v) + { + queue[tail++] = v; + if (tail > size) tail = 0; + } +itemType Queue::get() + { + itemType t = queue[head++]; + if (head > size) head = 0; + return t; + } +int Queue::empty() + { return head == tail; } + + +-------------------------------- +CHAPTER 4 Trees + + struct node + { char info; struct node *l, *r; }; + struct node *x, *z; + + char c; Stack stack(50); + z = new node; z->l = z; z->r = z; + while (cin.get(c)) + { + while (c == ' ') cin.get(c); + x = new node; + x->info = c; x->l = z; x->r = z; + if (c=='+' || c=='*') + { x->r = stack.pop(); x->l = stack.pop(); } + stack.push(x); + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); visit(t); + if (t->r != z) stack.push(t->r); + if (t->l != z) stack.push(t->l); + } + } + +traverse(struct node *t) + { + queue.put(t); + while (!queue.empty()) + { + t = queue.get(); visit(t); + if (t->l != z) queue.put(t->l); + if (t->r != z) queue.put(t->r); + } + } + + +-------------------------------- +CHAPTER 5 Recursion + +int factorial(int N) + { + if (N == 0) return 1; + return N * factorial(N-1); + } + +int fibonacci(int N) + { + if (N <= 1) return 1; + return fibonacci(N-1) + fibonacci(N-2); + } + +const int max = 25; +int fibonacci(int N) + { + int i, F[max]; + F[0] = 1; F[1] = 1; + for (i = 2; i <= max; i++) + F[i] = F[i-1] + F[i-2]; + return F[N]; + } + +rule(int l, int r, int h) + { + int m = (l+r)/2; + if (h > 0) + { + mark(m,h); + rule(l,m,h-1); + rule(m,r,h-1); + } + } + +rule(0,8,3) + mark(4,3 ) + rule(0,4,2) + mark(2,2) + rule(0,2,1) + mark(1,1) + rule(0,1,0) + rule(1,2,0) + rule(2,4,1) + mark(3,1) + rule(2,3,0) + rule(3,4,0) + rule(4,8,2) + mark(6,2) + rule(4,6,1) + mark(5,1) + rule(4,5,0) + rule(5,6,0) + rule(6,8,1) + mark(7,1) + rule(6,7,0) + +rule(0,8,3) + rule(0,4,2) + rule(0,2,1) + rule(0,1,0) + mark(1,1) + rule(1,2,0) + mark(2,2) + rule(2,4,1) + rule(2,3,0) + mark(3,1) + rule(3,4,0) + mark(4,3 ) + rule(4,8,2) + rule(4,6,1) + rule(4,5,0) + mark(5,1) + rule(5,6,0) + mark(6,2) + rule(6,8,1) + rule(6,7,0) + mark(7,1) + +rule(int l, int r, int h) + { + int i, j, t; + for (i = 1,j = 1; i <= h; i++,j+=j) + for (t = 0; t <= (l+r)/j; t++) + mark(l+j+t*(j+j),i); + } + +star(int x, int y, int r) + { + if (r > 0) + { + star(x-r,y+r,r/2); + star(x+r,y+r,r/2); + star(x-r,y-r,r/2); + star(x+r,y-r,r/2); + box(x,y,r); + } + } + +traverse(struct node *t) + { + if (t != z) + { + traverse(t->l); + visit(t); + traverse(t->r); + } + } + +visit(struct node *t) + { t->x = ++x; t->y = y; } +traverse(struct node *t) + { + y++; + if (t != z) + { + traverse(t->l); + visit(t); + traverse(t->r) + } + y--; + } + +traverse(struct node *t) + { + if (t != z) + { + visit(t); + traverse(t->l); + traverse(t->r); + } + } + +traverse(struct node *t) + { + l: if (t == z) goto x; + visit(t); + traverse(t->l); + t = t->r; + goto l; + x: ; + } + +traverse(struct node *t) + { + l: if (t == z) goto s; + visit(t); + stack.push(t); t = t->l; goto l; + r: t = t->r; goto l; + s: if (stack.empty()) goto x; + t = stack.pop(); goto r; + x: ; + } + +traverse(struct node *t) + { + l: while (t != z) + { + visit(t); + stack.push(t->r); t = t->l; + } + if (stack.empty()) goto x; + t = stack.pop(); goto l; + x: ; + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); + while (t != z) + { + visit(t); + stack.push(t->r); + t = t->l; + } + } + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); + if (t != z) + { + visit(t); + stack.push(t->r); + stack.push(t->l); + } + } + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); visit(t); + if (t->r != z) stack.push(t->r); + if (t->l != z) stack.push(t->l); + } + } + + +-------------------------------- +CHAPTER 6 Analysis of Algorithms + + +-------------------------------- +CHAPTER 7 Implementation of Algorithms + + +-------------------------------- +CHAPTER 8 Elementary Sorting Methods + +inline void swap(itemType a[], int i, int j) + { itemType t = a[i]; a[i] = a[j]; a[j] = t; } +sort3(itemType a[], int N) + { + if (a[1] > a[2]) swap(a, 1, 2); + if (a[1] > a[3]) swap(a, 1, 3); + if (a[2] > a[3]) swap(a, 2, 3); + } +const int maxN = 100; +main() + { + int N, i; itemType v, a[maxN+1]; + N = 0; while (cin >> v) a[++N] = v; + a[0] = 0; + sort3(a, N); + for (i = 1; i <= N; i++) cout << a[i] << ' '; + cout << '\n'; + } + +void selection(itemType a[], int N) + { + int i, j, min; + for (i = 1; i < N; i++) + { + min = i; + for (j = i+1; j <= N; j++) + if (a[j] < a[min]) min = j; + swap(a, min, i); + } + } + +void insertion(itemType a[], int N) + { + int i, j; itemType v; + for (i = 2; i <= N; i++) + { + v = a[i]; j = i; + while (a[j-1] > v) + { a[j] = a[j-1]; j--; } + a[j] = v; + } + } + +void bubble(itemType a[], int N) + { + int i, j; + for (i = N; i >= 1; i--) + for (j = 2; j <= i; j++) + if (a[j-1] > a[j]) swap(a, j-1, j); + } + +void insertion(itemType a[], int p[], int N) + { + int i, j; itemType v; + for (i = 0; i <= N; i++) p[i] = i; + for (i = 2; i <= N; i++) + { + v = p[i]; j = i; + while (a[p[j-1]] > a[v]) + { p[j] = p[j-1]; j--; } + p[j] = v; + } + } + +void insitu(itemType a[], int p[], int N) + { + int i, j, k; itemType t; + for (i = 1; i <= N; i++) + if (p[i] != i) + { + t = a[i]; k = i; + do + { + j = k; a[j] = a[p[j]]; + k = p[j]; p[j] = j; + } + while (k != i); + a[j] = t; + } + } + +void insertion(itemType a[], itemType *p[], int N) + { + int i, j; itemType *v; + for (i = 0; i <= N; i++) p[i] = &a[i]; + for (i = 2; i <= N; i++) + { + v = p[i]; j = i; + while (*p[j-1] > *v) + { p[j] = p[j-1]; j--; } + p[j] = v; + } + } + +void shellsort(itemType a[], int N) + { + int i, j, h; itemType v; + for (h = 1; h <= N/9; h = 3*h+1) ; + for ( ; h > 0; h /= 3) + for (i = h+1; i <= N; i += 1) + { + v = a[i]; j = i; + while (j>h && a[j-h]>v) + { a[j] = a[j-h]; j -= h; } + a[j] = v; + } + } + +for (j = 0; j < M; j++) count[j] = 0; +for (i = 1; i <= N; i++) count[a[i]]++; +for (j = 1; j < M; j++) count[j] += count[j-1]; +for (i = N; i >= 1; i--) b[count[a[i]]--] = a[i]; +for (i = 1; i <= N; i++) a[i] = b[i]; + + +-------------------------------- +CHAPTER 9 Quicksort + +void quicksort(itemType a[], int l, int r) + { + int i; + if (r > l) + { + i = partition(a, l, r); + quicksort(a, l, i-1); + quicksort(a, i+1, r); + } + } + +void quicksort(itemType a[], int l, int r) + { + int i, j; itemType v; + if (r > l) + { + v = a[r]; i = l-1; j = r; + for (;;) + { + while (a[++i] < v) ; + while (a[--j] > v) ; + if (i >= j) break; + swap(a, i, j); + } + swap(a, i, r); + quicksort(a, l, i-1); + quicksort(a, i+1, r); + } + } + +void quicksort(itemType a[], int l, int r) + { + int i; Stack sf(50); + for (;;) + { + while (r > l) + { + i = partition(a, l, r); + if (i-l > r-i) + { sf.push(l); sf.push(i-1); l = i+1; } + else + { sf.push(i+1); sf.push(r); r = i-1; } + } + if (sf.empty()) break; + r = sf.pop(); l = sf.pop(); + } + } + +void select(itemType a[], int l, int r, int k) + { + int i; + if (r > l) + { + i = partition(a, l, r); + if (i > l+k-1) select(a, l, i-1, k); + if (i < l+k-1) select(a, i+1, r, k-i); + } + } + +void select(itemType a[], int N, int k) + { + int i, j, l, r; itemType v; + l = 1; r = N; + while (r > l) + { + v = a[r]; i = l-1; j = r; + for (;;) + { + while (a[++i] < v) ; + while (a[--j] > v) ; + if (i >= j) break; + swap(a, i, j); + } + swap(a, i, r); + if (i >= k) r = i-1; + if (i <= k) l = i+1; + } + } + + +-------------------------------- +CHAPTER 10 Radix Sorting + +class bitskey + { + private: + int x; + public: + bitskey& operator=(int i) + { x = i; return *this; } + inline unsigned bits(int k, int j) + { return (x >> k) & ~(~0 << j); } + }; +typedef bitskey itemType; + +void radixexchange(itemType a[], int l, int r, int b) + { + int i, j; itemType t; + if (r>l && b>=0) + { + i = l; j = r; + while (j != i) + { + while (!a[i].bits(b, 1) && ii) j--; + swap(a, i, j); + } + if (!a[r].bits(b, 1)) j++; + radixexchange(a, l, j-1, b-1); + radixexchange(a, j, r, b-1); + } + } + +void straightradix(itemType a[], itemType b[], int N) + { + int i, j, pass, count[M-1]; + for (pass = 0; pass < w/m; pass++) + { + for (j = 0; j < M; j++) count[j] = 0; + for (i = 1; i <= N; i++) + count[a[i].bits(pass*m, m)]++; + for (j = 1; j < M; j++) + count[j] += count[j-1]; + for (i = N; i >= 1; i--) + b[count[a[i].bits(pass*m, m)]--] = a[i]; + for (i = 1; i <= N; i++) a[i] = b[i]; + } + } + + +-------------------------------- +CHAPTER 11 Priority Queues + +class PQ + { + private: + itemType *a; + int N; + public: + PQ(int max) + { a = new itemType[max]; N = 0; } + ~PQ() + { delete a; } + void insert(itemType v) + { a[++N] = v; } + itemType remove() + { + int j, max = 1; + for (j = 2; j <= N; j++) + if (a[j] > a[max]) max = j; + swap(a, max, N); + return a[N--]; + } + }; + +void PQ::upheap(int k) + { + itemType v; + v = a[k]; a[0] = itemMAX; + while (a[k/2] <= v) + { a[k] = a[k/2]; k = k/2; } + a[k] = v; + } +void PQ::insert(itemType v) + { a[++N] = v; upheap(N); } + +void PQ::downheap(int k) + { + int j; itemType v; + v = a[k]; + while (k <= N/2) + { + j = k+k; + if (j= a[j]) break; + a[k] = a[j]; k = j; + } + a[k] = v; + } + +itemType PQ::remove() + { + itemType v = a[1]; + a[1] = a[N--]; + downheap(1); + return v; + } + +itemType PQ::replace(itemType v) + { + a[0] = v; + downheap(0); + return a[0]; + } + +void heapsort(itemType a[], int N) + { + int i; PQ heap(N); + for (i = 1; i <= N; i++) heap.insert(a[i]); + for (i = N; i >= 1; i--) a[i] = heap.remove(); + } + +void heapsort(itemType a[], int N) + { + int k; + for (k = N/2; k >= 1; k--) + downheap(a, N, k); + while (N > 1) + { swap(a, 1, N); downheap(a, --N, 1); } + } + +class PQ + { + private: + itemType *a; int *p, *info; + int N; + public: + PQ(int size) + { a = new itemType[size]; + p = new int[size]; + info = new int[size]; N = 0; } + ~PQ() + { delete a; delete p; delete info; } + void insert(int x, itemType v) + { a[++N] = v; p[x] = N; info[N] = x; } + void change(int x, itemType v) + { a[p[x]] = v; } + int remove() // remove smallest + { + int j, min = 1; + for (j = 2; j <= N; j++) + if (a[j] < a[min]) min = j; + swap(a, min, N); swap(info, min, N); + p[info[min]] = min; + return info[N--]; + } + int empty() + { return (N <= 0); } + }; + +PQ::PQ(itemType *array, int size) + { + int k; + p = new itemType[size]; q = new itemType[size]; + a = array; N = size; + for (k = 1; k <= N; k++) { p[k] = k; q[k] = k; } + for (k = N/2; k >= 1; k--) downheap(k); + } + +void PQ::downheap(int k) + { + int j, v; + v = p[k]; + while (k <= N/2) + { + j = k+k; + if (j=a[p[j]]) break; + p[k] = p[j]; q[p[j]] = k; k = j; + } + p[k] = v; q[v] = k; + } + + +-------------------------------- +CHAPTER 12 Mergesort + +i = 1; j = 1; +a[M+1] = itemMAX; b[N+1] = itemMAX; +for (k = 1; k <= M+N; k++) + c[k] = (a[i]key <= b->key) + { c->next = a; c = a; a = a->next; } + else + { c->next = b; c = b; b = b->next; } + while (c != z); + c = z->next; z->next = z; + return c; + } + +void mergesort(itemType a[], int l, int r) + { + int i, j, k, m; + if (r > l) + { + m = (r+l)/2; + mergesort(a, l, m); + mergesort(a, m+1, r); + for (i = m+1; i > l; i--) b[i-1] = a[i-1]; + for (j = m; j < r; j++) b[r+m-j] = a[j+1]; + for (k = l; k <= r; k++) + a[k] = (b[i]next != z) + { + a = c; b = c->next->next->next; + while (b != z) + { c = c->next; b = b->next->next; } + b = c->next; c->next = z; + return merge(mergesort(a), mergesort(b)); + } + return c; + } + +struct node *mergesort(struct node *c) + { + int i, N; + struct node *a, *b, *head, *todo, *t; + head = new node; + head->next = c; a = z; + for (N = 1; a != head->next; N = N+N) + { + todo = head->next; c = head; + while (todo != z) + { + t = todo; a = t; + for (i = 1; i < N; i++) t = t->next; + b = t->next; t->next = z; t = b; + for (i = 1; i < N; i++) t = t->next; + todo = t->next; t->next = z; + c->next = merge(a, b); + for (i = 1; i <= N+N; i++) c = c->next; + } + } + return head->next; + } + + +-------------------------------- +CHAPTER 13 External Sorting + + +-------------------------------- +CHAPTER 14 Elementary Searching Methods + +class Dict + { + private: + struct node + { itemType key; infoType info; }; + struct node *a; + int N; + public: + Dict(int max) + { a = new node[max]; N = 0; } + ~Dict() + { delete a; } + infoType search(itemType v); + void insert(itemType v, infoType info); + }; +infoType Dict::search(itemType v) // Sequential + { + int x = N+1; + a[0].key = v; a[0].info = infoNIL; + while (v != a[--x].key) ; + return a[x].info; + } +void Dict::insert(itemType v, infoType info) + { a[++N].key = v; a[N].info = info; } + +class Dict + { + private: + struct node + { itemType key; infoType info; + struct node *next; + node(itemType k, infoType i, struct node *n) + { key = k; info = i; next = n; }; + }; + struct node *head, *z; + public: + Dict(int max) + { + z = new node(itemMAX, infoNIL, 0); + head = new node(0, 0, z); + } + ~Dict(); + infoType search(itemType v); + void insert(itemType v, infoType info); + }; + +infoType Dict::search(itemType v) // Sorted list + { + struct node *t = head; + while (v > t->key) t = t->next; + return (v = t->key) ? t->info : z->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *x, *t = head; + while (v > t->next->key) t = t->next; + x = new node(v, info, t->next); + t->next = x; + } + +infoType Dict::search(itemType v) // Binary search + { + int l = 1; int r = N; int x; + while (r >= l) + { + x = (l+r)/2; + if (v == a[x].key) return a[x].info; + if (v < a[x].key) r = x-1; else l = x+1; + } + return infoNIL; + } + +class Dict + { + private: + struct node + { itemType key; infoType info; + struct node *l, *r; + node(itemType k, infoType i, + struct node *ll, struct node *rr) + { key = k; info = i; l = ll; r = rr; }; + }; + struct node *head, *z; + public: + Dict(int max) + { z = new node( 0, infoNIL, 0, 0); + head = new node(itemMIN, 0, 0, z); } + ~Dict(); + infoType search(itemType v); + void insert(itemType v, infoType info); + }; + +infoType Dict::search(itemType v) + { + struct node *x = head->r; + z->key = v; + while (v != x->key) + x = (v < x->key) ? x->l : x->r; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *x; + p = head; x = head->r; + while (x != z) + { p = x; x = (v < x->key) ? x->l : x->r; } + x = new node(v, info, z, z); + if (v < p->key) p->l = x; else p->r = x; + } + +void Dict::treeprint(struct node *x) + { + if (x != z) + { + treeprint(x->l); + printnode(x); + treeprint(x->r); + } + } + +void Dict::remove(itemType v) + { + struct node *c, *p, *x, *t; + z->key = v; + p = head; x = head->r; + while (v != x->key) + { p = x; x = (v < x->key) ? x->l : x->r; } + t = x; + if (t->r == z) x = x->l; + else if (t->r->l == z) { x = x->r; x->l = t->l; } + else + { + c = x->r; while (c->l->l != z) c = c->l; + x = c->l; c->l = x->r; + x->l = t->l; x->r = t->r; + } + delete t; + if (v < p->key) p->l = x; else p->r = x; + } + + +-------------------------------- +CHAPTER 15 Balanced Trees + +void Dict::insert(itemType v, infoType info) + { + x = head; p = head; g = head; + while (x != z) + { + gg = g; g = p; p = x; + x = (v < x->key) ? x->l : x->r; + if (x->l->b && x->r->b) split(v); + } + x = new node(v, info, 1, z, z); + if (v < p->key) p->l = x; else p->r = x; + split(v); head->r->b = black; + } + +struct node *rotate(itemType v, struct node *y) + { + struct node *c, *gc; + c = (v < y->key) ? y->l : y->r; + if (v < c->key) + { gc = c->l; c->l = gc->r; gc->r = c; } + else + { gc = c->r; c->r = gc->l; gc->l = c; } + if (v < y->key) y->l = gc; else y->r = gc; + return gc; + } + +void split(itemType v) + { + x->b = red; x->l->b = black; x->r->b = black; + if (p->b) + { + g->b = red; + if (vkey != vkey) p = rotate(v, g); + x = rotate(v, gg); + x->b = black; + } + } + + Dict(int max) + { + z = new node( 0, infoNIL, black, 0, 0); + z->l = z; z->r = z; + head = new node(itemMIN, 0, black, 0, z); + } + + +-------------------------------- +CHAPTER 16 Hashing + +unsigned stringkey::hash(int M) + { + int h; char *t = v; + for (h = 0; *t; t++) + h = (64*h + *t) % M; + return h; + } + +Dict::Dict(int sz) + { + M = sz; + z = new node; z->next = z; z->info = infoNIL; + heads = new node*[M]; + for (int i = 0; i < M; i++) + { heads[i] = new node; heads[i]->next = z; } + } + +class Dict + { + private: + struct node + { itemType key; infoType info; + node() { key = " "; info = infoNIL; } + }; + struct node *a; + int M; + public: + Dict(int sz) + { M = sz; a = new node[M]; } + int search(itemType v); + void insert(itemType v, infoType info) + { + int x = v.hash(M); + while (a[x].info != infoNIL) x = (x+1) % M; + a[x].key = v; a[x].info = info; + } + }; + + +-------------------------------- +CHAPTER 17 Radix Searching + +infoType Dict::search(itemType v) // Digital tree + { + struct node *x = head; + int b = itemType::maxb; + z->key = v; + while (v != x->key) + x = (v.bits(b--, 1)) ? x->r : x->l; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *x = head; + int b = itemType::maxb; + while (x != z) + { + p = x; + x = (v.bits(b--, 1)) ? x->r : x->l; + } + x = new node; + x->key = v; x->info = info; x->l = z; x->r = z; + if (v.bits(b+1, 1)) p->r = x; else p->l = x; + } + +infoType Dict::search(itemType v) // Patricia tree + { + struct node *p, *x; + p = head; x = head->l; + while (p->b > x->b) + { + p = x; + x = (bits(v, x->b, 1)) ? x->r : x->l; + } + if (v != x->key) return infoNIL; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *t, *x; + int i = maxb; + p = head; t = head->l; + while (p->b > t->b) + { p = t; t = (bits(v, t->b, 1)) ? t->r : t->l; } + if (v == t->key) return; + while (bits(t->key, i, 1) == bits(v, i, 1)) i--; + p = head; x = head->l; + while (p->b > x->b && x->b > i) + { p = x; x = (bits(v, x->b, 1)) ? x->r : x->l; } + t = new node; + t->key = v; t->info = info; t->b = i; + t->l = (bits(v, t->b, 1)) ? x : t; + t->r = (bits(v, t->b, 1)) ? t : x; + if (bits(v, p->b, 1)) p->r = t; else p->l = t; + } + + +-------------------------------- +CHAPTER 18 External Searching + + +-------------------------------- +CHAPTER 19 String Searching + +int brutesearch(char *p, char *a) + { + int i, j, M = strlen(p), N = strlen(a); + for (i = 0, j = 0; j < M && i < N; i++, j++) + if (a[i] != p[j]) { i -= j-1; j = -1; } + if (j == M) return i-M; else return i; + } + +int kmpsearch(char *p, char *a) + { + int i, j, M = strlen(p), N = strlen(a); + initnext(p); + for (i = 0, j = 0; j < M && i < N; i++, j++) + while ((j >= 0) && (a[i] != p[j])) j = next[j]; + if (j == M) return i-M; else return i; + } + +initnext(char *p) + { + int i, j, M = strlen(p); + next[0] = -1; + for (i = 0, j = -1; i < M; i++, j++, next[i] = j) + while ((j >= 0) && (p[i] != p[j])) j = next[j]; + } + +int kmpsearch(char *a) + { + int i = -1; +sm: i++; +s0: if (a[i] != '1') goto sm; i++; +s1: if (a[i] != '0') goto s0; i++; +s2: if (a[i] != '1') goto s0; i++; +s3: if (a[i] != '0') goto s1; i++; +s4: if (a[i] != '0') goto s2; i++; +s5: if (a[i] != '1') goto s0; i++; +s6: if (a[i] != '1') goto s1; i++; +s7: if (a[i] != '1') goto s1; i++; + return i-8; + } + +next[i] = (p[i] == p[j]) ? next[j] : j + +int mischarsearch(char *p, char *a) + { + int i, j, t, M = strlen(p), N = strlen(a); + initskip(p); + for (i = M-1, j = M-1; j > 0; i--, j--) + while (a[i] != p[j]) + { + t = skip[index(a[i])]; + i += (M-j > t) ? M-j : t; + if (i >= N) return N; + j = M-1; + } + return i; + } + +const int q = 33554393; +const int d = 32; +int rksearch(char *p, char *a) + { + int i, dM = 1, h1 = 0, h2 = 0; + int M = strlen(p), N = strlen(a); + for (i = 1; i < M; i++) dM = (d*dM) % q; + for (i = 0; i < M; i++) + { + h1 = (h1*d+index(p[i])) % q; + h2 = (h2*d+index(a[i])) % q; + } + for (i = 0; h1 != h2; i++) + { + h2 = (h2+d*q-index(a[i])*dM) % q; + h2 = (h2*d+index(a[i+M])) % q; + if (i > N-M) return N; + } + return i; + } + + +-------------------------------- +CHAPTER 20 Pattern Matching + +const int scan = -1; +int match(char *a) + { + int n1, n2; Deque dq(100); + int j = 0, N = strlen(a), state = next1[0]; + dq.put(scan); + while (state) + { + if (state == scan) { j++; dq.put(scan); } + else if (ch[state] == a[j]) + dq.put(next1[state]); + else if (ch[state] == ' ') + { + n1 = next1[state]; n2 = next2[state]; + dq.push(n1); if (n1 != n2) dq.push(n2); + } + if (dq.empty() || j==N) return 0; + state = dq.pop(); + } + return j; + } + + +-------------------------------- +CHAPTER 21 Parsing + +expression() + { + term(); + if (p[j] == '+') + { j++; expression(); } + } + +term() + { + factor(); + if ((p[j] == '(') || letter(p[j])) term(); + } + +factor() + { + if (p[j] == '(') + { + j++; expression(); + if (p[j] == ')') j++; else error(); + } + else if (letter(p[j])) j++; else error(); + if (p[j] == '*') j++; + } + +expression + term + factor + ( + expression + term + factor A * + term + factor B + + + expression + term + factor A + term + factor C + ) + term + factor D + +badexpression(); + { + if (letter(p[j])) j++; else + { + badexpression(); + if (p[j] == '+') { j++; term(); } + else error(); + } + } + + +int expression() + { + int t1,t2,r; + t1 = term(); r = t1; + if (p[j] == '+') + { + j++; state++; + t2 = state; r = t2; state++; + setstate(t2, ' ', expression(), t1); + setstate(t2-1, ' ', state, state); + } + return r; + } + +int term() + { + int t, r; + r = factor(); + if ((p[j] == '(') || letter(p[j])) t = term(); + return r; + } + +int factor() + { + int t1, t2, r; + t1 = state; + if (p[j] == '(') + { + j++; t2 = expression(); + if (p[j] == ')') j++; else error(); + } + else if (letter(p[j])) + { + setstate(state, p[j], state+1, state+1); + t2 = state; j++; state++; + } + else error(); + if (p[j] != '*') r = t2; else + { + setstate(state, ' ', state+1, t2); + r = state; next1[t1-1] = state; + j++; state++; + } + return r; + } + +void matchall(char *a) + { + j = 0; state = 1; + next1[0] = expression(); + setstate(0, ' ', next1[0], next1[0]); + setstate(state, ' ', 0, 0); + while (*a) cout << match(a++) << ' '; + cout << '\n'; + } + + +-------------------------------- +CHAPTER 22 File Compression + + for (i = 0; i <= 26; i++) count[i] = 0; + for (i = 0; i < M; i++) count[index(a[i])]++; + + for (i = 0; i <= 26; i++) + if (count[i]) pq.insert(count[i], i); + for ( ; !pq.empty(); i++) + { + t1 = pq.remove(); t2 = pq.remove(); + dad[i] = 0; dad[t1] = i; dad[t2] = -i; + count[i] = count[t1] + count[t2]; + if (!pq.empty()) pq.insert(count[i], i); + } + +for (k = 0; k <= 26; k++) + { + i = 0; x = 0; j = 1; + if (count[k]) + for (t=dad[k]; t; t=dad[t], j+=j, i++) + if (t < 0) { x += j; t = -t; } + code[k] = x; len[k] = i; + } + +for (j = 0; j < M; j++) + for (i = len[index(a[j])]; i > 0; i--) + cout << ((code[index(a[j])] >> i-1) & 1); + + +-------------------------------- +CHAPTER 23 Cryptology + + +-------------------------------- +CHAPTER 24 Elementary Geometric Methods + +struct point { int x, y; char c; }; +struct line { struct point p1, p2; }; +struct point polygon[Nmax]; + +int ccw(struct point p0, + struct point p1, + struct point p2 ) + { + int dx1, dx2, dy1, dy2; + dx1 = p1.x - p0.x; dy1 = p1.y - p0.y; + dx2 = p2.x - p0.x; dy2 = p2.y - p0.y; + if (dx1*dy2 > dy1*dx2) return +1; + if (dx1*dy2 < dy1*dx2) return -1; + if ((dx1*dx2 < 0) || (dy1*dy2 < 0)) return -1; + if ((dx1*dx1+dy1*dy1) < (dx2*dx2+dy2*dy2)) + return +1; + return 0; + } + +int intersect(struct line l1, struct line l2) + { + return ((ccw(l1.p1, l1.p2, l2.p1) + *ccw(l1.p1, l1.p2, l2.p2)) <= 0) + && ((ccw(l2.p1, l2.p2, l1.p1) + *ccw(l2.p1, l2.p2, l1.p2)) <= 0); + } + +float theta(struct point p1, struct point p2) + { + int dx, dy, ax, ay; + float t; + dx = p2.x - p1.x; ax = abs(dx); + dy = p2.y - p1.y; ay = abs(dy); + t = (ax+ay == 0) ? 0 : (float) dy/(ax+ay); + if (dx < 0) t = 2-t; else if (dy < 0) t = 4+t; + return t*90.0; + } + +int inside(struct point t, struct point p[], int N) + { + int i, count = 0, j = 0; + struct line lt,lp; + p[0] = p[N]; p[N+1] = p[1]; + lt.p1 = t; lt.p2 = t; lt.p2.x = INT_MAX; + for (i = 1; i <= N; i++) + { + lp.p1= p[i]; lp.p2 = p[i]; + if (!intersect(lp,lt)) + { + lp.p2 = p[j]; j = i; + if (intersect(lp,lt)) count++; + } + } + return count & 1; + } + + +-------------------------------- +CHAPTER 25 Finding the Convex Hull + +int wrap(point p[], int N) + { + int i, min, M; + float th, v; + for (min = 0, i = 1; i < N; i++) + if (p[i].y < p[min].y) min = i; + p[N] = p[min]; th = 0.0; + for (M = 0; M < N; M++) + { + swap(p, M, min); + min = N; v = th; th = 360.0; + for (i = M+1; i <= N; i++) + if (theta(p[M], p[i]) > v) + if (theta(p[M], p[i]) < th) + { min = i; th = theta(p[M], p[min]); } + if (min == N) return M; + } + } + +int grahamscan(point p[], int N) + { + int i, min, M; + for (min = 1, i = 2; i <= N; i++) + if (p[i].y < p[min].y) min = i; + for (i = 1; i <= N; i++) + if (p[i].y == p[min].y) + if (p[i].x > p[min].x) min = i; + swap(p, 1, min); + shellsort(p, N); + p[0] = p[N]; + for (M = 3, i = 4; i <= N; i++) + { + while (ccw(p[M], p[M-1], p[i]) >= 0) M--; + M++; swap(p, i, M); + } + return M; + } + + +-------------------------------- +CHAPTER 26 Range Searching + +int range(int v1, int v2) + { return ranger(head->r, v1, v2); } +int ranger(struct node *t, int v1, int v2) + { + int tx1, tx2, count = 0; + if (t == z) return 0; + tx1 = (t->key >= v1); + tx2 = (t->key <= v2); + if (tx1) count += ranger(t->l, v1, v2); + if (tx1 && tx2) count++; + if (tx2) count += ranger(t->r, v1, v2); + return count; + } + +class Range + { + private: + struct node + { struct point p; struct node *next; }; + struct node *grid[maxG][maxG]; + struct node *z; + public: + Range(); + void insert(struct point p); + int search(rect range); + }; +Range::Range() + { + int i, j; + z = new node; + for (i = 0; i <= maxG; i++) + for (j = 0; j <= maxG; j++) + grid[i][j] = z; + } +void Range::insert(struct point p) + { + struct node *t = new node; + t->p = p; t->next = grid[p.x/size][p.y/size]; + grid[p.x/size][p.y/size] = t; + } + +int Range::search(struct rect range) // Grid method + { + struct node *t; + int i, j, count = 0; + for (i = range.x1/size; i <= range.x2/size; i++) + for (j = range.y1/size; j <= range.y2/size; j++) + for (t = grid[i][j]; t != z; t = t->next) + if (insiderect(t->p, range)) count++; + return count; + } + +class Range + { + private: + struct node + { struct point p; struct node *l, *r; }; + struct node *z, *head; + struct point dummy; + int searchr(struct node *t, + struct rect range, int d); + public: + Range(); + void insert(struct point p); + int search(rect range); + }; + +void Range::insert(struct point p) // 2D tree + { + struct node *f, *t; int d, td; + for (d = 0, t = head; t != z; d !=d) + { + td = d ? (p.x < t->p.x) : (p.y < t->p.y); + f = t; t = td ? t->l : t->r; + } + t = new node; t->p = p; t->l = z; t->r = z; + if (td) f->l = t; else f->r = t; + } + +int Range::search(struct rect range) // 2D tree + { return searchr(head->r, range, 1); } +int Range::searchr(struct node *t, + struct rect range, int d) + { + int t1, t2, tx1, tx2, ty1, ty2, count = 0; + if (t == z) return 0; + tx1 = range.x1 < t->p.x; tx2 = t->p.x <= range.x2; + ty1 = range.y1 < t->p.y; ty2 = t->p.y <= range.y2; + t1 = d ? tx1 : ty1; t2 = d ? tx2 : ty2; + if (t1) count += searchr(t->l, range, !d); + if (insiderect(t->p, range)) count++; + if (t2) count += searchr(t->r, range, !d); + return count; + } + + +-------------------------------- +CHAPTER 27 Geometric Intersection + +Dict Xtree(Nmax), Ytree(Nmax); +struct line lines[Nmax]; +int count = 0; +int intersections() + { + int x1, y1, x2, y2, N; + for (N = 1; cin >> x1 >> y1 >> x2 >> y2; N++) + { + lines[N].p1.x = x1; lines[N].p1.y = y1; + lines[N].p2.x = x2; lines[N].p2.y = y2; + Ytree.insert(y1, N); + if (y2 != y1) Ytree.insert(y2, N); + } + Ytree.traverse(); + return count; + } + +void Dict::visit(itemType v, infoType info) + { + int t, x1, x2, y1, y2; + x1 = lines[info].p1.x; y1 = lines[info].p1.y; + x2 = lines[info].p2.x; y2 = lines[info].p2.y; + if (x2 < x1) { t = x2; x2 = x1; x1 = t; } + if (y2 < y1) { t = y2; y2 = y1; y1 = t; } + if (v == y1) + Xtree.insert(x1, info); + if (v == y2) + { + Xtree.remove(x1, info); + count += Xtree.range(x1, x2); + } + } + + +-------------------------------- +CHAPTER 28 Closest-Point Problems + +int comp(struct node *t) + { return (pass == 1) ? t->p.x : t->p.y; } +struct node *merge(struct node *a, struct node *b) + { + struct node *c; + c = z; + do + if (comp(a) < comp(b)) + { c->next = a; c = a; a = a->next; } + else + { c->next = b; c = b; b = b->next; } + while (c != z); + c = z->next; z->next = z; + return c; + } + +check(struct point p1, struct point p2) + { + float dist; + if ((p1.y != z->p.y) && (p2.y != z->p.y)) + { + dist = sqrt((p1.x-p2.x)*(p1.x-p2.x) + +(p1.y-p2.y)*(p1.y-p2.y)); + if (dist < min) + { min = dist; cp1 = p1; cp2 = p2; }; + } + } + +struct node *sort(struct node *c, int N) + { + int i; + struct node *a, *b; + float middle; + struct point p1, p2, p3, p4; + if (c->next == z) return c; + a = c; + for (i = 2; i <= N/2; i++) c = c->next; + b = c->next; c->next = z; + if (pass == 2) middle = b->p.x; + c = merge(sort(a, N/2), sort(b, N-(N/2))); + if (pass == 2) + { + p1 = z->p; p2 = z->p; p3 = z->p; p4 = z->p; + for (a = c; a != z; a = a->next) + if (fabs(a->p.x - middle) < min) + { + check(a->p, p1); + check(a->p, p2); + check(a->p, p3); + check(a->p, p4); + p1 = p2; p2 = p3; p3 = p4; p4 = a->p; + } + } + return c; + } + +z = new node; z->p.x = max; + z->p.y = max; z->next = z; +h = new node; h->next = readlist(); +min = max; +pass = 1; h->next = sort(h->next, N); +pass = 2; h->next = sort(h->next, N); + + +-------------------------------- +CHAPTER 29 Elementary Graph Algorithms + +int V, E; +int a[maxV][maxV]; + +void adjmatrix() + { + int j, x, y; + cin >> V >> E; + for (x = 1; x <= V; x++) + for (y = 1; y <= V; y++) a[x][y] = 0; + for (x = 1; x <= V; x++) a[x][x] = 1; + for (j = 1; j <= E; j++) + { + cin >> v1 >> v2; + x = index(v1); y = index(v2); + a[x][y] = 1; a[y][x] = 1; + } + } + +struct node + { int v; struct node *next; }; +int V, E; +struct node *adj[maxV], *z; + +void adjlist() + { + int j, x, y; struct node *t; + cin >> V >> E; + z = new node; z->next = z; + for (j = 1; j <= V; j++) adj[j] = z; + for (j = 1; j <= E; j++) + { + cin >> v1 >> v2; + x = index(v1); y = index(v2); + t = new node; + t->v = x; t->next = adj[y]; adj[y] = t; + t = new node; + t->v = y; t->next = adj[x]; adj[x] = t; + } + } + +void search() + { + int k; + for (k = 1; k <= V; k++) val[k] = unseen; + for (k = 1; k <= V; k++) + if (val[k] == unseen) visit(k); + } + +void visit(int k) // DFS, adjacency lists + { + struct node *t; + val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) visit(t->v); + } + +void visit(int k) // DFS, adjacency matrix + { + int t; + val[k] = ++id; + for (t = 1; t <= V; t++) + if (a[k][t] != 0) + if (val[t] == unseen) visit(t); + } + +Stack stack(maxV); +void visit(int k) // non-recursive DFS, adj lists + { + struct node *t; + stack.push(k); + while (!stack.empty()) + { + k = stack.pop(); val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { stack.push(t->v); val[t->v] = -1; } + } + } + +Queue queue(maxV); +void visit(int k) // BFS, adjacency lists + { + struct node *t; + queue.put(k); + while (!queue.empty()) + { + k = queue.get(); val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { queue.put(t->v); val[t->v] = -1; } + } + } + + +-------------------------------- +CHAPTER 30 Connectivity + +int visit(int k) // DFS to find articulation points + { + struct node *t; + int m, min; + val[k] = ++id; + min = id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { + m = visit(t->v); + if (m < min) min = m; + if (m >= val[k]) cout << name(k); + } + else if (val[t->v] < min) min = val[t->v]; + return min; + } + +class EQ + { + private: + int *dad; + public: + EQ(int size); + int find(int x, int y, int doit); + }; + +int EQ::find(int x, int y, int doit) + { + int i = x, j = y; + while (dad[i] > 0) i = dad[i]; + while (dad[j] > 0) j = dad[j]; + if (doit && (i != j)) dad[j] = i; + return (i != j); + } + +int EQ::find(int x, int y, int doit) + { + int t, i = x, j = y; + while (dad[i] > 0) i = dad[i]; + while (dad[j] > 0) j = dad[j]; + while (dad[x] > 0) + { t = x; x = dad[x]; dad[t] = i; } + while (dad[y] > 0) + { t = y; y = dad[y]; dad[t] = j; } + if (doit && (i != j)) + if (dad[j] < dad[i]) + { dad[j] += dad[i] - 1; dad[i] = j; } + else + { dad[i] += dad[j] - 1; dad[j] = i; } + return (i != j); + } + + +-------------------------------- +CHAPTER 31 Weighted Graphs + +PQ pq(maxV); +visit(int k) // PFS, adjacency lists + { + struct node *t; + if (pq.update(k, -unseen) != 0) dad[k] = 0; + while (!pq.empty()) + { + id++; k = pq.remove(); val[k] = -val[k]; + if (val[k] == -unseen) val[k] = 0; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] < 0) + if (pq.update(t->v, priority)) + { + val[t->v] = -(priority); + dad[t->v] = k; + } + } + } + + +void kruskal() + { + int i, m, V, E; + struct edge + { char v1, v2; int w; }; + struct edge e[maxE]; + PQ pq(maxE); EQ eq(maxE); + cin >> V >> E; + for (i = 1; i <= E; i++) + cin >> e[i].v1 >> e[i].v2 >> e[i].w; + for (i = 1; i <= E; i++) + pq.insert(i, e[i].w); + for (i = 0; i < V-1; ) + { + if (pq.empty()) break; else m = pq.remove(); + if (eq.find(index(e[m].v1),index(e[m].v2),1)) + { cout << e[m].v1 << e[m].v2 << ' '; i++; }; + } + } + +void search() // PFS, adjacency matrix + { + int k, t, min = 0; + for (k = 1; k <= V; k++) + { val[k] = unseen; dad[k] = 0; } + val[0] = unseen-1; + for (k = 1; k != 0; k = min, min = 0) + { + val[k] = -val[k]; + if (val[k] == -unseen) val[k] = 0; + for (t = 1; t <= V; t++) + if (val[t] < 0) + { + if (a[k][t] && (val[t] < -priority)) + { val[t] = -priority; dad[t] = k; } + if (val[t] > val[min]) min = t; + } + } + } + + +-------------------------------- +CHAPTER 32 Directed Graphs + +for (k = 1; k <= V; k++) + { + id = 0; + for (j = 1; j <= V; j++) val[j] = 0; + visit(k); + cout >> '\n'; + } + +for (y = 1; y <= V; y++) + for (x = 1; x <= V; x++) + if (a[x][y]) + for (j = 1; j <= V; j++) + if (a[y][j]) a[x][j] = 1; + +for (y = 1; y <= V; y++) + for (x = 1; x <= V; x++) + if (a[x][y]) + for (j = 1; j <= V; j++) + if (a[y][j] > 0) + if (!a[x][j] || (a[x][y]+a[y][j] < a[x][j])) + a[x][j] = a[x][y] + a[y][j]; + +Stack stack(maxV); +int visit(int k) // DFS to find strong components + { + struct node *t; int m, min; + val[k] = ++id; min = id; + stack.push(k); + for (t = adj[k]; t != z; t = t->next) + { + m = (!val[t->v]) ? visit(t->v) : val[t->v]; + if (m < min) min = m; + } + if (min == val[k]) + { + do + { + m = stack.pop(); cout << m; + val[m] = V+1; + } + while (m != k); + cout << '\n'; + } + return min; + } + + +-------------------------------- +CHAPTER 33 Network Flow + + priority = -flow[k][t]; + if (size[k][t] > 0) priority += size[k][t]; + if (priority > val[k]) priority = val[k]; + +for (;;) + { + if (!search(1,V)) break; + y = V; x = dad[V]; + while (x != 0) + { + flow[x][y] = flow[x][y]+val[V]; + flow[y][x] = -flow[x][y]; + y = x; x = dad[y]; + } + } + + +-------------------------------- +CHAPTER 34 Matching + +for (m = 1; m <= N; m++) + { + for (s = m; s != 0;) + { + next[s]++; w = prefer[s][next[s]]; + if (rank[w][s] < rank[w][fiancee[w]]) + { t = fiancee[w]; fiancee[w] = s; s = t; } + } + } + + +-------------------------------- +CHAPTER 35 Random Numbers + +a[0] = seed; +for (i = 1; i <= N; i++) + a[i] = (a[i-1]*b+1) % m; + +#include +const int m = 100000000; +const int m1 = 10000; +int mult(int p, int q) + { + int p1, p0, q1, q0; + p1 = p/m1; p0 = p%m1; + q1 = q/m1; q0 = q%m1; + return (((p0*q1+p1*q0) % m1)*m1+p0*q0) % m; + } +class Random + { + private: + int a; + public: + Random(int seed) + { a = seed; } + int next() + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return a; + } + }; +main() + { + int i, N; Random x(1234567); + cin >> N; + for (i = 1; i <= N; i++) + cout << x.next() << ' '; + cout << '\n'; + } + + + int badnext(int r) + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return a % r; + } + + int next(int r) + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return ((a/m1)*r)/m1; + } + +class Random + { + private: + int a[55], j; + public: + Random(int seed); + int next(int r) + { + j = (j+1) % 55; + a[j] = (a[(j+23) % 55]+a[(j+54) % 55]) % m; + return ((a[j]/m1)*r)/m1; + } + }; + +Random:: Random(int seed) + { const int b = 31415821; + a[0] = seed; + for (j = 1; j <= 54; j++) + a[j] = (mult(a[j-1], b) + 1) % m; + } + +float chisquare(int N, int r) + { + int i, t, f[rmax]; Random x(1234567); + for (i = 0; i < r; i++) f[i] = 0; + for (i = 0; i < N; i++) f[x.next(r)]++; + for (i = 0, t = 0; i < r; i++) t += f[i]*f[i]; + return (float) ((r*t/N) - N); + } + + +-------------------------------- +CHAPTER 36 Arithmetic + +for (i = 0; i < N; i++) r[i] = p[i]+q[i]; + +for (i = 0; i < 2*N-1; i++) r[i] = 0; +for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + r[i+j] += p[i]*q[j]; + +struct node *add(struct node *p, struct node *q) + { + struct node *t; + t = z; z->c = 0; + while ((p != z) && (q != z)) + { + t->next = new node; + t = t->next; t->c = p->c + q->c; + p = p->next; q = q->next; + } + t->next = z; t = z->next; z->next = z; + return t; + } + +struct node + { int c; int j; struct node *next; }; + +struct node *insert(struct node *t, int c, int j) + { + t->next = new node; + t = t->next; t->c = c; t->j = j; + return t; + } + +struct node *add(struct node *p, struct node *q) + { + struct node *t; + t = z; z->c = 0; z->j = maxN; + while ((p !=z) || (q != z)) + { + if ((p->j == q->j) && ((p->c + q->c) != 0)) + { + t = insert(t, p->c+q->c, p->j); + p = p->next; q = q->next; + } + else if (p->j < q->j) + { t = insert(t, p->c, p->j); p = p->next; } + else if (q->j < p->j) + { t = insert(t, q->c, q->j); q = q->next; } + } + t->next = z; t = z->next; z->next = z; + return t; + } + +y = p[N]; +for (i = N-1; i >= 0; i--) y = x*y + p[i]; + +float *mult(float p[], float q[], int N) + { + float pl[N/2], ql[N/2], ph[N/2], qh[N/2], + t1[N/2], t2[N/2]; + float r[2*N-2], rl[N], rm[N], rh[N]; + int i, N2; + if (N == 1) + { r[0] = p[0]*q[0]; return (float *) r; } + for (i = 0; i < N/2; i++) + { pl[i] = p[i]; ql[i] = q[i]; } + for (i = N/2; i < N; i++) + { ph[i-N/2] = p[i]; qh[i-N/2] = q[i]; } + for (i = 0; i < N/2; i++) t1[i] = pl[i]+ph[i]; + for (i = 0; i < N/2; i++) t2[i] = ql[i]+qh[i]; + rm = mult(t1, t2, N/2); + rl = mult(pl, ql, N/2); + rh = mult(ph, qh, N/2); + for (i = 0; i < N-1; i++) r[i] = rl[i]; + r[N-1] = 0; + for (i = 0; i < N-1; i++) r[N+i] = rh[i]; + for (i = 0; i < N-1; i++) + r[N/2+i] += rm[i] - (rl[i]+rh[i]); + return (float *) r; + } + + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + for (k = 0, r[i][j] = 0; k < N; k++) + r[i][j] += p[i][k]*q[k][j]; + + +-------------------------------- +CHAPTER 37 Gaussian Elimination + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N; j++) + for (k = N+1; k >= i; k--) + a[j][k] -= a[i][k]*a[j][i]/a[i][i]; + +eliminate() + { + int i, j, k, max; + float t; + for (i = 1; i <= N; i++) + { + max = i; + for (j = i+1; j <= N; j++) + if (abs(a[j][i]) > abs(a[max][i])) max = j; + for (k = i; k <= N+1; k++) + { t = a[i][k]; + a[i][k] = a[max][k]; + a[max][k] = t; } + for (j = i+1; j <= N; j++) + for (k = N+1; k >= i; k--) + a[j][k] -= a[i][k]*a[j][i]/a[i][i]; + } + } + +substitute() + { + int j, k; + float t; + for (j = N; j >= 1; j--) + { + t = 0.0; + for (k = j+1; k <= N; k++) t += a[j][k]*x[k]; + x[j] = (a[j][N+1]-t)/a[j][j]; + } + } + + for (i = 1; i < N; i++) + { + a[i+1][N+1] -= a[i][N+1]*a[i+1][i]/a[i][i]; + a[i+1][i+1] -= a[i][i+1]*a[i+1][i]/a[i][i]; + } + for (j = N; j >= 1; j--) + x[j] = (a[j][N+1]-a[j][j+1]*x[j+1])/a[j][j]; + + +-------------------------------- +CHAPTER 38 Curve Fitting + +makespline(float x[], float y[], int N) + { + for (i = 2; i < N; i++) d[i] = 2*(x[i+1]-x[i-1]); + for (i = 1; i < N; i++) u[i] = x[i+1]-x[i]; + for (i = 2; i < N; i++) + w[i] = 6.0*((y[i+1]-y[i])/u[i] + -(y[i]-y[i-1])/u[i-1]); + p[1] = 0.0; p[N] = 0.0; + for (i = 2; i < N-1; i++) + { + w[i+1] = w[i+1] - w[i]*u[i]/d[i]; + d[i+1] = d[i+1] - u[i]*u[i]/d[i]; + } + for (i = N-1; i > 1; i--) + p[i] = (w[i]-u[i]*p[i+1])/d[i]; + } + +float f(float x) + { return x*x*x - x; } +float eval(float v) + { + float t; int i = 1; + while (v > x[i+1]) i++; + t = (v-x[i])/u[i]; + return t*y[i+1]+(1-t)*y[i] + + u[i]*u[i]*(f(t)*p[i+1]+f(1-t)*p[i])/6.0; + } + +for (i = 1; i <= M; i++) + for (j = 1; j <= M+1; j++) + { + t = 0.0; + for (k = 1; k <= N; k++) + t += f[i][k]*f[j][k]; + a[i][j] = t; + } + + +-------------------------------- +CHAPTER 39 Integration + +for (i = N; i > 0; i--) p[i] = p[i-1]/i; p[0] = 0; + +double intrect(double a, double b, int N) + { + int i; double r = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) r += w*f(a-w/2+i*w); + return r; + } + +double inttrap(double a, double b, int N) + { + int i; double t = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) + t += w*(f(a+(i-1)*w)+f(a+i*w))/2; + return t; + } + +double intsimp(double a, double b, int N) + { + int i; double s = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) + s += w*(f(a+(i-1)*w) + + 4*f(a-w/2+i*w) + + f(a+i*w))/6; + return s; + } + +double adapt(double a, double b) + { + double x = intsimp(a, b, 10); + if (fabs(x - intsimp(a, b, 5)) > tolerance) + return adapt(a, (a+b)/2) + adapt((a+b)/2, b); + return x; + } + + +-------------------------------- +CHAPTER 40 Parallel Algorithms + + +-------------------------------- +CHAPTER 41 The Fast Fourier Transform + +eval(p, outN, 0); +eval(q, outN, 0); +for (i = 0; i <= outN; i++) r[i] = p[i]*q[i]; +eval(r, outN, 0); +for (i = 1; i <= N; i++) + { t = r[i]; r[i] = r[outN+1-i]; r[outN+1-i] = t; } +for (i = 0; i <= outN; i++) r[i] = r[i]/(outN+1); + +eval(complex p[], int N, int k) + { + int i, j; + if (N == 1) + { + p0 = p[k]; p1 = p[k+1]; + p[k] = p0+p1; p[k+1] = p0-p1; + } + else + { + for (i = 0; i <= N/2; i++) + { + j = k+2*i; + t[i] = p[j]; t[i+1+N/2] = p[j+1]; + } + for (i = 0; i <= N; i++) p[k+i] = t[i]; + eval(p, N/2, k); + eval(p, N/2, (k+1+N)/2); + j = (outN+1)/(N+1); + for (i = 0; i <= N/2; i++) + { + p0 = w[i*j]*p[k+(N/2)+1+i]; + t[i] = p[k+i]+p0; + t[i+(N/2)+1] = p[k+i]-p0; + } + for (i = 0; i <= N; i++) p[k+i] = t[i]; + } + } + + +-------------------------------- +CHAPTER 42 Dynamic Programming + +for (j = 1; j <= N; j++) + { + for (i = 1; i <= M; i++) + if (i >= size[j]) + if (cost[i] < cost[i-size[j]]+val[j]) + { + cost[i] = cost[i-size[j]]+val[j]; + best[i] = j; + } + } + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N; j++) cost[i][j] = INT_MAX; +for (i = 1; i <= N; i++) cost[i][i] = 0; +for (j = 1; j < N; j++) + for (i = 1; i <= N-j; i++) + for (k = i+1; k <= i+j; k++) + { + t = cost[i][k-1]+cost[k][i+j] + +r[i]*r[k]*r[i+j+1]; + if (t < cost[i][i+j]) + { cost[i][i+j] = t; best[i][i+j] = k; } + } + +order(int i, int j) + { + if (i == j) cout >> name(i); else + { + cout >> '('; + order(i, best[i][j]-1); order(best[i][j], j); + cout >> ')'; + } + } + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N+1; j++) cost[i][j] = INT_MAX; +for (i = 1; i <= N; i++) cost[i][i] = f[i]; +for (i = 1; i <= N+1; i++) cost[i][i-1] = 0; +for (j = 1; j <= N-1; j++) + for (i = 1; i <= N-j; i++) + { + for (k = i; k <= i+j; k++) + { + t = cost[i][k-1]+cost[k+1][i+j]; + if (t < cost[i][i+j]) + { cost[i][i+j] = t; best[i][i+j] = k; } + } + for (k = i; k <= i+j; cost[i][i+j] += f[k++]) ; + } + + +-------------------------------- +CHAPTER 43 Linear Programming + +pivot(int p, int q) + { + int j, k; + for (j = 0; j <= N; j++) + for (k = M+1; k >= 1; k--) + if (j!=p && k!=q) + a[j][k] = a[j][k]-a[p][k]*a[j][q]/a[p][q]; + for (j = 0; j <= N; j++) + if (j != p) a[j][q] = 0; + for (k = 1; k <= M+1; k++) + if (k != q) a[p][k] = a[p][k]/a[p][q]; + a[p][q] = 1; + } + +for (;;) + { + for (q = 0; (q<=M+1) && (a[0][q]>=0); q++) ; + for (p = 0; (p<=N+1) && (a[p][q]<=0); p++) ; + if (q>M || p>N) break; + for (i = p+1; i <= N; i++) + if (a[i][q] > 0) + if (a[i][M+1]/a[i][q] < a[p][M+1]/a[p][q]) + p = i; + pivot(p,q); + } + + +-------------------------------- +CHAPTER 44 Exhaustive Search + +visit(int k) + { + int t; + val[k] = ++id; + for (t = 1; t <= V; t++) + if (a[k][t]) + if (val[t] == 0) visit(t); + id--; val[k] = 0; + } + +visit(int k) + { + int t; + val[k] = ++id; + if (id == V) writeperm(); + for (t = 1; t <= V; t++) + if (val[t] == 0) visit(t); + id--; val[k] = 0; + } + + +-------------------------------- +CHAPTER 45 NP-Complete Problems + diff --git a/binary_conversion.c b/binary_conversion.c new file mode 100644 index 0000000..e661efa --- /dev/null +++ b/binary_conversion.c @@ -0,0 +1,24 @@ +#include +#include +#include + +void main() +{ + int n,i=0,z,j; + scanf("%d",&n); + int *a = (int*)malloc(sizeof(int)); + + while(n>0) + { + z=n%2; + a[i]=z; + i++; + n/=2; + } + i--; + while(i>=0) + { + printf("%d",a[i]); + i--; + } +} \ No newline at end of file diff --git a/binary_conversions1.c b/binary_conversions1.c new file mode 100644 index 0000000..eb4c6a1 --- /dev/null +++ b/binary_conversions1.c @@ -0,0 +1,26 @@ +#include +#include +#include + +void main() +{ + int n,i=0,z,j; + scanf("%d",&n); + int *a = (int*)malloc(sizeof(int)); + + while(n>0) + { + z=n%2; + a[i]=z; + i++; + n/=2; + } + i--; + while(i>=0) + { + printf("%d",a[i]); + i--; + } +} +Footer +© 2022 GitHub, Inc. diff --git a/bintodecimal (2020_12_18 18_56_42 UTC).c b/bintodecimal (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..a692ec8 --- /dev/null +++ b/bintodecimal (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,21 @@ +#include +#include +#include + +int main() +{ +long int a,b,x=0,i,n; +int d; +float e; +printf("enter binary number\n"); +scanf("%ld",&n); + +for (i=0;n!=0;++i) +{ + a=n%10; + x=a+(pow(2,i))+x; + n=n/10; +} +printf("%ld",x); + return 0; +} \ No newline at end of file diff --git a/breadthfirstsearch c++.txt b/breadthfirstsearch c++.txt new file mode 100644 index 0000000..b5f934f --- /dev/null +++ b/breadthfirstsearch c++.txt @@ -0,0 +1,88 @@ +// Program to print BFS traversal from a given +// source vertex. BFS(int s) traverses vertices +// reachable from s. +#include +using namespace std; + +// This class represents a directed graph using +// adjacency list representation +class Graph +{ + int V; // No. of vertices + + // Pointer to an array containing adjacency + // lists + vector> adj; +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int v, int w); + + // prints BFS traversal from a given source s + void BFS(int s); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj.resize(V); +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::BFS(int s) +{ + // Mark all the vertices as not visited + vector visited; + visited.resize(V,false); + + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + + while(!queue.empty()) + { + // Dequeue a vertex from queue and print it + s = queue.front(); + cout << s << " "; + queue.pop_front(); + + // Get all adjacent vertices of the dequeued + // vertex s. If a adjacent has not been visited, + // then mark it visited and enqueue it + for (auto adjecent: adj[s]) + { + if (!visited[adjecent]) + { + visited[adjecent] = true; + queue.push_back(adjecent); + } + } + } +} + +// Driver program to test methods of graph class +int main() +{ + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; +} diff --git a/charisalphabet (2020_12_18 18_56_42 UTC).c b/charisalphabet (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..f627650 --- /dev/null +++ b/charisalphabet (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,21 @@ +//char is alphabet or not +#include +int main() +{ + char c; + printf("enter a\n"); + scanf("%c", &c); + + // if (c >= 'a' && c <= 'z' || c >= 'A' && c <= "Z") + // { + // printf("CAHARCTER IS ALPHABET"); + // } + + // else + // { + // printf("NO CAHARCTER IS NOT AN ALPHABET"); + // } + (c >= 'a' && c <= 'z' || c >= 'A' && c <= "Z") ? printf("Character is Alphabet") : printf("NOT AN ALPHABET"); + + return 0; +} diff --git a/count total number of occurances of element in the sorted array in java b/count total number of occurances of element in the sorted array in java new file mode 100644 index 0000000..06c0ff0 --- /dev/null +++ b/count total number of occurances of element in the sorted array in java @@ -0,0 +1,30 @@ +public int count(int[] arr, int target) { + int left = binarySearch(arr, target, true); + if (left < 0) return 0; + int right = binarySearch(arr, target, false); + return right - left + 1; +} + +private int binarySearch(int[] arr, int target, boolean leftmost) { + int lo = 0; + int hi = arr.length - 1; + int idx = -1; + while (lo <= hi) { + int mid = (lo + hi) >>> 1; // avoid overflow. same as (lo + hi) / 2 + + if (target > arr[mid]) { + lo = mid + 1; + } else if (target < arr[mid]) { + hi = mid - 1; + } else { + idx = mid; + if (leftmost) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } + } + return idx; +} + diff --git a/dataManipulation.java b/dataManipulation.java new file mode 100644 index 0000000..efb481a --- /dev/null +++ b/dataManipulation.java @@ -0,0 +1,34 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + System.out.println("ArrayList1: " + numbers); + + // Using reverse() + Collections.reverse(numbers); + System.out.println("Reversed ArrayList1: " + numbers); + + // Using swap() + Collections.swap(numbers, 0, 1); + System.out.println("ArrayList1 using swap(): " + numbers); + + ArrayList newNumbers = new ArrayList<>(); + + // Using addAll + newNumbers.addAll(numbers); + System.out.println("ArrayList2 using addAll(): " + newNumbers); + + // Using fill() + Collections.fill(numbers, 0); + System.out.println("ArrayList1 using fill(): " + numbers); + + // Using copy() + Collections.copy(newNumbers, numbers); + System.out.println("ArrayList2 using copy(): " + newNumbers); + } +} diff --git a/doubleLinkedList.cpp b/doubleLinkedList.cpp new file mode 100644 index 0000000..4d890a9 --- /dev/null +++ b/doubleLinkedList.cpp @@ -0,0 +1,136 @@ +#include +using namespace std; + +template +struct DoubleLinkedList{ + struct Node{ + T data; + Node *next; + Node *prev; + }; + + Node *n=NULL, *head=NULL, *tail=NULL, *x=NULL; + + void addNewNode(T i){ + n = new Node; + n->data = i; + n->prev = NULL; + head = n; + tail = n; + tail->next = NULL; + } + + void addNodeLast(T i){ + n = new Node; + n->data = i; + n->prev = tail; + tail->next = n; + tail = n; + tail->next = NULL; + } + + void addNodeFront(T i){ + n = new Node; + n->data = i; + n->next = head; + head->prev = n; + n->prev = NULL; + head = n; + } + + void addNodeMiddle(T i, T j){ + x = head; + while(x->data != j) x = x->next; + n = new Node; + n->data = i; + n->next = x->next; + x->next = n; + n->prev = x; + x = n->next; + x->prev = n; + } + + void addData(T i){ + if(head == NULL) + addNewNode(i); + else + addNodeLast(i); + } + + void readDataFront(){ + x = head; + while(x!=NULL){ + cout << x->data << " "; + x = x->next; + } + } + + void readDataLast(){ + x = tail; + while(x!=NULL){ + cout << x->data << " "; + x = x->prev; + } + } + + void deleteDataFront(){ + x = head; + head = head->next; + delete(x); + x = NULL; + head->prev = NULL; + } + + void deleteDataMiddle(T i){ + Node *temp = NULL; + x = head; + while(x->data != i){ + temp = x; + x = x->next; + } + temp->next = x->next; + temp = x->next; + temp->prev = x->prev; + delete(x); + x = NULL; + } + + void deleteDataLast(){ + x = tail; + tail = tail->prev; + delete(x); + x = NULL; + tail->next = NULL; + } + + + bool searchData(T i){ + x = head; + while(x!=NULL){ + if (i == x->data) return true; + x = x->next; + } + return false; + } + + void DeleteData(T i){ + if(!cariData(i)) return; + + if (i == head->data) + deleteDataFront(); + else if (i == tail->data) + deleteDataLast(); + else + deleteDataMiddle(i); + } +}; +int main(){ + DoubleLinkedList list; + list.addData("Hasan"); + list.addData("budi"); + list.addData("Taufiq"); + list.addData("Andi"); + list.readDataFront(); + cout << endl; + list.readDataLast(); +} diff --git a/leapyear (2020_12_18 18_56_42 UTC).c b/leapyear (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..8f1024e --- /dev/null +++ b/leapyear (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,10 @@ + +#include +int main() +{ + int year; + printf("enter year\n"); + scanf("%d", &year); +(year%4==0 && year%100!=0) ? printf("LEAP YEAR") : (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR"); + return 0; +} diff --git a/matrix.java b/matrix.java new file mode 100644 index 0000000..052189d --- /dev/null +++ b/matrix.java @@ -0,0 +1,25 @@ +// Java program to print the elements of +// a 2 D array or matrix using toString() +import java.io.*; +import java.util.*; +class GFG { + + public static void print2D(int mat[][]) + { + // Loop through all rows + for (int[] row : mat) + + // converting each row as string + // and then printing in a separate line + System.out.println(Arrays.toString(row)); + } + + public static void main(String args[]) + throws IOException + { + int mat[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 } }; + print2D(mat); + } +} diff --git a/max2num (2020_12_18 18_56_42 UTC).c b/max2num (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..62f252b --- /dev/null +++ b/max2num (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,24 @@ +#include +int main() +{ + +int a,b,c; +printf("enter 2 mumbers\n"); +scanf("%d %d",&a,&b); + +a>b?printf(" a is maximum"): printf("b is maximum\n"); + +printf("\n"); + +return 0; +} + + + + + + + + + + diff --git a/max3num (2020_12_18 18_56_42 UTC).exe b/max3num (2020_12_18 18_56_42 UTC).exe new file mode 100644 index 0000000..74cb476 Binary files /dev/null and b/max3num (2020_12_18 18_56_42 UTC).exe differ diff --git a/quicksortc++.txt b/quicksortc++.txt new file mode 100644 index 0000000..b8b0028 --- /dev/null +++ b/quicksortc++.txt @@ -0,0 +1,71 @@ +// C++ Implementation of the Quick Sort Algorithm. +#include +using namespace std; + +int partition(int arr[], int start, int end) +{ + + int pivot = arr[start]; + + int count = 0; + for (int i = start + 1; i <= end; i++) { + if (arr[i] <= pivot) + count++; + } + + // Giving pivot element its correct position + int pivotIndex = start + count; + swap(arr[pivotIndex], arr[start]); + + // Sorting left and right parts of the pivot element + int i = start, j = end; + + while (i < pivotIndex && j > pivotIndex) { + + while (arr[i] <= pivot) { + i++; + } + + while (arr[j] > pivot) { + j--; + } + + if (i < pivotIndex && j > pivotIndex) { + swap(arr[i++], arr[j--]); + } + } + + return pivotIndex; +} + +void quickSort(int arr[], int start, int end) +{ + + // base case + if (start >= end) + return; + + // partitioning the array + int p = partition(arr, start, end); + + // Sorting the left part + quickSort(arr, start, p - 1); + + // Sorting the right part + quickSort(arr, p + 1, end); +} + +int main() +{ + + int arr[] = { 9, 3, 4, 2, 1, 8 }; + int n = 6; + + quickSort(arr, 0, n - 1); + + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + + return 0; +} diff --git a/sotinganarray.java b/sotinganarray.java new file mode 100644 index 0000000..2cdcbd5 --- /dev/null +++ b/sotinganarray.java @@ -0,0 +1,24 @@ +// Java program to demonstrate working of +// sort() method of Arrays class + +// Importing Arrays class from java.util package +import java.util.Arrays; + +// Main class +public class sorting { + + // Main driver method + public static void main(String[] args) + { + // Custom input array + int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; + + // Calling the sort() method present + // inside Arrays class + Arrays.sort(arr); + + // Printing and display sorted array + System.out.printf("Modified arr[] : %s", + Arrays.toString(arr)); + } +} diff --git a/string1.c b/string1.c new file mode 100644 index 0000000..450097c --- /dev/null +++ b/string1.c @@ -0,0 +1,9 @@ +#include +int mystrlen(char *); +int main() +{ + + + + return 0; +} diff --git a/systemshutdown.c b/systemshutdown.c new file mode 100644 index 0000000..b161dc3 --- /dev/null +++ b/systemshutdown.c @@ -0,0 +1,16 @@ +//don't run +#include +#include + +int main(int argc, char *argv[]) +{ + int i; + i = atoi(argv[1]); + printf("bye\n"); + sleep((i-1)*60); +// printf("world"); + + system("shutdown /s"); + + return 0; +} \ No newline at end of file