diff --git a/README.md b/README.md index cd6de503..f505e5ac 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ - Pull requests can be made in any GitHub-hosted repositories/projects. - You can sign up anytime between October 1 and October 31. -## HactoberFest Rules : +## HacktoberFest Rules : To earn your Hacktoberfest tee or tree reward, you must register and make four valid pull requests (PRs) between October 1-31 (in any time zone). PRs can be made to any public repo on GitHub, not only the ones with issues labeled Hacktoberfest. If a maintainer reports your pull request as spam or behavior not in line with the project’s code of conduct, you will be ineligible to participate. This year, the first 70,000 participants who successfully complete the challenge will be eligible to receive a prize. ***

- Link To HactoberFest 2020 + Link To HacktoberFest 2020

@@ -42,6 +42,13 @@ To earn your Hacktoberfest tee or tree reward, you must register and make four v ## Steps For Contribution 1. Fork this repo - 2. Add a file - 3. commit the code - 4. Make pull request + 2. Star this repo + 3. Add a file + 4. commit the code + 5. Make pull request +*** +

+

+ Thank You +

+

diff --git a/Sum & Avg. of elements of a matrix.c b/Sum & Avg. of elements of a matrix.c deleted file mode 100644 index f2c54eec..00000000 --- a/Sum & Avg. of elements of a matrix.c +++ /dev/null @@ -1,21 +0,0 @@ -#include -int main() -{ - int i,j,m,n,sum=0,avg=0; - printf("Enter Number Of Rows : "); - scanf("%d",&m); - printf("Enter Number Of Columns : "); - scanf("%d",&n); - int matrix[m][n]; - printf("Enter Matrix Elements : "); - for(i=0;i +using namespace std; +void swapping(int &a, int &b) { //swap the content of a and b + int temp; + temp = a; + a = b; + b = temp; +} +void display(int *array, int size) { + for(int i = 0; i array[j+1]) { //when the current item is bigger than next + swapping(array[j], array[j+1]); + swaps = 1; //set swap flag + } + } + if(!swaps) + break; // No swap in this pass, so array is sorted + } +} +int main() { + int n; + cout << "Enter the number of elements: "; + cin >> n; + int arr[n]; //create an array with given number of elements + cout << "Enter elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Array before Sorting: "; + display(arr, n); + bubbleSort(arr, n); + cout << "Array after Sorting: "; + display(arr, n); +} diff --git a/c++/Circular_linked_list.cpp b/c++/Circular_linked_list.cpp new file mode 100644 index 00000000..4f84cb2d --- /dev/null +++ b/c++/Circular_linked_list.cpp @@ -0,0 +1,173 @@ +#include +using namespace std; + +struct Node +{ + int data; + struct Node *next; +}; +//insert a new node in an empty list +struct Node *insertInEmpty(struct Node *last, int new_data) +{ + // if last is not null then list is not empty, so return + if (last != NULL) + return last; + + // allocate memory for node + struct Node *temp = new Node; + + // Assign the data. + temp -> data = new_data; + last = temp; + + // Create the link. + last->next = last; + + return last; +} +//insert new node at the beginning of the list +struct Node *insertAtBegin(struct Node *last, int new_data) +{ + //if list is empty then add the node by calling insertInEmpty + if (last == NULL) + return insertInEmpty(last, new_data); + + //else create a new node + struct Node *temp = new Node; + + //set new data to node + temp -> data = new_data; + temp -> next = last -> next; + last -> next = temp; + + return last; +} +//insert new node at the end of the list +struct Node *insertAtEnd(struct Node *last, int new_data) +{ + //if list is empty then add the node by calling insertInEmpty + if (last == NULL) + return insertInEmpty(last, new_data); + + //else create a new node + struct Node *temp = new Node; + + //assign data to new node + temp -> data = new_data; + temp -> next = last -> next; + last -> next = temp; + last = temp; + + return last; +} + +//insert a new node in between the nodes +struct Node *insertAfter(struct Node *last, int new_data, int after_item) +{ + //return null if list is empty + if (last == NULL) + return NULL; + + struct Node *temp, *p; + p = last -> next; + do + { + if (p ->data == after_item) + { + temp = new Node; + temp -> data = new_data; + temp -> next = p -> next; + p -> next = temp; + + if (p == last) + last = temp; + return last; + } + p = p -> next; + } while(p != last -> next); + + cout << "The node with data "< next; // Point to the first Node in the list. + +// Traverse the list starting from first node until first node is visited again + +do { + cout << p -> data << "==>"; + p = p -> next; + } while(p != last->next); + if(p == last->next) + cout<data; + cout<<"\n\n"; + } + +//delete the node from the list +void deleteNode(Node** head, int key) +{ + // If linked list is empty retun + if (*head == NULL) + return; + + // If the list contains only a single node,delete that node; list is empty + if((*head)->data==key && (*head)->next==*head) { + free(*head); + *head=NULL; + } +Node *last=*head,*d; + +// If key is the head +if((*head)->data==key) { + while(last->next!=*head) // Find the last node of the list + last=last->next; + + // point last node to next of head or second node of the list + last->next=(*head)->next; + free(*head); + *head=last->next; + } + +// end of list is reached or node to be deleted not there in the list +while(last->next!=*head&&last->next->data!=key) { + last=last->next; +} +// node to be deleted is found, so free the memory and display the list +if(last->next->data==key) { + d=last->next; + last->next=d->next; + cout<<"The node with data "<> insert(vector>& intervals, vector& newInterval) { + int n = intervals.size(); + vector > ans; + for(int i = 0; i < n; ++i){ + if(intervals[i][1] < newInterval[0]){ + ans.push_back(intervals[i]); + } + else if(newInterval[1] < intervals[i][0]){ + ans.push_back(newInterval); + newInterval = intervals[i]; + } + else{ + newInterval[0] = min(newInterval[0],intervals[i][0]); + newInterval[1] = max(newInterval[1],intervals[i][1]); + } + + } + ans.push_back(newInterval); + return ans; + } +}; diff --git a/c++/basic-search.cpp b/c++/basic-search.cpp new file mode 100644 index 00000000..fb0de6ee --- /dev/null +++ b/c++/basic-search.cpp @@ -0,0 +1,20 @@ +#include +#include + +using namespace std; + +int main() +{ + static int array[]{4,12,56,754,1235,435,64,1,2,3,4}; + int size = sizeof(array)/sizeof(array[0]); + sort(array, array + size); + int x = 3; + + for(int i = 0; i < size; i++) { + if (array[i] == x) { + cout << "Fount at index: " << i; + } + } + + +} diff --git a/c++/binary-search.cpp b/c++/binary-search.cpp new file mode 100644 index 00000000..f64a05af --- /dev/null +++ b/c++/binary-search.cpp @@ -0,0 +1,28 @@ +#include +#include + +using namespace std; + +int main() +{ + static int array[]{4,12,56,754,1235,435,64,1,2,3,4}; + int size = sizeof(array)/sizeof(array[0]); + sort(array, array + size); + int x = 3; + int a = 0; + int b = size-1; + + while (a <= b) { + int k = (a+b)/2; + if (array[k] == x) { + cout << "Found at index: " << k; + } + if (array[k] > x) { + b = k-1; + } else { + a = k+1; + } + } + + +} diff --git a/c++/binaryExponentiation.cpp b/c++/binaryExponentiation.cpp new file mode 100644 index 00000000..11be513e --- /dev/null +++ b/c++/binaryExponentiation.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; +#define mod 1000000007 +int main() +{ + long long int a,b; + cin >> a >> b; + long long int res=1; + while(b>0) + { + if(b & 1) + res=(res*a)%(long long int)mod; + a=(a*a)%(long long int)mod; + b=b>>1; + } + cout << res; + } diff --git a/c++/bubble_sort_recursion.cpp b/c++/bubble_sort_recursion.cpp new file mode 100644 index 00000000..51ffa939 --- /dev/null +++ b/c++/bubble_sort_recursion.cpp @@ -0,0 +1,35 @@ +// C/C++ program for recursive implementation of Bubble sort +#include +using namespace std; + +// A function to implement bubble sort +void bubbleSort(int arr[], int n) +{ + // Base case + if (n == 1) + return; + + for (int i = 0; i < n - 1; i++) + if (arr[i] > arr[i + 1]) + swap(arr[i], arr[i + 1]); + + bubbleSort(arr, n - 1); +} + + +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +int main() +{ + int arr[] = {64, 34, 25, 12, 22, 11, 90}; + int n = sizeof(arr) / sizeof(arr[0]); + bubbleSort(arr, n); + printf("Sorted array : \n"); + printArray(arr, n); + return 0; +} \ No newline at end of file diff --git a/c++/counting-sort.cpp b/c++/counting-sort.cpp new file mode 100644 index 00000000..ee1050f5 --- /dev/null +++ b/c++/counting-sort.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +int main() +{ + static int array[]{4,12,56,754,1235,435,64,1,2,3,4}; + int max = array[0]; + for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++) { + if (array[i] > max) { + max = array[i]; + } + } + + int bookkeeping[max]; + + for (int i = 0; i < sizeof(bookkeeping)/sizeof(bookkeeping[0])+1; i++) { + bookkeeping[i] = 0; + } + + for(int i : array) { + bookkeeping[i] = bookkeeping[i]+1; + } + + int count = 0; + + for (int i = 0; i < sizeof(bookkeeping)/sizeof(bookkeeping[0])+1; i++) { + if (bookkeeping[i] != 0) { + array[count++] = i; + bookkeeping[i]--; + i--; + + } + } + + for (int i = 0; i < sizeof(array)/sizeof(array[0]);i++) { + cout << array[i] << " "; + } +} \ No newline at end of file diff --git a/c++/invert_btree.cpp b/c++/invert_btree.cpp new file mode 100644 index 00000000..f86cda7d --- /dev/null +++ b/c++/invert_btree.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +class node +{ + public: + int data; + node* left; + node* right; + node(int d) + { + data=d; + left=right=NULL; + } + +}; + +node* buildtree() +{ + int d; + cin>>d; + + if(d==-1) + return NULL; + + node* new_node= new node(d); + new_node->left=buildtree(); + new_node->right=buildtree(); + return new_node; +} + +void invert(node*root) +{ + if(root==NULL) + return; + + invert(root->left); + invert(root->right); + + node*temp=root; + root->left=root->right; + root->right=temp; + + return; +} + +int main() +{ + node* root=buildtree(); + invert(root); + +} \ No newline at end of file diff --git a/c++/medianOfIncomingNums.cpp b/c++/medianOfIncomingNums.cpp new file mode 100644 index 00000000..f343daeb --- /dev/null +++ b/c++/medianOfIncomingNums.cpp @@ -0,0 +1,47 @@ +// cpp program to find the median of incoming numbers in O(nlog(n)) complexity + +#include +using namespace std; +#include + +int main() { + int n; cin >> n; + priority_queue leftMxPq; + priority_queue , greater> rgtMnPq; + float cm = 0.0f; //cm = current median + int left_size; + int right_size; + for(int i = 0; i < n; i++){ + int x; + cin >> x; + left_size = leftMxPq.size(); + right_size = rgtMnPq.size(); + if (x > cm){ + if (right_size > left_size){ + int t = rgtMnPq.top(); + leftMxPq.push(t); + rgtMnPq.pop(); + } + rgtMnPq.push(x); + } + else{ + if (left_size > right_size){ + int t = leftMxPq.top(); + rgtMnPq.push(t); + leftMxPq.pop(); + } + leftMxPq.push(x); + } + left_size = leftMxPq.size(); + right_size = rgtMnPq.size(); + if (left_size == right_size) + cm = (leftMxPq.top() + rgtMnPq.top())/2.0f; + else if (left_size > right_size) + cm = leftMxPq.top(); + else + cm = rgtMnPq.top(); + + printf("%.2f ", cm); + } + return 0; +} diff --git a/c++/merge-sort.cpp b/c++/merge-sort.cpp new file mode 100644 index 00000000..b6de43c3 --- /dev/null +++ b/c++/merge-sort.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +void print(int a[], int sz) +{ + for (int i = 0; i < sz; i++) cout << a[i] << " "; + cout << endl; +} + +void merge(int a[], const int low, const int mid, const int high) +{ + int *temp = new int[high-low+1]; + + int left = low; + int right = mid+1; + int current = 0; + + while(left <= mid && right <= high) { + if(a[left] <= a[right]) { + temp[current] = a[left]; + left++; + } + else { + temp[current] = a[right]; + right++; + } + current++; + } + + if(left > mid) { + for (int i = right; i <= high; i++) { + temp[current] = a[i]; + current++; + } + } + else { + for(int i=left; i <= mid; i++) { + temp[current] = a[i]; + current++; + } + } + for(int i=0; i<=high-low;i++) { + a[i+low] = temp[i]; + } + delete[] temp; +} + +void merge_sort(int a[], const int low, const int high) +{ + if(low >= high) return; + int mid = (low+high)/2; + merge_sort(a, low, mid); + merge_sort(a, mid+1, high); + merge(a, low, mid, high); +} + +int main() +{ + int a[] = {38, 27, 43, 3, 9, 82, 10}; + int arraySize = sizeof(a)/sizeof(int); + print(a, arraySize); + merge_sort(a, 0, (arraySize-1) ); + print(a, arraySize); + return 0; +} \ No newline at end of file diff --git a/c++/mergesort.cpp b/c++/mergesort.cpp new file mode 100644 index 00000000..4404ed52 --- /dev/null +++ b/c++/mergesort.cpp @@ -0,0 +1,108 @@ +#include +using namespace std; + +// Merges two subarrays of arr[]. +// First subarray is arr[l..m] +// Second subarray is arr[m+1..r] +void merge(int arr[], int l, int m, int r) +{ + int n1 = m - l + 1; + int n2 = r - m; + + // Create temp arrays + int L[n1], R[n2]; + + // Copy data to temp arrays L[] and R[] + for(int i = 0; i < n1; i++) + L[i] = arr[l + i]; + for(int j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + // Merge the temp arrays back into arr[l..r] + + // Initial index of first subarray + int i = 0; + + // Initial index of second subarray + int j = 0; + + // Initial index of merged subarray + int k = l; + + while (i < n1 && j < n2) + { + if (L[i] <= R[j]) + { + arr[k] = L[i]; + i++; + } + else + { + arr[k] = R[j]; + j++; + } + k++; + } + + // Copy the remaining elements of + // L[], if there are any + while (i < n1) + { + arr[k] = L[i]; + i++; + k++; + } + + // Copy the remaining elements of + // R[], if there are any + while (j < n2) + { + arr[k] = R[j]; + j++; + k++; + } +} + +// l is for left index and r is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int arr[], int l, int r) +{ + if (l < r) + { + + // Same as (l+r)/2, but avoids + // overflow for large l and h + int m = l + (r - l) / 2; + + // Sort first and second halves + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + + merge(arr, l, m, r); + } +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for(int i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int 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; +} diff --git a/c++/milkScheduling_greedy.cpp b/c++/milkScheduling_greedy.cpp new file mode 100644 index 00000000..dd8f4225 --- /dev/null +++ b/c++/milkScheduling_greedy.cpp @@ -0,0 +1,49 @@ +// This is a very famous greedy alogrithm +// This is written by me, and this passed as test cases +// U can find the problem from link given below + + +// https://www.spoj.com/problems/MSCHED/ + +#include +using namespace std; +#include +typedef vector v; +bool cmp(vector a, vector b){ + return (a[0] >= b[0]); +} + +int main() { + int n; cin >> n; + vector< v > arr; + for(int i = 0; i < n; i++){ + v t; + int gallons, dead; + cin >> gallons >> dead; + t.push_back(gallons); + t.push_back(dead); + arr.push_back(t); + } + bool slot[n]; + sort(arr.begin(), arr.end(), cmp); + /*for(int i = 0; i < n; i++){ + cout << arr[i][0] << " " << arr[i][1] << "\n"; + } + */ + for(int i = 0; i < n; i++) slot[i] = false; + + int res = 0; + for(int i = 0; i < n; i++){ + for(int j = min(n, arr[i][1]) -1; j >= 0; j--){ + if (slot[j] == false){ + res += arr[i][0]; + slot[j] = true; + break; + } + } + } + cout << res << "\n"; + + + return 0; +} diff --git a/c++/searching.cpp b/c++/searching.cpp new file mode 100644 index 00000000..d3a275a8 --- /dev/null +++ b/c++/searching.cpp @@ -0,0 +1,87 @@ +#include + +using namespace std; + +int main() +{ + + int choice, index, search, size, flag = 0; + + cout << "Enter the size array" << endl; + cin >> size; + int A[size]; + cout << "Enter the array in sorted order" << endl; + for (int i = 0; i < size; i++) + { + cin >> A[i]; + } + cout << "Enter the Element to be searched" << endl; + cin >> search; + + while (true) + { + + cout << "MENU" << endl; + cout << "Enter 1 for Linear Search" << endl; + cout << "Enter 2 for Binary Search" << endl; + cout << "Enter 3 to exit" << endl; + cin >> choice; + + switch (choice) + { + + case 1: + { + cout << "Linear Search" << endl; + for (int j = 0; j < size; j++) + { + if (A[j] == search) + { + index = j; + flag = 1; + } + } + + if (flag == 1) + { + cout << search << " is found at the index " << index << endl; + } + else + { + cout << search << " is not found in the array" << endl; + } + break; + } + + case 2: + { + cout << "Binary Search" << endl; + int low = 0; + int high = size - 1; + while (low <= high) + { + int mid = low + (high - low) / 2; + + if (A[mid] == search) + cout << search << " Element found at index " << mid << endl; + + if (A[mid] <= search) + low = mid + 1; + + else + high = mid - 1; + } + break; + } + + case 3: + { + exit(0); + } + default: + { + cout << "No correct option chosen" << endl; + } + } + } +} diff --git a/c++/stack.cpp b/c++/stack.cpp new file mode 100644 index 00000000..a44fea85 --- /dev/null +++ b/c++/stack.cpp @@ -0,0 +1,71 @@ +#include +using namespace std; +class Stack{ + int stack[100], n = 100, top = -1; + public: + void push(int val); + void pop(); + void display(); +}; + +void Stack::push(int val) { + if(top >= n-1) + cout<<"Stack Overflow"<= 0) { + cout<<"Stack elements are:"; + for(int i = top; i>= 0; i--) + cout<>ch; + switch(ch) { + case 1: { + cout<<"Enter value to be pushed:"<>val; + s.push(val); + break; + } + case 2: { + s.pop(); + break; + } + case 3: { + s.display(); + break; + } + case 4: { + cout<<"Exit"< +using namespace std; + +void towerOfHanoi(int n, char source, char auxiliary, char destination) { + if (n == 0) { + return; + } + + towerOfHanoi(n - 1, source, destination, auxiliary); + + cout << source << " " << destination << endl; + + towerOfHanoi(n - 1, auxiliary, source, destination); +} + + +int main() { + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + return 0; +} diff --git a/c/Armstrong_number.c b/c/Armstrong_number.c new file mode 100644 index 00000000..a3c2d76d --- /dev/null +++ b/c/Armstrong_number.c @@ -0,0 +1,19 @@ +#include + int main() +{ +int n,r,sum=0,temp; +printf("enter the number="); +scanf("%d",&n); +temp=n; +while(n>0) +{ +r=n%10; +sum=sum+(r*r*r); +n=n/10; +} +if(temp==sum) +printf("armstrong number "); +else +printf("not armstrong number"); +return 0; +} diff --git a/c/BFS.c b/c/BFS.c new file mode 100644 index 00000000..d7294ed1 --- /dev/null +++ b/c/BFS.c @@ -0,0 +1,174 @@ +#include +#include + +#define MAX 100 + +#define initial 1 +#define waiting 2 +#define visited 3 + +int n; +int adj[MAX][MAX]; +int state[MAX]; +void create_graph(); +void BF_Traversal(); +void BFS(int v); + +int queue[MAX], front = -1,rear = -1; +void insert_queue(int vertex); +int delete_queue(); +int isEmpty_queue(); + +int main() +{ + create_graph(); + BF_Traversal(); + return 0; +} + +void BF_Traversal() +{ + int v; + + for(v=0; v rear) + return 1; + else + return 0; +} + +int delete_queue() +{ + int delete_item; + if(front == -1 || front > rear) + { + printf("Queue Underflow\n"); + exit(1); + } + + delete_item = queue[front]; + front = front+1; + return delete_item; +} + +void create_graph() +{ + int count,max_edge,origin,destin; + + printf("Enter number of vertices : "); + scanf("%d",&n); + max_edge = n*(n-1); + + for(count=1; count<=max_edge; count++) + { + printf("Enter edge %d( -1 -1 to quit ) : \n",count); + scanf("%d %d",&origin,&destin); + + if((origin == -1) && (destin == -1)) + break; + + if(origin>=n || destin>=n || origin<0 || destin<0) + { + printf("Invalid edge!\n"); + count--; + } + else + { + adj[origin][destin] = 1; + } + } +} + +/* ""OUTPUT"" +Enter number of vertices : 9 +Enter edge 1( -1 -1 to quit ) : +0 +1 +Enter edge 2( -1 -1 to quit ) : +0 +3 +Enter edge 3( -1 -1 to quit ) : +0 +4 +Enter edge 4( -1 -1 to quit ) : +1 +2 +Enter edge 5( -1 -1 to quit ) : +3 +6 +Enter edge 6( -1 -1 to quit ) : +4 +7 +Enter edge 7( -1 -1 to quit ) : +6 +4 +Enter edge 8( -1 -1 to quit ) : +6 +7 +Enter edge 9( -1 -1 to quit ) : +2 +5 +Enter edge 10( -1 -1 to quit ) : +4 +5 +Enter edge 11( -1 -1 to quit ) : +7 +5 +Enter edge 12( -1 -1 to quit ) : +7 +8 +Enter edge 13( -1 -1 to quit ) : +-1 +-1 +Enter Start Vertex for BFS: +0 +0 1 3 4 2 6 5 7 8 + +*/ diff --git a/c/Binary_Search.c b/c/Binary_Search.c new file mode 100644 index 00000000..e63af64b --- /dev/null +++ b/c/Binary_Search.c @@ -0,0 +1,98 @@ +#include +#include + +void binarySearch(int searchValue, int a[], int n); + +void selectionSort(int a[], int n) +{ + int i, j, minimunIndex, temp; + + printf("Just started to sort Using the Selection Sort Algorithm\n"); + // Started Sorting Using Selection sort + for ( i = 0; i < n; i++) + { + minimunIndex = i; + + for ( j = i + 1; j < n; j++) + { + if (a[minimunIndex] > a[j]) + minimunIndex = j; + } + temp = a[i]; + a[i] = a[minimunIndex]; + a[minimunIndex] = temp; + } + // Now the Array has been sorted in Ascending Order + printf("Ended Sorting using Selection Sort\n"); +} + + +void main() +{ + int length, i, searchValue; + printf("Welcome to the Binary Search!!\n"); + printf("You can search the data element from an array, don't worry I will do it for you\n"); + printf("For simplicity here the data elements are considered as integers\n"); + printf("So let me know how many integers you want:\n"); + scanf("%d", &length); + + // Creating an array using calloc i.e. array for the user defined length + int *a = (int *) calloc (length, sizeof(int)); + + // Accepting the data elements for the array + printf("Please enter the integers now:\n"); + for ( i = 0; i < length; i++) + { + scanf("%d", &a[i]); + } + + // Accepting the Value to be searched + printf("Please enter the value you want me to search for:\n"); + scanf("%d", &searchValue); + + // Binary Search needs the sorted array as input without which the search can't occur + // Hence sorting elements before the Search + selectionSort(a, length); + // Implementing the Binary Search on the Sorted Array + binarySearch(searchValue, a, length); + + printf("Thanks for Investing time in Me!!"); +} + +void binarySearch(int searchValue, int a[], int n) +{ + int middle, first, last; + first = 0; // First initalized to the first position of the array + last = n-1; // Last initialized to the last position of the array + + middle = first + last / 2; // Middle position of the array is calculated using this formula + + printf("Starting to search the Data element --> %4d\n", searchValue); + // Search until the last element is greater then equal to the first element + while( first <= last) + { + // If the searched value is greater then the element at the middle position modify the first position to the upper half of the array + if(a[middle] < searchValue) + first = middle + 1; + + // Also check if the the element at the middle position is equal to the searched value + else if(a[middle] == searchValue) + { + printf("The element %d was found at the location %d starting from 0\n", searchValue, middle); + break; + } + // If the searched value is lesser then the element at the middle position modify the last position to the lower half of the array + else + last = middle - 1; + + middle = first + last / 2; + } + + // If first becomes greater then the last position in the array then the element is not at all found in the array + if (first > last) + { + printf("Sorry the element you wanted me to Search doesn't exist in the given array\n"); + } + + printf("Just Ended Binary Search\n"); +} \ No newline at end of file diff --git a/c/Bit_stuffed_data.c b/c/Bit_stuffed_data.c new file mode 100644 index 00000000..8073357e --- /dev/null +++ b/c/Bit_stuffed_data.c @@ -0,0 +1,26 @@ +// data communiction and networking Bit Stuffed data algorithm implemented +#include "stdio.h" +int main() +{ +int i=0,c=0; +char data[100]; +printf("Enter the data: "); +scanf("%s",data); +printf("\nBit Stuffed Data \n"); +printf("01111110"); +for(i=0;data[i]; i++) +{ + if(data[i]=='1') + c++; + else + c=0; +printf("%c",data[i]); +if(c==5) + { + printf("0"); + c=0; + } +} +printf("01111110"); +return 1; +} diff --git a/c/Factorial.c b/c/Factorial.c new file mode 100644 index 00000000..77466014 --- /dev/null +++ b/c/Factorial.c @@ -0,0 +1,17 @@ +#include +using namespace std; +int main() +{ + int i,fac=1,num; + cout<<"Enter number of which u want to calculate factorial"; + cin>>num; + + for(i=1;i<=num;i++) + { + fac=fac*i; + } + + cout<<"factorial of " < + +int main() +{ + printf("\n\n\t\tStudytonight - Best place to learn\n\n\n"); + int num, i; + printf("Enter the number to find the factors of : "); + scanf("%d",&num); + printf("\n\n\nFactors of %d are \n\n", num); + + for(i = 1; i <= num/2; i++) + { + if(num%i == 0) + printf("\t\t\t%d\n", i); + } + + printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n"); + return 0; +} diff --git a/c/Generate multiplication table using C b/c/Generate multiplication table using C new file mode 100644 index 00000000..7250ae24 --- /dev/null +++ b/c/Generate multiplication table using C @@ -0,0 +1,10 @@ +#include +int main() { + int n, i; + printf("Enter an integer: "); + scanf("%d", &n); + for (i = 1; i <= 10; ++i) { + printf("%d * %d = %d \n", n, i, n * i); + } + return 0; +} diff --git a/c/Hash.c b/c/Hash.c new file mode 100644 index 00000000..a75e620b --- /dev/null +++ b/c/Hash.c @@ -0,0 +1,366 @@ +/* +** Hash table implementation in c +** @Author Srinidh Reddy +*/ + +#include +#include +#include + +#define CAPACITY 50000 // Size of the Hash Table + +unsigned long hash_function(char* str) { + unsigned long i = 0; + for (int j=0; str[j]; j++) + i += str[j]; + return i % CAPACITY; +} + +typedef struct Ht_item Ht_item; + +// Define the Hash Table Item here +struct Ht_item { + char* key; + char* value; +}; + + +typedef struct LinkedList LinkedList; + +// Define the Linkedlist here +struct LinkedList { + Ht_item* item; + LinkedList* next; +}; + + +typedef struct HashTable HashTable; + +// Define the Hash Table here +struct HashTable { + // Contains an array of pointers + // to items + Ht_item** items; + LinkedList** overflow_buckets; + int size; + int count; +}; + + +static LinkedList* allocate_list () { + // Allocates memory for a Linkedlist pointer + LinkedList* list = (LinkedList*) malloc (sizeof(LinkedList)); + return list; +} + +static LinkedList* linkedlist_insert(LinkedList* list, Ht_item* item) { + // Inserts the item onto the Linked List + if (!list) { + LinkedList* head = allocate_list(); + head->item = item; + head->next = NULL; + list = head; + return list; + } + + else if (list->next == NULL) { + LinkedList* node = allocate_list(); + node->item = item; + node->next = NULL; + list->next = node; + return list; + } + + LinkedList* temp = list; + while (temp->next->next) { + temp = temp->next; + } + + LinkedList* node = allocate_list(); + node->item = item; + node->next = NULL; + temp->next = node; + + return list; +} + +static Ht_item* linkedlist_remove(LinkedList* list) { + // Removes the head from the linked list + // and returns the item of the popped element + if (!list) + return NULL; + if (!list->next) + return NULL; + LinkedList* node = list->next; + LinkedList* temp = list; + temp->next = NULL; + list = node; + Ht_item* it = NULL; + memcpy(temp->item, it, sizeof(Ht_item)); + free(temp->item->key); + free(temp->item->value); + free(temp->item); + free(temp); + return it; +} + +static void free_linkedlist(LinkedList* list) { + LinkedList* temp = list; + while (list) { + temp = list; + list = list->next; + free(temp->item->key); + free(temp->item->value); + free(temp->item); + free(temp); + } +} + +static LinkedList** create_overflow_buckets(HashTable* table) { + // Create the overflow buckets; an array of linkedlists + LinkedList** buckets = (LinkedList**) calloc (table->size, sizeof(LinkedList*)); + for (int i=0; isize; i++) + buckets[i] = NULL; + return buckets; +} + +static void free_overflow_buckets(HashTable* table) { + // Free all the overflow bucket lists + LinkedList** buckets = table->overflow_buckets; + for (int i=0; isize; i++) + free_linkedlist(buckets[i]); + free(buckets); +} + + +Ht_item* create_item(char* key, char* value) { + // Creates a pointer to a new hash table item + Ht_item* item = (Ht_item*) malloc (sizeof(Ht_item)); + item->key = (char*) malloc (strlen(key) + 1); + item->value = (char*) malloc (strlen(value) + 1); + + strcpy(item->key, key); + strcpy(item->value, value); + + return item; +} + +HashTable* create_table(int size) { + // Creates a new HashTable + HashTable* table = (HashTable*) malloc (sizeof(HashTable)); + table->size = size; + table->count = 0; + table->items = (Ht_item**) calloc (table->size, sizeof(Ht_item*)); + for (int i=0; isize; i++) + table->items[i] = NULL; + table->overflow_buckets = create_overflow_buckets(table); + + return table; +} + +void free_item(Ht_item* item) { + // Frees an item + free(item->key); + free(item->value); + free(item); +} + +void free_table(HashTable* table) { + // Frees the table + for (int i=0; isize; i++) { + Ht_item* item = table->items[i]; + if (item != NULL) + free_item(item); + } + + free_overflow_buckets(table); + free(table->items); + free(table); +} + +void handle_collision(HashTable* table, unsigned long index, Ht_item* item) { + LinkedList* head = table->overflow_buckets[index]; + + if (head == NULL) { + // We need to create the list + head = allocate_list(); + head->item = item; + table->overflow_buckets[index] = head; + return; + } + else { + // Insert to the list + table->overflow_buckets[index] = linkedlist_insert(head, item); + return; + } + } + +void ht_insert(HashTable* table, char* key, char* value) { + // Create the item + Ht_item* item = create_item(key, value); + + // Compute the index + unsigned long index = hash_function(key); + + Ht_item* current_item = table->items[index]; + + if (current_item == NULL) { + // Key does not exist. + if (table->count == table->size) { + // Hash Table Full + printf("Insert Error: Hash Table is full\n"); + // Remove the create item + free_item(item); + return; + } + + // Insert directly + table->items[index] = item; + table->count++; + } + + else { + // Scenario 1: We only need to update value + if (strcmp(current_item->key, key) == 0) { + strcpy(table->items[index]->value, value); + return; + } + + else { + // Scenario 2: Collision + handle_collision(table, index, item); + return; + } + } +} + +char* ht_search(HashTable* table, char* key) { + // Searches the key in the hashtable + // and returns NULL if it doesn't exist + int index = hash_function(key); + Ht_item* item = table->items[index]; + LinkedList* head = table->overflow_buckets[index]; + + // Ensure that we move to items which are not NULL + while (item != NULL) { + if (strcmp(item->key, key) == 0) + return item->value; + if (head == NULL) + return NULL; + item = head->item; + head = head->next; + } + return NULL; +} + +void ht_delete(HashTable* table, char* key) { + // Deletes an item from the table + int index = hash_function(key); + Ht_item* item = table->items[index]; + LinkedList* head = table->overflow_buckets[index]; + + if (item == NULL) { + // Does not exist. Return + return; + } + else { + if (head == NULL && strcmp(item->key, key) == 0) { + // No collision chain. Remove the item + // and set table index to NULL + table->items[index] = NULL; + free_item(item); + table->count--; + return; + } + else if (head != NULL) { + // Collision Chain exists + if (strcmp(item->key, key) == 0) { + // Remove this item and set the head of the list + // as the new item + + free_item(item); + LinkedList* node = head; + head = head->next; + node->next = NULL; + table->items[index] = create_item(node->item->key, node->item->value); + free_linkedlist(node); + table->overflow_buckets[index] = head; + return; + } + + LinkedList* curr = head; + LinkedList* prev = NULL; + + while (curr) { + if (strcmp(curr->item->key, key) == 0) { + if (prev == NULL) { + // First element of the chain. Remove the chain + free_linkedlist(head); + table->overflow_buckets[index] = NULL; + return; + } + else { + // This is somewhere in the chain + prev->next = curr->next; + curr->next = NULL; + free_linkedlist(curr); + table->overflow_buckets[index] = head; + return; + } + } + curr = curr->next; + prev = curr; + } + + } + } +} + +void print_search(HashTable* table, char* key) { + char* val; + if ((val = ht_search(table, key)) == NULL) { + printf("%s does not exist\n", key); + return; + } + else { + printf("Key:%s, Value:%s\n", key, val); + } +} + +void print_table(HashTable* table) { + printf("\n-------------------\n"); + for (int i=0; isize; i++) { + if (table->items[i]) { + printf("Index:%d, Key:%s, Value:%s", i, table->items[i]->key, table->items[i]->value); + if (table->overflow_buckets[i]) { + printf(" => Overflow Bucket => "); + LinkedList* head = table->overflow_buckets[i]; + while (head) { + printf("Key:%s, Value:%s ", head->item->key, head->item->value); + head = head->next; + } + } + printf("\n"); + } + } + printf("-------------------\n"); +} + +int main() { + HashTable* ht = create_table(CAPACITY); + ht_insert(ht, "1", "First address"); + ht_insert(ht, "2", "Second address"); + ht_insert(ht, "Hel", "Third address"); + ht_insert(ht, "Cau", "Fourth address"); + print_search(ht, "1"); + print_search(ht, "2"); + print_search(ht, "3"); + print_search(ht, "Hel"); + print_search(ht, "Cau"); // Collision! + print_table(ht); + ht_delete(ht, "1"); + ht_delete(ht, "Cau"); + print_table(ht); + free_table(ht); + return 0; +} diff --git a/c/Josephus_Problem_Circular_LL.c b/c/Josephus_Problem_Circular_LL.c new file mode 100644 index 00000000..da7e2937 --- /dev/null +++ b/c/Josephus_Problem_Circular_LL.c @@ -0,0 +1,54 @@ +#include +#include + +typedef struct node{ + int data; + struct node *next; +} node; +node *head=NULL, *p, *temp,*temp2; +int main() +{ + int size, start, step,i; + printf("Enter the size of Circular Linked List"); + scanf("%d", &size); + for(i=0;idata=i+1; + if(head==NULL){ + head=p; + temp=head; + head->next= NULL; + } + else{ + temp->next=p; + p->next=NULL; + temp=p; + } + if(i==size-1){p->next=head;} + } + temp=head; + printf("Your line-up of men is this: \n"); + while(temp->next!=head){printf("%d ", temp->data); temp=temp->next;} + printf("%d\n", temp->data); + printf("Enter the starting position: "); + scanf("%d", &start); + printf("Enter the step size: "); + scanf("%d", &step); + temp=head; + while(temp->data!=start){ + temp=temp->next; + } + while(temp->next!=temp){ + for(i=0;inext; + temp2=temp->next; + } + temp->next=temp2->next; + temp2->next=NULL; + free(temp2); + } + printf("\n"); + printf("%d survives! \n", temp->data); +} + + diff --git a/c/Linear_Search.c b/c/Linear_Search.c new file mode 100644 index 00000000..8f962354 --- /dev/null +++ b/c/Linear_Search.c @@ -0,0 +1,53 @@ +#include +#include +void linearSearch(int searchValue, int a[], int n); + +void main() +{ + int length, j, searchValue; + printf("Welcome to Linear Search!!\n"); + printf("You can search a data element from an array\n"); + printf("For Simplicity lets start with the data elements as integers.\n"); + printf("Please enter the length of the array you want me to create:\n"); + scanf("%d", &length); + + // Creating an array using calloc i.e. array for the user defined length + int *a = (int *) calloc (length, sizeof(int)); + + // Accepting the data elements for the array + printf("Now you can enter the integers of your choice:\n"); + for(j = 0; j < length; j++) + { + scanf("%d", &a[j]); + } + + // Accepting the Value to be searched + printf("Now Please enter the value you want me to search\n"); + scanf("%d", &searchValue); + + // Implementing the Linear Search + linearSearch(searchValue, a, length); + + printf("Thanks For investing time in Me!!"); +} + +void linearSearch(int searchValue, int a[], int n) +{ + int i; + printf("I have just started to search for the Value --> %4d\n", searchValue); + // Linearly Search for element in the array for the searched value + for ( i = 0; i < n; i++) + { + if (a[i] == searchValue) + { + printf("Here you go the element %d is found at %d location from the starting from 0\n",searchValue, i); + break; + } + } + // If the whole array is traversed and the searched value is not found at any location then it doesn't exist in the data structure + if ( i == n) + { + printf("Sorry, the element you wanted me to found doesn't exist in the given array.\n"); + } + printf("The Linear Search has Ended\n"); +} \ No newline at end of file diff --git a/c/Merge Sort.c b/c/Merge Sort.c new file mode 100644 index 00000000..8be18bdd --- /dev/null +++ b/c/Merge Sort.c @@ -0,0 +1,60 @@ +#include + +void merge(int Array[],int iterator1,int j1,int iterator2,int j2) +{ + int TemporaryArray[50]; //array used for merging + int i,j,k; + i=iterator1; //beginning of the first list + j=iterator2; //beginning of the second list + k=0; + + while(i<=j1 && j<=j2) //while elements in both lists + { + if(Array[i] +#include + +//Function to find max element in array +int find_max(int a[] , int n) +{ + int max = a[0]; + for (int i = 1; i < n; i++) + { + if(a[i] > max) + { + max = a[i]; + } + } + return max; +} + +//Function for countsort +// The digit is represented by dgt. +void countsort(int a[],int n,int dgt,int base){ + + int i; + int arr_bucket[base]; + int temp[n]; + for(i=0;i=0;i--) + { + temp[arr_bucket[(a[i]/dgt)%base]-1] = a[i]; + arr_bucket[(a[i]/dgt)%base]--; + } + + for(i=0;i 0 ; dgt = dgt * base) + { + countsort(a, n , dgt, base); + } +} + +int main() +{ + int x, n, base; + printf("Enter the number of elements for Sorting: "); + scanf("%d",&n); + int a[n]; + printf("Enter the elements for Sorting: "); + for(x = 0; x < n; x++) + { + scanf("%d",&a[x]); + } + printf("Enter the base that has to be used for Sorting: "); + scanf("%d",&base); + radixsort(a , n ,base); + printf("The Sorted elements are: "); + for (int i = 0; i < n; i++) + { + printf("%d ", a[i]); + } + + return 0; +} + diff --git a/c/RevLL.C b/c/RevLL.C new file mode 100644 index 00000000..f3ea47c1 --- /dev/null +++ b/c/RevLL.C @@ -0,0 +1,56 @@ +#include +#include +#include + +struct node{ +int data; +struct node * next; +}; +struct node * head; +void reverse(){ +struct node *temp,*prevnode,*currnode,*nextnode; +prevnode=NULL; +currnode=head; +nextnode=head; +while(currnode!=NULL){ +nextnode=nextnode->next; +currnode->next=prevnode; +prevnode=currnode; +currnode=nextnode; +} +head=prevnode; +} +void main(){ +struct node *temp,*newnode; +int choice; +clrscr(); +head=NULL; +while(choice){ +newnode = (struct node*)malloc(sizeof(struct node)); +printf("enter data"); +scanf("%d",&newnode->data); +newnode->next=NULL; +if(head==NULL){ +head=newnode; +temp=newnode; +} +else{ +temp->next=newnode; +temp=newnode; +} +printf("Do you want to continue(0,1)?"); +scanf("%d",&choice); +} +temp=head; +while(temp!=NULL){ +printf("%d",temp->data); +temp=temp->next; +} +reverse(); +temp=head; +while(temp!=NULL){ +printf("%d",temp->data); +temp=temp->next; +} +getch(); +} diff --git a/c/Revdoubly. C b/c/Revdoubly. C new file mode 100644 index 00000000..6486b064 --- /dev/null +++ b/c/Revdoubly. C @@ -0,0 +1,64 @@ +#include +#include +#include +struct node{ +int data; +struct node *next; +struct node *prev; +}; +struct node *head,*tail; + +void create(){ +struct node *newnode; +int choice; +head=NULL; +while(choice){ +newnode=(struct node*)malloc(sizeof(struct node)); +printf("enter data"); +scanf("%d",&newnode->data); +newnode->prev=NULL; +newnode->next=NULL; +if(head == NULL){ +head=newnode; +tail=newnode; +} +else{ +tail->next=newnode; +newnode->prev=tail; +tail=newnode; +} +printf("do you want to continue(1,0)?"); +scanf("%d",&choice); +} +} + +void print(){ +struct node * temp; +temp=head; +while(temp!=NULL){ +printf("%d",temp->data); +temp=temp->next; +} +} +void rever(){ +struct node * pnode,* nnode; +pnode=head; +while(pnode!=NULL){ +nnode=pnode->next; +pnode->next=pnode->prev; +pnode->prev=nnode; +pnode=nnode; +} +pnode=head; +head=tail; +tail=pnode; +} +void main(){ +clrscr(); +create(); +print(); +rever(); +printf("\n"); +print(); +getch(); +} diff --git a/c/ReverseAnInteger.c b/c/ReverseAnInteger.c new file mode 100644 index 00000000..2555af0a --- /dev/null +++ b/c/ReverseAnInteger.c @@ -0,0 +1,13 @@ +#include +int main() { + int n, rev = 0, remainder; + printf("Enter an integer: "); + scanf("%d", &n); + while (n != 0) { + remainder = n % 10; + rev = rev * 10 + remainder; + n /= 10; + } + printf("Reversed number = %d", rev); + return 0; +} diff --git a/c/Sum & Avg. of elements of a matrix.c b/c/Sum & Avg. of elements of a matrix.c new file mode 100644 index 00000000..a14602e0 --- /dev/null +++ b/c/Sum & Avg. of elements of a matrix.c @@ -0,0 +1,73 @@ +#include +int main() +{ + int i,j,m,n,sum=0,avg=0; + printf("Enter Number Of Rows : "); + scanf("%d",&m); + printf("Enter Number Of Columns : "); + scanf("%d",&n); + int matrix[m][n]; + printf("Enter Matrix Elements : "); + for(i=0;i + +int main() +{ + int m, n, p, q, c, d, k, sum = 0; + int first[10][10], second[10][10], multiply[10][10]; + + printf("Enter number of rows and columns of first matrix\n"); + scanf("%d%d", &m, &n); + printf("Enter elements of first matrix\n"); + + for (c = 0; c < m; c++) + for (d = 0; d < n; d++) + scanf("%d", &first[c][d]); + + printf("Enter number of rows and columns of second matrix\n"); + scanf("%d%d", &p, &q); + + if (n != p) + printf("The multiplication isn't possible.\n"); + else + { + printf("Enter elements of second matrix\n"); + + for (c = 0; c < p; c++) + for (d = 0; d < q; d++) + scanf("%d", &second[c][d]); + + for (c = 0; c < m; c++) { + for (d = 0; d < q; d++) { + for (k = 0; k < p; k++) { + sum = sum + first[c][k]*second[k][d]; + } + + multiply[c][d] = sum; + sum = 0; + } + } + + printf("Product of the matrices:\n"); + + for (c = 0; c < m; c++) { + for (d = 0; d < q; d++) + printf("%d\t", multiply[c][d]); + + printf("\n"); + } + } + + return 0; +} diff --git a/c/balancing_equation.c b/c/balancing_equation.c new file mode 100644 index 00000000..2d9169d7 --- /dev/null +++ b/c/balancing_equation.c @@ -0,0 +1,74 @@ +#include +#define SIZE 50 +char stack[SIZE]; +int Top = -1; +void push(char item) +{ + if( Top >= SIZE-1 ) + printf("\nStack overflow.\n"); + else + stack[++Top] = item; +} +char pop() +{ + char item; + if( Top<0 ) + { + printf("\nStack underflow : INVALID EXPRESSION\n"); + } + else + { + return(stack[Top--]); + } +} +void checkExp(char exp[]) +{ + int i=0; + char c = exp[i],item; + while(exp[i]!='\0') + { + if(c=='{'||c=='['||c=='(') + push(c); + else if(c=='}') + { + item = pop(); + if( item!='{' ) + { + printf("missing pair of %c.\n",item); + printf("Non balanced expression.\n"); + return; + } + } + else if(c==']') + { + item = pop(); + if( item!='[' ){ + printf("missing pair of %c.\n",item); + printf("Non balanced expression.\n"); + return; + } + } + else if(c==')') + { + item = pop(); + if( item!='(' ){ + printf("missing pair of %c.\n",item); + printf("Non balanced expression.\n"); + return; + } + } + c=exp[++i]; + } + if(Top<0) + printf("Balanced Expression.\n"); + else + printf("Non balanced expression:(Since it has odd number of symbols)\n"); +} +int main() +{ + char exp[SIZE]; + printf("Enter expression.\n"); + gets(exp); + checkExp(exp); + return 0; +} diff --git a/c/binarySearchTree.c b/c/binarySearchTree.c new file mode 100644 index 00000000..3a139436 --- /dev/null +++ b/c/binarySearchTree.c @@ -0,0 +1,52 @@ +#include +#include +struct node +{ int data; + struct node* left; + struct node* right; +}; +struct node* createNode(int value){ + struct node* newNode = malloc(sizeof(struct node)); + newNode->data = value; + newNode->left = newNode->right= NULL; + return newNode; +} +struct node* insert(struct node* root, int data) +{ if (root == NULL) {return createNode(data);} + if (data < root->data) {root->left = insert(root->left, data);} + else if (data > root->data) {root->right = insert(root->right, data);} + return root; +} +void inorder(struct node* root){ + if(root == NULL) return; + inorder(root->left); + printf("%d ", root->data); + inorder(root->right); +} +void preorder(struct node* root){ + if(root == NULL) return; + printf("%d ", root->data); + preorder(root->left); + preorder(root->right); +} +void postorder(struct node* root){ + if(root == NULL) return; + postorder(root->left); + postorder(root->right); + printf("%d ", root->data); +} +int main(){ + int inp, rt; + struct node *root = NULL; + printf("Enter the value of the ROOT:\n"); + scanf("%d", &rt); + root = insert(root, rt); + while(1){ printf("Enter Value or -1 to STOP:\n"); + scanf("%d", &inp); + if(inp==-1){break;} + insert(root, inp); } + + printf("Your INORDER output is:\n"); inorder(root); + printf("\nYour PREORDER output is:\n"); preorder(root); + printf("\nYour POSTORDER output is:\n"); postorder(root); +} diff --git a/c/binarytree.c b/c/binarytree.c new file mode 100644 index 00000000..0fbbe8e3 --- /dev/null +++ b/c/binarytree.c @@ -0,0 +1,114 @@ +#include +#include + +struct btree{ + int data; + struct btree *left; + struct btree *right; +}; + +struct btree *minValueNode(struct btree* node){ + struct btree* current = node; + + /* loop down to find the leftmost leaf */ + while (current && current->left != NULL) + current = current->left; + + return current; +} + +void insert(struct btree **root, int newData){ + struct btree *node = (*root); + if(node == NULL){ + struct btree *newNode = (struct btree *)malloc(sizeof(struct btree)); + newNode->left = NULL; + newNode->data = newData; + newNode->right = NULL; + *root = newNode; + } + else{ + if(newData > node->data) + insert(&(node->right), newData); + else + insert(&(node->left), newData); + } +} + +struct btree *delete(struct btree *root, int item){ + if(root == NULL) + return root; + + if(item > root->data) + root->right = delete(root->right, item); + + else if(item < root->data) + root->left = delete(root->left, item); + + else{ + if(root->left == NULL){ + struct btree *temp = root->right; + free(root); + return temp; + } + if(root->right == NULL){ + struct btree *temp = root->left; + free(root); + return temp; + } + struct btree *temp = minValueNode(root->right); + root->data = temp->data; + root->right = delete(root->right, temp->data); + } + return root; +} + +void inorder(struct btree *root){ + if(root != NULL){ + inorder(root->left); + printf("%d ", root->data); + inorder(root->right); + } + else{ + return; + } +} + +void preorder(struct btree *root){ + if(root != NULL){ + printf("%d ", root->data); + preorder(root->left); + preorder(root->right); + } + else{ + return; + } +} + +void postorder(struct btree *root){ + if(root != NULL){ + postorder(root->left); + postorder(root->right); + printf("%d ", root->data); + } + else{ + return; + } +} + +int main(){ + struct btree *root = NULL; + insert(&root, 20); + insert(&root, 40); + insert(&root, 17); + insert(&root, 6); + insert(&root, 8); + insert(&root, 10); + insert(&root, 7); + inorder(root); + printf("\n"); + delete(root, 20); + inorder(root); + printf("\n"); + postorder(root); + return 0; +} \ No newline at end of file diff --git a/c/bubblesort.c b/c/bubblesort.c new file mode 100644 index 00000000..2e046460 --- /dev/null +++ b/c/bubblesort.c @@ -0,0 +1,24 @@ +#include +int main() +{ + int n, temp, i, j; + printf ("Enter No of elements in the array \n"); + scanf("%d",&n); + int number[n]; + printf ("Enter the elements of array \n"); + for(int i=0;i=0;i--){ + for(j=0;j<=i;j++){ + if(number[j]>number[j+1]){ + temp=number[j]; + number[j]=number[j+1]; + number[j+1]=temp; + } + } + } + printf("Sorted elements: "); + for(i=0;i +int main() { + char operator; + double first, second; + printf("Enter an operator (+, -, *,): "); + scanf("%c", &operator); + printf("Enter two operands: "); + scanf("%lf %lf", &first, &second); + + switch (operator) { + case '+': + printf("%.1lf + %.1lf = %.1lf", first, second, first + second); + break; + case '-': + printf("%.1lf - %.1lf = %.1lf", first, second, first - second); + break; + case '*': + printf("%.1lf * %.1lf = %.1lf", first, second, first * second); + break; + case '/': + printf("%.1lf / %.1lf = %.1lf", first, second, first / second); + break; + // operator doesn't match any case constant + default: + printf("Error! operator is not correct"); + } + + return 0; +} diff --git a/c/calculatorv1.c b/c/calculatorv1.c new file mode 100644 index 00000000..085456e6 --- /dev/null +++ b/c/calculatorv1.c @@ -0,0 +1,40 @@ +# include +using namespace std; + +int main() +{ + char op; + float num1, num2; + + cout << "Enter operator either + or - or * or /: "; + cin >> op; + + cout << "Enter two operands: "; + cin >> num1 >> num2; + + switch(op) + { + case '+': + cout << num1+num2; + break; + + case '-': + cout << num1-num2; + break; + + case '*': + cout << num1*num2; + break; + + case '/': + cout << num1/num2; + break; + + default: + // If the operator is other than +, -, * or /, error message is shown + cout << "Error! operator is not correct"; + break; + } + + return 0; +} diff --git a/c/corrected_calculator_c b/c/corrected_calculator_c new file mode 100644 index 00000000..718e5b8d --- /dev/null +++ b/c/corrected_calculator_c @@ -0,0 +1,29 @@ +#include +int main() { + char operator; + double first, second; + printf("Enter an operator (+, -, *, /): "); + scanf("%c", &operator); + printf("Enter two operands: "); + scanf("%lf %lf", &first, &second); + + switch (operator) { + case '+': + printf("%.1lf + %.1lf = %.1lf", first, second, first + second); + break; + case '-': + printf("%.1lf - %.1lf = %.1lf", first, second, first - second); + break; + case '*': + printf("%.1lf * %.1lf = %.1lf", first, second, first * second); + break; + case '/': + printf("%.1lf / %.1lf = %.1lf", first, second, first / second); + break; + // operator doesn't match any case constant + default: + printf("Error! operator is not correct"); + } + + return 0; +} diff --git a/c/doublylinkedlist.c b/c/doublylinkedlist.c new file mode 100644 index 00000000..59463dfc --- /dev/null +++ b/c/doublylinkedlist.c @@ -0,0 +1,83 @@ +#include +#include + +struct node{ + int data; + struct node *prev; + struct node *next; +}; + +void addAtBeg(struct node **head, int newData){ + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + + newNode->data = newData; + + if(*head == NULL){ + *head = newNode; + newNode->next = NULL; + newNode->prev = NULL; + } + else{ + newNode->prev = NULL; + newNode->next = *head; + (*head)->prev = newNode; + *head = newNode; + } +} + +void addAfter(struct node **head, int look, int newData){ + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + + newNode->data = newData; + + struct node *link = *head; + while(link->data != look){ + link = link->next; + } + newNode->prev = link; + newNode->next = link->next; + link->next = newNode; +} + +void removeNode(struct node **head, int key){ + struct node *link = *head; + + while(link->next->data != key){ + link = link->next; + } + link->next->next->prev = link; + link->next = link->next->next; +} + +void reverse(struct node **head){ + struct node *current = *head; + struct node *temp = NULL; + while(current != NULL){ + temp = current->prev; + current->prev = current->next; + current->next = temp; + current = current->prev; + } + if(temp != NULL ) + *head = temp->prev; +} + +void print(struct node *head){ + while(head != NULL){ + printf("%d ", head->data); + head = head->next; + } +} + +int main(){ + struct node *head = NULL; + struct node *tail = NULL; + addAtBeg(&head, 5); + addAtBeg(&head, 4); + addAfter(&head, 5, 6); + addAfter(&head, 6, 7); + removeNode(&head, 6); + reverse(&head); + print(head); + return 0; +} \ No newline at end of file diff --git a/c/encryption_hackerrank.c b/c/encryption_hackerrank.c new file mode 100644 index 00000000..7c82c70c --- /dev/null +++ b/c/encryption_hackerrank.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the encryption function below. + +// Please either make the string static or allocate on the heap. For example, +// static char str[] = "hello world"; +// return str; +// +// OR +// +// char* str = "hello world"; +// return str; +// +char* encryption(char* s) { + + +} + +int main() +{ + FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); + + char* s = readline(); + + char* result = encryption(s); + + fprintf(fptr, "%s\n", result); + + fclose(fptr); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} diff --git a/c/insertionsort.c b/c/insertionsort.c new file mode 100644 index 00000000..319e7b48 --- /dev/null +++ b/c/insertionsort.c @@ -0,0 +1,36 @@ +#include + +int main() +{ + int i,j,n,temp,a[30]; + printf("Enter the number of elements:"); + scanf("%d",&n); + printf("\nEnter the elements\n"); + + for(i=0;i=0)) + { + a[j+1]=a[j]; //moves element forward + j=j-1; + } + + a[j+1]=temp; //insert element in proper place + } + + printf("\nSorted list is as follows\n"); + for(i=0;i +#include + +struct node{ + int data; + struct node *link; +}; + +void addNodeAtBeg(struct node **head, int newData){ + //Create a new node + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + //insert data in new node + newNode->data = newData; + //it's a new node i.e. it is going to be last node, add NULL to it's link + newNode->link = NULL; + //if linked list is empty + if(*head == NULL){ + *head = newNode; + return; + } + else{ + newNode->link = *head; + *head = newNode; + return; + } +} + +void addNodeAtEnd(struct node **head, int newData){ + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + + newNode->data = newData; + newNode->link = NULL; + + struct node *last = *head; + + if(*head == NULL) + *head = newNode; + else{ + while(last->link != NULL) + last = last->link; + last->link = newNode; + } +} + +void insertNodeAfter(struct node **head, int item, int newData){ + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + + newNode->data = newData; + + struct node *find = *head; + + while(find->data != item) + find = find->link; + newNode->link = find->link; + find->link = newNode; +} + +void deleteParticularNode(struct node **head, int item){ + struct node *find = *head; + if(find->data == item){ + *head = find->link; + free(find); + } + else{ + while(find->link->data != item) + find = find->link; + find->link = find->link->link; + free(find->link->link); + } +} + +void reverse(struct node **head){ + struct node *prev = *head; + struct node *next = *head; + struct node *current = *head; + + next = next->link->link; + current = current->link; + prev->link = NULL; + + while(1){ + current->link = prev; + prev = current; + current = next; + if(current == NULL) + break; + next = next->link; + } + *head = prev; +} + +void printList(struct node *head){ + while(head != NULL){ + printf("%d ", head->data); + head = head->link; + } +} + +int main(){ + + struct node *head = NULL; + + addNodeAtBeg(&head, 6); + + addNodeAtBeg(&head, 5); + + addNodeAtEnd(&head, 7); + + insertNodeAfter(&head, 7, 79); + + deleteParticularNode(&head, 7); + + addNodeAtBeg(&head, 2); + + addNodeAtBeg(&head, 3); + + addNodeAtBeg(&head, 4); + + printList(head); + + reverse(&head); + printf("\n"); + printList(head); + + return 0; +} \ No newline at end of file diff --git a/c/linkedlistcreate.c b/c/linkedlistcreate.c new file mode 100644 index 00000000..f17c40c6 --- /dev/null +++ b/c/linkedlistcreate.c @@ -0,0 +1,37 @@ +#include +struct node +{ + int data; + struct node*next; +}; +int main() +{ + int n,i; + struct node *head,*prev,*p; + printf("enter the size of list:"); + scanf("%d",&n); + head=NULL; + for(i=0;idata); + p->next=NULL; + if(head==NULL) + head=p; + else + prev->next=p; + prev=p; + } + display(head); + return 0; +} +void display(struct node *head) +{ + if(head==NULL) + printf("NULL"); + else + { + printf("%d\t",head->data); + display(head->next); + } +} diff --git a/c/mainREDBLACKTREE.c b/c/mainREDBLACKTREE.c new file mode 100644 index 00000000..b91515db --- /dev/null +++ b/c/mainREDBLACKTREE.c @@ -0,0 +1,231 @@ +#include +#include +#define RED 0 +#define BLACK 1 +struct rbnode +{ + int value; + int color; + struct rbnode*left,*right,*parent; +}; +void flipcolor(struct rbnode*node) +{ + (node->color)=1-(node->color); +} +struct rbnode*singleleftrotate(struct rbnode*gp) +{ + struct rbnode*p=gp->right; + gp->right=p->left; + if(p->left!=NULL) + { + p->left->parent=gp; + } + p->parent=gp->parent; + p->left=gp; + gp->parent=p; + flipcolor(gp); + flipcolor(p); + return p; +} +struct rbnode*singlerightrotate(struct rbnode*gp) +{ + struct rbnode*p=gp->left; + gp->left=p->right; + if(p->right!=NULL) + { + p->right->parent=gp; + } + p->parent=gp->parent; + p->right=gp; + gp->parent=p; + flipcolor(gp); + flipcolor(p); + return p; +} +struct rbnode*doubleleftrightrotate(struct rbnode*gp) +{ + struct rbnode*c,*p; + p=gp->left; + c=p->right; + p->right=c->left; + if(c->left!=NULL) + { + c->left->parent=p; + } + c->left=p; + p->parent=c; + gp->left=c; + c->parent=gp; + return singlerightrotate(gp); +} +struct rbnode*doublerightleftrotate(struct rbnode*gp) +{ + struct rbnode*c,*p; + p=gp->right; + c=p->left; + p->left=c->right; + if(c->right!=NULL) + { + c->right->parent=p; + } + c->right=p; + p->parent=c; + gp->right=c; + c->parent=gp; + return singleleftrotate(gp); +} +int isroot(struct rbnode*node) +{ + if(node->parent==NULL) + { + return 1; + } + else + { + return 0; + } +} +int getcolor(struct rbnode*node) +{ + if(node==NULL) + { + return BLACK; + } + else + { + return node->color; + } +} +struct rbnode*getuncle(struct rbnode*node) +{ + struct rbnode*p,*gp; + p=node->parent; + gp=p->parent; + if(p==gp->left) + { + return gp->right; + } + else + { + return gp->left; + } +} +struct rbnode*insert(struct rbnode*root,int v) +{ + struct rbnode*newnode,*x,*p,*gp,*uncle; + newnode=(struct rbnode*)malloc(sizeof(struct rbnode)); + if(newnode==NULL) + { + printf("Malloc failed"); + } + newnode->value=v; + newnode->color=RED; + newnode->left=NULL; + newnode->right=NULL; + if(root==NULL) + { + newnode->color=BLACK; + newnode->parent=NULL; + return newnode; + } + p=root; + while(1) + { + if(vvalue) + { + if(p->left==NULL) + { + p->left=newnode; + newnode->parent=p; + break; + } + p=p->left; + } + else + { + if(p->right==NULL) + { + p->right=newnode; + newnode->parent=p; + break; + } + p=p->right; + } + } + x=newnode; + while(1) + { + p=x->parent; + if(p->color==BLACK) + break; + gp=p->parent; + uncle=getuncle(newnode); + if(getcolor(uncle)==RED) + { + p->color=BLACK; + uncle->color=BLACK; + gp->color=RED; + if(isroot(gp)){root=gp;gp->color=BLACK;break;} + x=gp; + continue; + } + else + { + if(p==gp->left) + { + if(newnode==p->left) + { + if(isroot(gp)) root=singlerightrotate(gp); + else if(gp==gp->parent->left) gp->parent->left=singlerightrotate(gp); + else gp->parent->right=singlerightrotate(gp); + } + else + { + if(isroot(gp)) root=doubleleftrightrotate(gp); + else if(gp==gp->parent->left) gp->parent->left=doubleleftrightrotate(gp); + else gp->parent->right=doubleleftrightrotate(gp); + } + } + else + { + if(newnode==p->right) + { + if(isroot(gp)) root=singleleftrotate(gp); + else if(gp==gp->parent->left) gp->parent->left=singleleftrotate(gp); + else gp->parent->right=singleleftrotate(gp); + } + else + { + if(isroot(gp)) root=doublerightleftrotate(gp); + else if(gp==gp->parent->left) gp->parent->left=doublerightleftrotate(gp); + else gp->parent->right=doublerightleftrotate(gp); + } + } + break; + } + } + return root; +} +void traverse(struct rbnode*root) +{ + if(root==NULL) return; + traverse(root->left); + printf("%d %s\n",root->value,(root->color)?"BLACK":"RED"); + traverse(root->right); +} +int main(int argc, char *argv[]) +{ + struct rbnode*root=NULL; + int value; + printf("\nEnter node values = "); + while(1) + { + scanf("%d",&value); + if(value==-1) break; + root=insert(root,value); + traverse(root); + } + printf("\nDisplaying Tree : \n"); + traverse(root); + return 0; +} diff --git a/c/mainqusingstack.c b/c/mainqusingstack.c new file mode 100644 index 00000000..c0d8044d --- /dev/null +++ b/c/mainqusingstack.c @@ -0,0 +1,144 @@ +#include +#include +#define N 5 + +int top1=-1,top2=-1; +int s1[N]={},s2[N]={}; + +void push(int val,int n) +{ + if(n==-1) + { + if(top1!=N-1) + { + s1[++top1]=val; + } + else + { + printf("\n Queue is full"); + } + } + else + { + s2[++top2]=val; + } +} +int pop(int n) +{ + int temp; + if(n==-1) + { + temp=s1[top1--]; + } + else + { + temp=s2[top2--]; + } + return temp; +} +void insertvalue(int value) +{ + push(value,1); +} +int deletevalue() +{ + int temp; + if(top1==-1&&top2==-1) + { + printf("Queue is empty"); + } + else + { + if(top2!=-1) + { + pop(2); + } + else + { + while(top1!=-1) + { + temp=pop(1); + push(temp,2); + } + pop(2); + } + } +} +void display() +{ + int i; + for(i=top2;i>-1;i--) + { + printf("%d\n",s2[i]); + } + for(i=0;i<=top1;i++) + { + printf("%d\n",s1[i]); + } + printf("\n"); +} +int main(int argc, char *argv[]) { + int n,value,temp; + printf("\n 1.Enqueue \t\n 2.Dequeue \t\n 3.Display \t\n 4.EXIT \t\n"); + do + { + printf("\nEnter choice = "); + scanf("%d",&n); + switch(n) + { + case 1: + printf("\n Enter value to be inserted = "); + scanf("%d",&value); + insertvalue(value); + break; + case 2: + temp=deletevalue(); + printf("%d is deleted\n",temp); + break; + case 3: + display(); + break; + case 4: + printf("EXIT"); + } + }while(n!=4); + return 0; +} + +/* ""OUTPUT"" + + 1.Enqueue + 2.Dequeue + 3.Display + 4.EXIT + +Enter choice = 1 + + Enter value to be inserted = 10 + +Enter choice = 1 + + Enter value to be inserted = 20 + +Enter choice = 1 + + Enter value to be inserted = 30 + +Enter choice = 3 +30 +20 +10 + + +Enter choice = 2 +30 is deleted + +Enter choice = 3 +20 +10 + + +Enter choice = 4 +EXIT + +*/ diff --git a/c/modified_kaprekar_numbers.c b/c/modified_kaprekar_numbers.c new file mode 100644 index 00000000..b7826277 --- /dev/null +++ b/c/modified_kaprekar_numbers.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the kaprekarNumbers function below. +void kaprekarNumbers(int p, int q) { + int flag=0; + for(long i=p;i<=q;i++){ + long long int num=i*i,x,y; + if(i<=9){ + x=num/10; + y=num-(x*10); + } + else if(i<=99){ + x=num/100; + y=num-(x*100); + } + else if(i<=999){ + x=num/1000; + y=num-(x*1000); + } + else if(i<=9999){ + x=num/10000; + y=num-(x*10000); + } + else if(i<=99999){ + x=num/100000; + y=num-(x*100000); + } + if(x+y==i){ + printf("%ld ",i); + flag=1; + } + } + if(flag==0){ + printf("INVALID RANGE"); + } + +} + +int main() +{ + char* p_endptr; + char* p_str = readline(); + int p = strtol(p_str, &p_endptr, 10); + + if (p_endptr == p_str || *p_endptr != '\0') { exit(EXIT_FAILURE); } + + char* q_endptr; + char* q_str = readline(); + int q = strtol(q_str, &q_endptr, 10); + + if (q_endptr == q_str || *q_endptr != '\0') { exit(EXIT_FAILURE); } + + kaprekarNumbers(p, q); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { + break; + } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { + break; + } + + alloc_length <<= 1; + + data = realloc(data, alloc_length); + + if (!line) { + break; + } + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + + data = realloc(data, data_length); + } else { + data = realloc(data, data_length + 1); + + data[data_length] = '\0'; + } + + return data; +} diff --git a/c/palindrome.c b/c/palindrome.c new file mode 100644 index 00000000..253cb68b --- /dev/null +++ b/c/palindrome.c @@ -0,0 +1,19 @@ +#include + int main() +{ + int n,rem,rev=0,temp; + printf("enter the number="); + scanf("%d",&n); + temp=n; + while(n>0) + { + rem=n%10; + rev=(sum*10)+rem; + n=n/10; + } + if(temp==rev) + printf("Number is palindrome "); + else + printf("Number is not palindrome"); + return 0; +} diff --git a/c/palindrome_number.c b/c/palindrome_number.c new file mode 100644 index 00000000..554598a5 --- /dev/null +++ b/c/palindrome_number.c @@ -0,0 +1,23 @@ +#include + int main() + { + int n, rev=0,t; + printf("Enter a number to check if it is a palindrome or not\n"); + scanf("%d", &n); + t=n; + while(t!=0) + { + + rev=rev*10+t%10; + t=t/10; + + } + if(rev==n) + printf("%d is a palindrome number.\n",n); + else + { + printf("%d is not a palindrome number.\n",n); + } + + return 0; +} diff --git a/c/queue operations.c b/c/queue operations.c new file mode 100644 index 00000000..a8f62f2f --- /dev/null +++ b/c/queue operations.c @@ -0,0 +1,104 @@ + #include + #include + struct node + { + int data; + struct node *next; + }; + struct node *front; + struct node *rear; + void insert(); + void delete(); + void display(); + void main () + { + int choice; + while(choice != 4) + { + printf("\n*************************Main Menu*****************************\n"); + printf("\n=================================================================\n"); + printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n"); + printf("\nEnter your choice ?"); + scanf("%d",& choice); + switch(choice) + { + case 1: + insert(); + break; + case 2: + delete(); + break; + case 3: + display(); + break; + case 4: + exit(0); + break; + default: + printf("\nEnter valid choice??\n"); + } + } + } + void insert() + { + struct node *ptr; + int item; + + ptr = (struct node *) malloc (sizeof(struct node)); + if(ptr == NULL) + { + printf("\nOVERFLOW\n"); + return; + } + else + { + printf("\nEnter value?\n"); + scanf("%d",&item); + ptr -> data = item; + if(front == NULL) + { + front = ptr; + rear = ptr; + front -> next = NULL; + rear -> next = NULL; + } + else + { + rear -> next = ptr; + rear = ptr; + rear->next = NULL; + } + } + } + void delete () + { + struct node *ptr; + if(front == NULL) + { + printf("\nUNDERFLOW\n"); + return; + } + else + { + ptr = front; + front = front -> next; + free(ptr); + } + } + void display() + { + struct node *ptr; + ptr = front; + if(front == NULL) + { + printf("\nEmpty queue\n"); + } + else + { printf("\nprinting values .....\n"); + while(ptr != NULL) + { + printf("\n%d\n",ptr -> data); + ptr = ptr -> next; + } + } + } diff --git a/c/queue.c b/c/queue.c new file mode 100644 index 00000000..d16220c6 --- /dev/null +++ b/c/queue.c @@ -0,0 +1,62 @@ +#include +#include + +struct node{ + int data; + struct node *link; +}; + +void enqueue(struct node **head, int newData){ + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + newNode->data = newData; + newNode->link = NULL; + if(*head == NULL){ + *head = newNode; + } + else{ + struct node *tail = *head; + while(tail->link != NULL) + tail = tail->link; + tail->link = newNode; + } +} + +void dequeue(struct node **head){ + if(*head == NULL) + printf("\nQueue is already empty"); + else if((*head)->link == NULL){ + *head = NULL; + printf("\nQueue is now empty"); + } + else{ + *head = (*head)->link; + } +} + +void print(struct node *head){ + while(head != NULL){ + printf("%d ", head->data); + head = head->link; + } +} + +int main(){ + struct node *head = NULL; + enqueue(&head, 1); + enqueue(&head, 2); + enqueue(&head, 3); + print(head); + dequeue(&head); + printf("\n"); + print(head); + dequeue(&head); + printf("\n"); + print(head); + dequeue(&head); + printf("\n"); + print(head); + dequeue(&head); + printf("\n"); + print(head); + return 0; +} \ No newline at end of file diff --git a/c/quick_sort.c b/c/quick_sort.c new file mode 100644 index 00000000..87cb44dd --- /dev/null +++ b/c/quick_sort.c @@ -0,0 +1,55 @@ +#include +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; + int i = (low - 1); + + for (int j = low; j <= high- 1; j++) + { + if (arr[j] < pivot) + { + i++; + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + int pi = partition(arr, low, high); + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} +int main() +{ + int n; + printf("enter the size of the array : "); + scanf("%d",&n); + int arr[n]; + printf("\nenter array elements: "); + for(int i=0;i +#include + +/* Link list node */ +struct Node { + int data; + struct Node* next; +}; + +/* Function to reverse the linked list */ +static void reverse(struct Node** head_ref) +{ + struct Node* prev = NULL; + struct Node* current = *head_ref; + struct Node* next = NULL; + while (current != NULL) { + // Store next + next = current->next; + + // Reverse current node's pointer + current->next = prev; + + // Move pointers one position ahead. + prev = current; + current = next; + } + *head_ref = prev; +} + +/* Function to push a node */ +void push(struct Node** head_ref, int new_data) +{ + struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); + new_node->data = new_data; + new_node->next = (*head_ref); + (*head_ref) = new_node; +} + +/* Function to print linked list */ +void printList(struct Node* head) +{ + struct Node* temp = head; + while (temp != NULL) { + printf("%d ", temp->data); + temp = temp->next; + } +} + +/* Driver program to test above function*/ +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 20); + push(&head, 4); + push(&head, 15); + push(&head, 85); + + printf("Given linked list\n"); + printList(head); + reverse(&head); + printf("\nReversed Linked list \n"); + printList(head); + getchar(); +} diff --git a/c/stack.c b/c/stack.c new file mode 100644 index 00000000..b3b7eaea --- /dev/null +++ b/c/stack.c @@ -0,0 +1,55 @@ +#include +#include + +struct node{ + int data; + struct node *link; +}; + +void push(struct node **top, int newData){ + struct node *newNode = (struct node *)malloc(sizeof(struct node)); + newNode->data = newData; + + if(*top == NULL){ + *top = newNode; + newNode->link = NULL; + } + else{ + newNode->link = *top; + *top = newNode; + } +} + +void pop(struct node **top){ + if(*top == NULL) + printf("\nstack underflow"); + else if((*top)->link == NULL){ + *top = NULL; + printf("\nstack is now empty"); + } + else + *top = (*top)->link; +} + +void print(struct node *top){ + while(top != NULL){ + printf("%d ", top->data); + top = top->link; + } +} + +int main(){ + struct node *top = NULL; + push(&top, 5); + push(&top, 4); + push(&top, 3); + print(top); + pop(&top); + pop(&top); + pop(&top); + pop(&top); + pop(&top); + printf("\n"); + print(top); + return 0; +} \ No newline at end of file diff --git a/c/structure.c b/c/structure.c new file mode 100644 index 00000000..90b91c16 --- /dev/null +++ b/c/structure.c @@ -0,0 +1,22 @@ +#include + +struct Distance{ + int inch, feet; +}; + +void add(struct Distance l1, struct Distance l2){ + l1.feet = l1.feet + l2.feet + (l1.inch + l2.inch) / 12; + l2.inch = (l1.inch + l2.inch) % 12; + printf("\nFeet = %d, inch = %d",l1.feet, l1.inch); +} + +int mian(){ + struct Distance d1 = {100, 30}; + struct Distance d2 = {20, 20}; + printf("Distance 1"); + printf("\nFeet = %d, inch = %d",d1.feet, d1.inch); + printf("\nDistance 2"); + printf("\nFeet = %d, inch = %d",d2.feet, d2.inch); + add(d1, d2); + return 0; +} \ No newline at end of file diff --git a/c/swayamvar.c b/c/swayamvar.c new file mode 100644 index 00000000..1e0159fd --- /dev/null +++ b/c/swayamvar.c @@ -0,0 +1,43 @@ +#include +#include + +int main(){ + +int n, i, count = 0, gr = 0, gm = 0; +char bride[10000]; +char groom[10000]; +scanf("%d",&n); +scanf("%s",bride); +scanf("%s",groom); + +for(i=0;i0){ + gr--; + count++; + } + else + break;} + +else{if(gm>0){ + + gm--; + count++; + } + else + break;} + +} + +printf("%d",n-count); + +} diff --git a/c/towerofhanoi.c b/c/towerofhanoi.c new file mode 100644 index 00000000..2ed07993 --- /dev/null +++ b/c/towerofhanoi.c @@ -0,0 +1,77 @@ +/****************************************************************************** + + Online C Compiler. + Code, Compile, Run and Debug C program online. +Write your code in this editor and press "Run" button to compile and execute it. + +*******************************************************************************/ + + +/* + + * C program for Tower of Hanoi using Recursion + + */ + +#include + + + +void towers(int, char, char, char); + + + +int main() + +{ + + int num; + + + + printf("Enter the number of disks : "); + + scanf("%d", &num); + + printf("The sequence of moves involved in the Tower of Hanoi are :\n"); + + towers(num, 'A', 'C', 'B'); + + return 0; + +} + +void towers(int num, char frompeg, char topeg, char auxpeg) + +{ + + if (num == 1) + + { + + printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg); + + return; + + } + + towers(num - 1, frompeg, auxpeg, topeg); + + printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg); + + towers(num - 1, auxpeg, topeg, frompeg); + +} +/*OUTPUT : + +Enter the number of disks : 3 +The sequence of moves involved in the Tower of Hanoi are : + +Move disk 1 from peg A to peg C +Move disk 2 from peg A to peg B +Move disk 1 from peg C to peg B +Move disk 3 from peg A to peg C +Move disk 1 from peg B to peg A +Move disk 2 from peg B to peg C +Move disk 1 from peg A to peg C +*/ \ No newline at end of file diff --git a/c/union.c b/c/union.c new file mode 100644 index 00000000..1b145ffe --- /dev/null +++ b/c/union.c @@ -0,0 +1,18 @@ +#include + +union mix{ + int a; + char c[4]; +}; + +int main(){ + union mix k; + k.c[0] = 'A'; + k.c[1] = 'B'; + k.c[2] = 'C'; + k.c[3] = 'D'; + k.a = 1024; + //k.c[4] = 'E'; + printf("%d %d %d %d %d", k.c[0], k.c[1], k.c[2], k.c[3], k.a); + return 0; +} \ No newline at end of file diff --git a/esibe.html b/esibe.html new file mode 100644 index 00000000..f4f48eb4 --- /dev/null +++ b/esibe.html @@ -0,0 +1,30 @@ + + + + Login Form + + + +

Login Page


+ + + diff --git a/factorial.cs b/factorial.cs new file mode 100644 index 00000000..04c9cdfe --- /dev/null +++ b/factorial.cs @@ -0,0 +1,34 @@ +using System; + +namespace Factorial +{ + + class Program + { + + static void Main(string[] args) + { + Console.WriteLine("Enter a number"); + + int number = Convert.ToInt32(Console.ReadLine()); + + long fact = GetFactorial(number); + + Console.WriteLine("{0} factorial is {1}", number, fact); + + Console.ReadKey(); + } + + private static long GetFactorial(int number) + { + if (number == 0) + { + + return 1; + + } + + return number * GetFactorial(number-1); + } + } +} \ No newline at end of file diff --git a/html/hactoberfest.html b/html/hactoberfest.html new file mode 100644 index 00000000..08ffcfd3 --- /dev/null +++ b/html/hactoberfest.html @@ -0,0 +1,23 @@ + + + + + + Hactoberfest2020 + + +

This is hactoberfest pull request 1

+

Only Unique lines to get pull request accepted,

+

I will accept your request in 24 hrs if not then send me email

+
    +
  1. Dont modify above line
  2. +
  3. Starting from here...
  4. +
  5. Happy hacking...
  6. +
  7. Happy hacking.2121..
  8. +
  9. All the best for future
  10. +
  11. Visit here for register in this fest.
  12. +
+

To create a pull request,first you should fork the file and edit or create the file ,then commit changes and give pull req

+ + + diff --git a/html/myPage.html b/html/myPage.html new file mode 100644 index 00000000..43e711eb --- /dev/null +++ b/html/myPage.html @@ -0,0 +1,56 @@ + + + + + +

My Page

+

Hello World!

+

Success in Life

+ +
+
+

How to be a successful person:

+
    +
  • Strongly willing to learn
  • +
  • Sustain Failure
  • +
  • Strong Determination
  • +
+ +

Necessities for success:

+
    +
  1. Good Idea
  2. +
  3. Plan to work upon
  4. +
  5. Smart work
  6. +
+
+ +
+

Do you think you are

+ + +

+

+ +
+
+ diff --git a/java/BubbleSort.java b/java/BubbleSort.java new file mode 100644 index 00000000..ff6a3509 --- /dev/null +++ b/java/BubbleSort.java @@ -0,0 +1,17 @@ +public class BubbleSort { + public static 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 + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + } +} diff --git a/java/Emi calculator.java b/java/Emi calculator.java new file mode 100644 index 00000000..8e8224d5 --- /dev/null +++ b/java/Emi calculator.java @@ -0,0 +1,35 @@ +//program to calculate emi in java +import java.util.*; +import java.util.Scanner; +class Emi +{ + public static void main(String []args) + { + Scanner a = new Scanner(System.in); + + double principal, rate, time, emi; + + System.out.print("Enter principal: "); + principal = a.nextFloat(); + + System.out.print("Enter rate: "); + rate = a.nextFloat(); + + System.out.print("Enter time in year: "); + time = a.nextFloat(); + + rate=rate/(12*100); + time=time*12; + + + emi= emiCalculation(principal,rate,time); + + System.out.print("Monthly EMI is= "+emi+"\n"); + + } + static double emiCalculation(double p,double r,double t) + { + double e= (p*r*Math.pow(1+r,t))/(Math.pow(1+r,t)-1); + return e; + } +} diff --git a/java/SelectionSort.java b/java/SelectionSort.java new file mode 100644 index 00000000..53c7ba32 --- /dev/null +++ b/java/SelectionSort.java @@ -0,0 +1,51 @@ +import java.util.Scanner; + +public class SelectionSort { + + public static void selectionSorting(int arr[]) { + + int i=0; + int minIndex=0; + while(iarr[i+1]: + temp = arr[i] + arr[i] = arr[i+1] + arr[i+1] = temp + +n=int(input("Give range of list of numbers")) +arr=[] +for i in range(n): + arr.append(input("input a number")) + +bubbleSort(arr) +print(arr) diff --git a/python/Bucketsort.py b/python/Bucketsort.py new file mode 100644 index 00000000..c6b23a51 --- /dev/null +++ b/python/Bucketsort.py @@ -0,0 +1,44 @@ +""" +This technique sorts the elements by first dividing the elements into several groups called buckets. +The elements inside each bucket are sorted using any of the suitable sorting algorithms here we used- insertion sort + then all buckets are merged to give the sorted array + +""" +def insertionSort(a): + for i in range(1,len(a)): + j=i-1 + while(j>=0): + if a[j] > a[i]: + temp=a[j] + a[j]=a[i] + a[i]=temp + j-=1 + i-=1 +def bucketsort(arr): + bucket_list=[] + slot=10 + # creating empty buckets + for i in range(10): + bucket_list.append([]) + sorted_bucket=[] + for element in arr: + # checking for float type elements + if float(element)>=0.0 and float(element)<=1.0: + index=int(slot*float(element)) + bucket_list[index].append(float(element)) + # checking for int tytpe elements. + else: + index=int(int(element)/10) + bucket_list[index].append(int(element)) + + for bucket in bucket_list: + insertionSort(bucket) + for i in bucket: + sorted_bucket.append(i) + print(sorted_bucket) + + + +#main +bucket = [23,12,89,34,67,90,5,77] +bucketsort(bucket) \ No newline at end of file diff --git a/python/Calculator.py b/python/Calculator.py new file mode 100644 index 00000000..1b629da6 --- /dev/null +++ b/python/Calculator.py @@ -0,0 +1,50 @@ +# Simple Calculator in python +# @Author Srinidh Reddy + +class cal(): + def __init__(self,a,b): + self.a = a + self.b = b + def add(self): + return self.a + self.b + def mul(self): + return self.a * self.b + def div(self): + return self.a / self.b + def sub(self): + return self.a - self.b + def mod(self): + # Modulo operator works like a % b returns remainder when a is divided by b + # example 7 % 3 == 1 + return self.a % self.b + +a=int(input("Enter first number: ")) +b=int(input("Enter second number: ")) +obj=cal(a,b) +choice=1 + +while choice != 0: + print("0. Exit") + print("1. Add") + print("2. Subtraction") + print("3. Multiplication") + print("4. Division") + print("5. Modulo") + choice=int(input("Enter choice: ")) + if choice == 1: + print("Result: ",obj.add()) + elif choice == 2: + print("Result: ",obj.sub()) + elif choice == 3: + print("Result: ",obj.mul()) + elif choice == 4: + print("Result: ",round(obj.div(),2)) + elif choice == 5: + print("Result: ",obj.mod()) + elif choice == 0: + print("Exiting the calculator") + else: + print("Invalid choice!!") + + +print() diff --git a/python/Created count_Sort.py b/python/Created count_Sort.py new file mode 100644 index 00000000..7ba68d36 --- /dev/null +++ b/python/Created count_Sort.py @@ -0,0 +1,19 @@ +print("counting Sort") +print("Range of input") +n=int(input()) +l=[] +print("Total elements:") +t=int(input()) +print("input elements:") + +for j in range(0,t): + p=int(input()) + if p>n: + print("out of bounds") + else: + l.append(p) +print("Unsorted list is:") +print(l) +print("Sorted list is:") +l.sort() +print(l) diff --git a/python/Max_frequence_of_tuple.py b/python/Max_frequence_of_tuple.py new file mode 100644 index 00000000..8cf63cf3 --- /dev/null +++ b/python/Max_frequence_of_tuple.py @@ -0,0 +1,21 @@ +# Maximum frequency in Tuple +# Using loop + count() + +# initializing tuple +test_tuple = (15, 12,33, 45,12 ,33 ,12) + +# printing original tuple +print("The original tuple : " + str(test_tuple)) + +# Maximum frequency in Tuple +# Using loop + count() +freq = 0 +res = test_tuple[0] +for ele in test_tuple: + curr_freq = test_tuple.count(ele) + if(curr_freq> freq): + freq = curr_freq + res = ele +# prints the leftmost highest frequency element of the tuple +# printing result +print("Maximum element frequency tuple : " + str(res)) diff --git a/python/Print_Pascal_Triangle_of_size_n.py b/python/Print_Pascal_Triangle_of_size_n.py new file mode 100644 index 00000000..d72db198 --- /dev/null +++ b/python/Print_Pascal_Triangle_of_size_n.py @@ -0,0 +1,14 @@ +n=int(input("Enter number of rows: ")) +a=[] +for i in range(n): + a.append([]) + a[i].append(1) + for j in range(1,i): + a[i].append(a[i-1][j-1]+a[i-1][j]) + if(n!=0): + a[i].append(1) +for i in range(n): + print(" "*(n-i),end=" ",sep=" ") + for j in range(0,i+1): + print('{0:6}'.format(a[i][j]),end=" ",sep=" ") + print() diff --git a/python/Reverse String.py b/python/Reverse String.py new file mode 100644 index 00000000..bd5f8388 --- /dev/null +++ b/python/Reverse String.py @@ -0,0 +1,5 @@ +print("enter a text you want to reverse") +txt = str(input()) +a=txt[::-1] +print("Reversed text is:") +print(a) diff --git a/python/basic_searchnumber.py b/python/basic_searchnumber.py new file mode 100644 index 00000000..dddcbbd6 --- /dev/null +++ b/python/basic_searchnumber.py @@ -0,0 +1,20 @@ +l=[] +print("Total number elements you want to add:") +t=int(input()) +print("input elements:") + +for j in range(0,t): + p=int(input()) + l.append(p) +print("Unsorted list is:") +print(l) +print("Sorted list is:") +l.sort() +print(l) +print("Enter the number you want to find index of :") +n=int(input()) +if n in l: + print("number is at index:") + print(l.index(n)) +else: + print("element does not exits") diff --git a/python/binarySearch.py b/python/binarySearch.py new file mode 100644 index 00000000..204a091d --- /dev/null +++ b/python/binarySearch.py @@ -0,0 +1,21 @@ +def bin_search(arr,x): + lo = 0 + hi = len(arr) + while(lo<=hi): + mi = int((lo+hi)/2) + if(arr[mi]x): + hi=mi-1 + else: + break + return mi + + +def main(): + arr = [128,15,3656,355,32,1,2546] + arr.sort() + x = 355 + print("In The array "+str(x)+" exists at index",bin_search(arr,x)) +if _name=="main_": + main() diff --git a/python/bubble-sort.py b/python/bubble-sort.py new file mode 100644 index 00000000..90da2c2c --- /dev/null +++ b/python/bubble-sort.py @@ -0,0 +1,29 @@ +# Optimized bubble sort in python + + +def bubbleSort(array): + + # Run loops two times: one for walking throught the array + # and the other for comparison + for i in range(len(array)): + + # swapped keeps track of swapping + swapped = True + for j in range(0, len(array) - i - 1): + + # To sort in descending order, change > to < in this line. + if array[j] > array[j + 1]: + + # Swap if greater is at the rear position + (array[j], array[j + 1]) = (array[j + 1], array[j]) + swapped = False + + # If there is not swapping in the last swap, then the array is already sorted. + if swapped: + break + + +data = [-2, 45, 0, 11, -9] +bubbleSort(data) +print('Sorted Array in Ascending Order:') +print(data) diff --git a/python/fibonacci.py b/python/fibonacci.py new file mode 100644 index 00000000..9d8e844d --- /dev/null +++ b/python/fibonacci.py @@ -0,0 +1,19 @@ +def fibonacci(n): + """ + Return n-th Fibonacci number. + + Raises TypeError if n is not integer. + Raises ValueError if n is negative. + :param n: (int) natural number + :return: (int) n-th Fibonacci number + """ + a, b = 0, 1 + if n == 0: + return a + elif n == 1: + return b + else: + for _ in range(2, n + 1): + c = a + b + a, b = b, c + return b \ No newline at end of file diff --git a/python/figure.py b/python/figure.py new file mode 100644 index 00000000..58b7665e --- /dev/null +++ b/python/figure.py @@ -0,0 +1,22 @@ +import turtle + +t = turtle.Turtle() +s = turtle.Screen() +s.bgcolor("black") +t.pencolor("green") +t.speed(0.2) +t.penup() +t.goto(0, 200) +t.pendown() +a = 0 +b = 0 +while True : + t.forward(a) + t.right(b) + a += 3 + b += 1 + if b == 200 : + break + t.hideturtle() + +turtle.done() diff --git a/python/mwi00174_ECA.py b/python/mwi00174_ECA.py new file mode 100644 index 00000000..3d5bb08c --- /dev/null +++ b/python/mwi00174_ECA.py @@ -0,0 +1,290 @@ +import random + +# +# NAME:Oarabile Mwiya +# ID :201700174. +# ECA + +# VectorAdd() returns a vector obtained by adding two vectors, +#which are parameters of the function +# result is a vector +def VectorAdd(a,b): + + #Check equality of the vectors + assert len(a)==len(b) + + #Initialise an empty vector list + newVector = [] + + #Iterate with respect to the vector length and add corresponding values + for i in range(len(a)): + + v = a[i] + b[i] + + newVector.append(v) + + + return newVector +# performs vector subtraction on two vectors and returns a +# vector +def VectorSub(a,b): + #check if length of vectors are equal + assert len(a)==len(b) + + #Initialize an empty vector list + newVector = [] + + #Iterate the indices wrt to vector length and subtract corresponding values + for i in range(len(a)): + + v = a[i] - b[i] + + newVector.append(v) + + return newVector + + +# Implement this: VectorMult() performs vector multiplication and returns a scalar +# (number) +def VectorMult(a,b): + #compare length equality of vector a and b + assert len(a)==len(b) + + total = 0 + + #Iterate the vector indices wrt to the vector length and multiply corresponding values + for i in range(len(a)): + v = a[i] * b[i] + total = total + v + return total + + +# DO NOT MODIFY THIS FUNCTION +def argMax(scores): + """ + Returns the key with the highest value. + """ + if len(scores) == 0: return None + all = scores.items() + values = [x[1] for x in all] + maxIndex = values.index(max(values)) + return all[maxIndex][0] + + +#MulticlassPerceptronLearning Function + +def MulticlassPerceptronLearning(trainingvectors): + + #Initalize weight + weights={'A':[0,0,0],'B':[0,0,0],'C':[0,0,0]} + + #Set threshold to zero + threshold = 0 + + #Initialize scores of class(A,B,C respectively ) + scoreA = 0 + + scoreB = 0 + + scoreC = 0 + + #Check if selected apple is bad + Badapple = True + + #Feature Vector for apples + VectorApples = "" + + #Declare and initialize variable iteration + iteration = 0 + + #Run the loop for a thousand iterations and check if a Bad apple is found + while(Badapple == True and iteration < 1000): + + #Initialize empty list for classification + classification = [] + + #Increment variable iteration by 1 and ouput each iteration at each interval + iteration += 1 + print "\nIteration Number:",iteration + + #Iterate apples in the trainingvectors using for loop + for AppleVector in trainingvectors: + + #Distiguish apart classless features + appleFeatures = [AppleVector[0], AppleVector[1]] + + #Instance of the current feature vector + VectorApples = AppleVector[2] + + #Threshold is appended to the feature vector + appleFeatures.append(1) + + # Feature vectors mutplied with correspong weight vectors + + scoreA = VectorMult(appleFeatures, weights['A']) + + scoreB = VectorMult(appleFeatures, weights['B']) + + scoreC = VectorMult(appleFeatures, weights['C']) + + #Scores stored in a dictionary + scores = {'A': scoreA, 'B': scoreB, 'C': scoreC} + + #Using percept identify class with highest score + MaximumClass = argMax(scores) + + #Check if The highest score correspond with the Current class + if(MaximumClass != VectorApples): + + #Subtract Apple Feature Vector From Incorrect Class Vector and output desired results + print "Bad Apple Detectad : ",AppleVector + + bad = VectorSub(weights[MaximumClass],appleFeatures) + + weights[MaximumClass] = bad + + #Add Apple Feature Vector To Correct Class Vector + + Good = VectorAdd(weights[VectorApples],appleFeatures) + + weights[VectorApples] = Good + + #append bad apples to classification list + classification.append("Bad") + + #If its highest score classify it a good apple in list then transcend to next iteration + else: + classification.append("Good") + + print "\AFTER ITERATION NUMBER:",iteration + print weights + + # Check If Bad Apple Was Found + if "Bad" in classification: + Badapple = True + else: + Badapple = False + + print "\n\nFinal W:",weights + return weights + + + + + + #LoadFile function to load file + +def LoadFile(fileName): + + dataFile=open(fileName,"r") + + #Initalize empty apples list + Apples = [] + + #Intialize empty firstlist variable + firstlist = [] + + #Initialize empty secondlist variable + secondlist = [] + + #start from the first value in tha data file + next(dataFile) + + #Iterate line by line the data txt file + for line in dataFile: + + #Our data file cointains list of apples in terms of(color ,size and class) thus use them to split data + #Use split to convert each corresponding line into an array + lineSplit = line.split() + + #Split color from the data text and store in array.. + color = float(lineSplit[0]) + + #split size from the data text and store in array.. + size = float(lineSplit[1]) + + #Append the split features into apples empty list .. + Apples.append([color,size,lineSplit[2]]) + + #Random number seed generator + random.seed(2) + + #Randomise apples + random.shuffle(Apples) + + # system must read in the data file, split such that 70% of apples are used for training and 30% for testing + #Extract first 84apples which is 70% for training + firstlist = Apples[:84] + + #Extract last 84apples which is 70% for training + secondlist = Apples[84:] + + #Return list + return firstlist,secondlist + +#Evaluate Function(Interpretation of classified apples).. +def Evaluate(weights,appleVectors): + + numapples=len(appleVectors) + numcorrect=0 + + #Initialize scores of class(A,B,C respectively ) + scoreA = 0 + + scoreB = 0 + + scoreC = 0 + + print "\n\nAPPLES CLASSIFICATION" + + #Iterate apples in apple set + for SetApples in appleVectors: + + # Extract cost and size + appleFeatures = [SetApples[0], SetApples[1]] + + # Set vector to apples class + VectorApples = SetApples[2] + + #Threshold appended to vector + appleFeatures.append(1) + print "\n\n Apple Being Classified:",SetApples + + # Feature vectors mutplied with correspong weight vectors + scoreA = VectorMult(appleFeatures, weights['A']) + + scoreB = VectorMult(appleFeatures, weights['B']) + + scoreC = VectorMult(appleFeatures, weights['C']) + + #Scores stored in a dictionary + scores = {'A': scoreA, 'B': scoreB, 'C': scoreC} + + # Determine Class With Max Score + MaximumClass = argMax(scores) + + print "Maximum Class Score : ",MaximumClass + + #Check if max class equals the current apple class and iterate if condition met + if(MaximumClass == VectorApples): + numcorrect+=1 + + + return round(float(numcorrect)/numapples*100,2) + + + +# DO NOT MODIFY THIS FUNCTION +def RunExperiment(): + training,testing=LoadFile("data.txt") + w=MulticlassPerceptronLearning(training) + score=Evaluate(w,testing) + + print "Evaluation Score:",score + +RunExperiment() + + +#Performance of Machine Learning model**** +# The model has an evaluation score of 97.22 which is much closer to a perfect score (100) which derives +#that the model can clearly classify apples as bad or good apples based on the color , size and class. diff --git a/python/perfect_numbers.py b/python/perfect_numbers.py new file mode 100644 index 00000000..244159d6 --- /dev/null +++ b/python/perfect_numbers.py @@ -0,0 +1,13 @@ +def classify(number): + if number == 0: raise ValueError("Zero is not a natural number") + if number < 0: raise ValueError("Negative integer is not a natural number") + aliquots = [] + for i in range(1, number): + if number % i == 0: + aliquots.append(i) + if sum(aliquots) == number: + return "perfect" + elif sum(aliquots) > number: + return "abundant" + elif sum(aliquots) < number: + return "deficient" \ No newline at end of file diff --git a/python/postFixEvaluation.py b/python/postFixEvaluation.py new file mode 100644 index 00000000..98cb8a12 --- /dev/null +++ b/python/postFixEvaluation.py @@ -0,0 +1,28 @@ +## Algorithm to evaluate any postfix expression in python using list as stack + + +def postFixOp(s): + n = len(s) + stk = [] + for i in s: + #print(stk) + if i.isnumeric() : + stk.append(i) + else: + b = stk[-1] + stk.pop() + a = stk[-1] + stk.pop() + if i == '+': + stk.append(int(a)+int(b)) + elif i == '-': + stk.append(int(a)-int(b)) + elif i == '*': + stk.append(int(a)*int(b)) + elif stk == '/': + sk.append(int(a)/int(b)) + + return stk[0] + +s = input() +print(postFixOp(s)) diff --git a/python/prime_factors.py b/python/prime_factors.py new file mode 100644 index 00000000..909c93e1 --- /dev/null +++ b/python/prime_factors.py @@ -0,0 +1,14 @@ +import math + +def factors(value): + factors = [] + while value % 2 == 0: + factors.append(2) + value //= 2 + for i in range(3, math.isqrt(value) + 1, 2): + while value % i == 0: + factors.append(i) + value //= i + if value > 2: + factors.append(value) + return factors diff --git a/python/quickSort.py b/python/quickSort.py new file mode 100644 index 00000000..f2d638cb --- /dev/null +++ b/python/quickSort.py @@ -0,0 +1,38 @@ +""" +Quick sort using last element as pivot index. + +Initial array: [23, 45, 12, 78, 90, 1] +-------------- [1, 45, 12, 78, 90, 23] +-------------- [1, 12, 23, 78, 90, 45] +-------------- [1, 12, 23, 45, 90, 78] +-------------- [1, 12, 23, 45, 78, 90] +Sorted array : [1, 12, 23, 45, 78, 90] + +""" +def find_pviot_index(A,start,end): + pivot=A[end] + p_index=start + for iter in range(start,end): + if A[iter] <= pivot: + A[p_index],A[iter]=A[iter],A[p_index] + p_index+=1 + A[p_index],A[end]=pivot,A[p_index] + return p_index + +def quick_sort(A,start,end): + if start < end: + pivot_index=find_pviot_index(A,start,end) + print("--------------",A) + quick_sort(A,start,pivot_index-1) + quick_sort(A,pivot_index+1,end) + + +#main +A=list() +n=int(input("Enter how many numbers you want ot enter: ")) +for x in range(0,n): + num=int(input("enter num:")) + A.append(num) +print("Initial array:",A) +quick_sort(A,0,n-1) +print("Sorted array :",A) \ No newline at end of file diff --git a/python/radixsort.py b/python/radixsort.py new file mode 100644 index 00000000..41240a11 --- /dev/null +++ b/python/radixsort.py @@ -0,0 +1,33 @@ +def insertion(a,n,m): + for i in range(1,len(a)): + j=i-1 + while(j>=0): + if ((a[j]%n)/m )>((a[i]%n)/m): + temp=a[j] + a[j]=a[i] + a[i]=temp + j-=1 + i-=1 + +def radix_sort(a,length): + n=10 + m=1 + for i in range(0,length): + insertion(a,n,m) + n=n*10 + m=m*10 + print(a) + +# main +# Taking the list of numbers and user +li=list() +length_ofDigit=0 +n=int(input("Enter how many numbers you want ot enter: ")) +for x in range(0,n): + num=int(input("enter num:")) + li.append(num) + # Taking the len of longest digit (No of steps taken by this sort is equal to length of longest number) + if length_ofDigit a[j]: + minindex = j + a[i], a[minindex] = a[minindex], a[i] + + # This will show the sorted array at each step + print("Sorted array at step", i + 1, a) + +print("------------------------") +print("Final sorted array is:", a) diff --git a/python/sieve_of_eratosthenes.py b/python/sieve_of_eratosthenes.py new file mode 100644 index 00000000..5f52d45b --- /dev/null +++ b/python/sieve_of_eratosthenes.py @@ -0,0 +1,13 @@ +def sieve_of_eratosthenes(n: int) -> list: + """ + Return ordered list of primes in the interval from 2 to n. + + :param n: (int) right-bound of interval + :return: (list) ordered list of all prime numbers from 2 to n + """ + primes = list(range(2, n + 1)) + for i in primes: + for j in range(2, n // i + 1): + if i * j in primes: + primes.remove(i * j) + return primes \ No newline at end of file diff --git a/unlabeled/Vowel or Consonant using pointers b/unlabeled/Vowel or Consonant using pointers new file mode 100644 index 00000000..6c023391 --- /dev/null +++ b/unlabeled/Vowel or Consonant using pointers @@ -0,0 +1,33 @@ +#include +int main(void) +{ + char alpha; + char *pa=α + printf("Enter any alphabet:"); + scanf("%c",pa); + { + if(*pa=='a') + printf("The alphabet is a vowel"); + else if(*pa=='A') + printf("The alphabet is a vowel"); + else if(*pa=='e') + printf("The alphabet is a vowel"); + else if (*pa=='E') + printf("The alphabet is a vowel"); + else if(*pa=='i') + printf("The alphabet is a vowel"); + else if(*pa=='I') + printf("The alphabet is a vowel"); + else if (*pa=='O') + printf("The alphabet is a vowel"); + else if(*pa=='o') + printf("The alphabet is a vowel"); + else if(*pa=='u') + printf("The alphabet is a vowel"); + else if (*pa=='U') + printf("The alphabet is a vowel"); + else + printf("The alphabet is a consonant"); + } + return 0; +} diff --git a/unlabeled/data.txt b/unlabeled/data.txt new file mode 100644 index 00000000..119f23a8 --- /dev/null +++ b/unlabeled/data.txt @@ -0,0 +1,121 @@ +Color Size Class +-0.731271511775 0.694867473874 A +0.527549237953 -0.489861948521 B +-0.00912982581612 -0.101017870423 A +0.303185945446 0.577446702271 A +-0.812280826452 -0.943305046956 B +0.67153020784 -0.13446586419 B +0.524560164916 -0.995787893298 B +-0.10922561189 0.443080064682 A +-0.542475557459 0.890541391108 A +0.802854915223 -0.938820033933 B +-0.949108278013 0.082824945587 A +0.878298325557 -0.237591524624 B +-0.566801205739 -0.155766848835 A +-0.94191842485 -0.556616667454 A +-0.124224812699 -0.0083755172363 A +-0.533831099485 -0.538266916918 B +-0.562437925325 -0.0807930685245 A +-0.420436770819 -0.957020589468 B +0.675155951325 0.112908645305 A +0.284588725865 -0.628187468211 B +0.985086824352 0.719893057591 C +-0.758220080388 -0.33460962928 A +0.442968815167 0.422383539391 A +0.872881173599 -0.155786000077 B +0.660071386549 0.340611132828 C +-0.393262978134 0.175161212287 A +0.764958001664 0.692394836857 C +0.0105676411592 0.178004515965 A +-0.930948339697 -0.514520052914 A +0.594808495109 -0.171372001398 B +-0.653985196842 0.0975975227763 A +0.406081524131 0.348971661005 A +-0.250593958997 -0.122076739911 A +0.0168529765 0.55688523 A +0.0418768352263 -0.213489810072 A +-0.0206129590755 -0.940850072066 B +-0.913025419287 0.406764177208 A +0.966375434619 0.18636746076 C +-0.212800627244 -0.659301606289 B +0.00447711686697 0.964153275077 A +0.541046279662 0.0792348968996 A +0.720579557841 -0.535647743874 B +0.0275433263753 0.904934776537 A +0.155589615602 -0.0817365361787 A +-0.461441045117 0.0959926189325 A +0.91423256292 -0.988581741099 B +0.567310465231 0.640971823851 C +0.772359161652 0.481006823666 C +0.618279801745 0.037356567046 A +0.122715729557 -0.147818640624 A +-0.887753404959 0.740020310353 A +0.139998667753 -0.600321159646 B +0.00944093485773 -0.0301497755445 A +-0.28642007091 -0.307844161964 A +0.0769575914757 0.246978905595 A +0.224904929565 -0.0837063998006 A +-0.944050031832 -0.540789937446 A +-0.645577482123 0.168921741557 A +0.722017721707 0.596877881155 C +0.594195125271 0.632874741121 C +-0.489411919825 0.683489664548 A +0.346227050877 -0.833531724392 B +-0.966618739769 -0.97088005015 B +0.511173550504 -0.500881548693 B +-0.781022745411 0.249604168305 A +-0.311154271807 -0.860969242938 B +-0.680748950612 0.054760798096 A +-0.663710107555 -0.454171126363 A +-0.158162641582 -0.623921390497 B +0.0202319618574 -0.581818014896 B +-0.958363782981 -0.964270958344 B +0.935806620302 0.75106848847 C +-0.49528379544 -0.983039475073 B +0.757435796418 -0.924166938803 B +0.638828221226 0.924402250362 C +0.14056114049 -0.656965809645 B +0.73556212887 0.947550472319 C +-0.134099757799 -0.61176271003 B +0.79935653927 -0.963814032719 B +0.974099435856 0.565400751459 C +-0.321808704298 -0.573940407238 B +0.348910139448 0.675402140308 C +0.864374943787 -0.312300370418 B +0.764786404933 0.374220364307 C +-0.830639539167 -0.660611716411 B +0.821975567016 -0.574063610017 B +0.682264391412 -0.263784001189 B +0.908614914344 0.774530209434 C +-0.791450003971 -0.921724402806 B +0.57623289745 0.657011942938 C +0.563807203266 -0.243920742323 B +0.141563051198 -0.552571854502 B +0.850134404217 -0.0844614819175 B +0.655536313291 -0.975236511027 B +0.340823278048 -0.816633754767 B +0.976316997212 -0.157972825139 B +0.826784034332 0.939626553676 C +0.95990577178 0.0858263949694 C +0.552417965972 0.969791742288 C +0.607712561968 0.814307533994 C +0.681437044493 0.492369770809 C +0.926771766643 0.616505256745 C +0.813879009012 0.835413167676 C +0.385113929206 0.697982244973 C +0.712554277826 0.793208742233 C +0.92015763393 0.142465388435 C +0.551514500631 0.683861717087 C +0.582181436736 0.617309240328 C +0.9472322191 0.0907540076517 C +0.0905741795363 0.929890657573 C +0.522131319706 0.94703956916 C +0.489261235477 0.975183382445 C +0.795818343274 0.49754692715 C +0.874235919078 0.564947370742 C +0.692536133202 0.534999580285 C +0.41604005413 0.747884149626 C +0.4268739968 0.630006887857 C +0.413380626503 0.687585244489 C +0.826290010407 0.456495689574 C +0.407847188838 0.629821117579 C \ No newline at end of file diff --git a/unlabeled/function overloading b/unlabeled/function overloading new file mode 100644 index 00000000..53fe48bf --- /dev/null +++ b/unlabeled/function overloading @@ -0,0 +1,62 @@ +// area of a circle, a rectangle and a triangle, using concept of function overloading. +#include +#include +using namespace std; +//Area of circle +float area(float r) +{ + float ret=3.14*pow(r,2); + return ret; +} +//Area of the rectangle +float area(float l,float b) +{ + float ret=l*b; + return ret; +} +//Area of the triangle +float area(float s1,float s2,float s3) +{ + float t=(s1+s2+s3)/2; + float ret=sqrt(t*(t-s1)*(t-s2)*(t-s3)); + return ret; +} +int main() +{ + int ch; + while(1){ + cout<<"\n 1. Area of circle \n"<<"2. Area of reactangle\n"<<"3. Area of triangle\n"<<"Enter your choice: "; + cin>>ch; + switch(ch) + { + case 1: + { + float n; + cout<<"\nEnter radius: "; + cin>>n; + cout<<"\nArea of sphere: "<>l>>b; + cout<<"Area of Rectangle: "<>s1>>s2>>s3; + cout< +main() +{ + int a1,a2,a3; + printf ("enter a,b,c(m[a][b]&m[b][c]):\n"); + scanf("%d%d%d",&a1,&a2,&a3); + + int m1[a1][a2],m2[a2][a3],c[a1][a3]; + printf ("enter values of m[%d][%d]\n",a1,a2); + for(int i=1;i<=a1;i++) + { + for(int j=1;j<=a2;j++) + scanf("%d",&m1[i][j]); + } + printf ("\n enter values of m[%d][%d]\n",a2,a3); + for(int i=1;i<=a2;i++) + { + for(int j=1;j<=a3;j++) + scanf("%d",&m2[i][j]); + } + printf("MULTIPLICATION OF MATRIX :\n"); + for(int i=1;i<=a1;i++) + { + for(int j=1;j<=a3;j++) + { int x=0; + for(int k=1;k<=a2;k++) + x=x+(m1[i][k]*m2[k][j]); + c[i][j]=x; + } + } + for(int i=1;i<=a1;i++) + { + for(int j=1;j<=a3;j++) + printf("%d\t",c[i][j]); + printf("\n"); + } +}