diff --git a/Area.c b/Area.c new file mode 100644 index 00000000..0388d327 --- /dev/null +++ b/Area.c @@ -0,0 +1,12 @@ +#include +int main() { +int rad; float PI = 3.14; +float area, ci; +printf("\nEnter radius of circle: "); +scanf("%d", &rad); +area = PI * rad * rad; +printf("\nArea of circle : %f ", area); +ci = 2 * PI * rad; +printf("\nCircumference: %f ", ci); +return (0); +} \ No newline at end of file diff --git a/BMI Calculator.py b/BMI Calculator.py new file mode 100644 index 00000000..06a0ec58 --- /dev/null +++ b/BMI Calculator.py @@ -0,0 +1,20 @@ +print(' BMI CALCULATOR') +name = input('What is your name?') +weight = float(input('What is your weight (in Kgs)?')) +height = float(input('What is your height (in meters)?')) +bmi = weight / (height ** 2) + +if bmi<18.5: + print(f"\n{name} is underweight by {bmi} BMI") + print('Eat foods containing high portion of fats and carbohydrates') +elif 18.5 + 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/Circular queue b/C/Circular queue new file mode 100644 index 00000000..19b37487 --- /dev/null +++ b/C/Circular queue @@ -0,0 +1,50 @@ +#include +#include +#define size 3 +void insert(); +void delete(); +void display(); +int front=-1; +int rear =-1; +int a[size]; +int main() +{ + int d; + printf("\n\n\n LIST OF CHOICES AND MENU"); + printf("=========================>>"); + printf("\n 1. insert"); + printf("\n 2. delete"); + printf("\n 3. DISPLAY"); + printf("\n 4. BYE BYE"); + while(1) + { + printf("\n\n enter your choice="); + scanf("%d",&d); + switch(d) + { + case 1: + { + insert(); + break; + } + case 2: + { + delete(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + exit(0); + } + default: + { + printf("\n INVALID INPUT !!!!!!"); + } + } + } + } 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.c b/C/Generate multiplication table using C.c new file mode 100644 index 00000000..7250ae24 --- /dev/null +++ b/C/Generate multiplication table using C.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 +#define size 3 +void insert(); +void delete(); +void display(); +int front=-1; +int rear =-1; +int a[size]; +int main() +{ + int d; + while(1) + { + printf("\n\n\n LIST OF CHOICES AND MENU"); + printf("=========================>>"); + printf("\n 1. insert"); + printf("\n 2. delete"); + printf("\n 3. DISPLAY"); + printf("\n 4. BYE BYE"); + printf("\n enter your choice="); + scanf("%d",&d); + switch(d) + { + case 1: + { + insert(); + break; + } + case 2: + { + delete(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + exit(0); + } + default: + { + printf("\n INVALID INPUT !!!!!!"); + } + } + } +} +void insert() +{ + int n; + if(rear>" ); + if(front==-1 && rear==-1) + { + printf("\n there is no element to display"); + } + else + { + for(i=front;i<=rear;i++) + { + printf(" %d ",a[i]); + } + } +} diff --git a/C/Radix_sort.c b/C/Radix_sort.c new file mode 100644 index 00000000..084540f0 --- /dev/null +++ b/C/Radix_sort.c @@ -0,0 +1,92 @@ +/* +This is implementation of Radix sort for variable base +@Author Srinidh Reddy +*/ + +#include +#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/Vowel or Consonant using pointers.c b/C/Vowel or Consonant using pointers.c new file mode 100644 index 00000000..6c023391 --- /dev/null +++ b/C/Vowel or Consonant using pointers.c @@ -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/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.c b/C/corrected_calculator_c.c new file mode 100644 index 00000000..718e5b8d --- /dev/null +++ b/C/corrected_calculator_c.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/infixtopostfix.c b/C/infixtopostfix.c new file mode 100644 index 00000000..df34b67a --- /dev/null +++ b/C/infixtopostfix.c @@ -0,0 +1,141 @@ +#include +#include +#include +#include + +typedef struct NODE +{ + char symbol; + int precedence; + int Rank; +} NODE; + +NODE INFIXOperators[] = {{'+', 1, -1}, {'-', 1, -1}, {'*', 3, -1}, {'/', 3, -1}, {'^', 5, -1}, {'(', 9}, {')', 0}}, + STACKOperators[] = {{'+', 2, -1}, {'-', 2, -1}, {'*', 4, -1}, {'/', 4, -1}, {'^', 6, -1}, {'(', 0}, {')', 0}}; + +int findrank(char a) +{ + int rank = 1; + for (int i = 0; i < 6; i++) + { + //printf("%c\t%c\n", a, INFIXOperators[i].symbol); + if (a == INFIXOperators[i].symbol) + { + rank = INFIXOperators[i].Rank; + break; + } + } + + return rank; +} +int ishigherprec(char a, char b) +{ + int aprec = 7, bprac = 8; + for (int i = 0; i < 7; i++) + { + if (a == INFIXOperators[i].symbol) + aprec = INFIXOperators[i].precedence; + if (b == STACKOperators[i].symbol) + bprac = STACKOperators[i].precedence; + } + + //printf("%d\t%d\n", aprec, bprac); + + if (aprec > bprac) + { + return 1; + } + else if (aprec == bprac) + return 0; + else + return -1; +} +typedef struct STACK +{ + char *data; + int top; +} STACK; + +void PUSH(STACK *s, char symbol) +{ + + s->data = (char *)realloc(s->data, sizeof(char) * (s->top + 1)); + s->data[s->top] = symbol; + s->top++; +} +char POP(STACK *s) +{ + char temp = s->data[s->top - 1]; + s->data[s->top - 1] = '\0'; + s->top--; + return temp; +} + +void display(STACK *s) +{ + for (int i = 0; i < s->top; i++) + { + printf("%c", s->data[i]); + } + printf("\n"); +} + +int main() +{ + char *INFIX, *R_POLISH, i, next; + int len = 0, Plen = 0, RANK = 0, a = 0; + STACK S; + + INFIX = (char *)malloc(sizeof(char) * 100); + R_POLISH = (char *)malloc(sizeof(char) * 100); + R_POLISH[0] = '\0'; + S.top = 0; + S.data = NULL; + PUSH(&S, '('); + + scanf("%c", &i); + while (i != '\n') + { + INFIX[len] = i; + len++; + scanf("%c", &i); + } + + INFIX[len++] = ')'; + INFIX[len] = '\0'; + + //puts(INFIX); + + next = INFIX[a++]; + + while (next != '\0') + { + if (S.top < 1) + { + printf("top is little"); + exit(0); + } + while (ishigherprec(next, S.data[S.top - 1]) == -1) + { + char temp = POP(&S); + R_POLISH[Plen++] = temp; + //display(&S); + RANK += findrank(temp); + if (RANK < 1) + { + printf("rank is small"); + exit(0); + } + } + if (ishigherprec(next, S.data[S.top - 1]) != 0) + { + PUSH(&S, next); + } + else + POP(&S); + next = INFIX[a++]; + } + + R_POLISH[Plen] = '\0'; + puts(R_POLISH); +} 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/matrix multiplication for unknown matrix.c b/C/matrix multiplication for unknown matrix.c new file mode 100644 index 00000000..383b5faf --- /dev/null +++ b/C/matrix multiplication for unknown matrix.c @@ -0,0 +1,38 @@ +//matrix multiplication // +#include +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"); + } +} 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/Client Server Paradigm - Soket Programming/README.md b/Client Server Paradigm - Soket Programming/README.md new file mode 100644 index 00000000..8079f0dd --- /dev/null +++ b/Client Server Paradigm - Soket Programming/README.md @@ -0,0 +1,54 @@ + +## About the Project + +This project was build to learn the fundamentals of socket programming. Berkeley socket interface is used for implementing whatever I learned. +The main features of this program are : +1. Implemented client server paradigm. +2. Functionality of sending and receiving text messages, basically a chat application. +3. Functionality of sending various files such as text/images/audio/video. + +### Screenshots +Running the server and client on same machine +![Product Name Screen Shot][screenshot1] + +Sending a file +![Product Name Screen Shot][screenshot2] + +Sending an txt file +![Product Name Screen Shot][screenshot4] + +Sending a image +![Product Name Screen Shot][screenshot5] + +Sending a audio file +![Product Name Screen Shot][screenshot6] + +Sending a video file +![Product Name Screen Shot][screenshot7] + +Chatting with the server +![Product Name Screen Shot][screenshot8] + + + + +### Installation + +1. Open the terminal run the server and give a port no. +```sh +./server portno +``` +2. Open another terminal and run the client. If you are running the code in same machine then give address as 127.0.0.1 or if you are running the client in another machine then pass the server ip adderess (Can be found usisng ifconfig). Make sure that the port no. in both the cases are same +```sh +./client 127.0.0.1 portno +``` + + +[screenshot1]: screenshots/ss1.png +[screenshot2]: screenshots/ss2.png +[screenshot3]: screenshots/ss3.png +[screenshot4]: screenshots/ss4.png +[screenshot5]: screenshots/ss5.png +[screenshot6]: screenshots/ss6.png +[screenshot7]: screenshots/ss7.png +[screenshot8]: screenshots/ss8.png diff --git a/Client Server Paradigm - Soket Programming/client b/Client Server Paradigm - Soket Programming/client new file mode 100644 index 00000000..361d2e10 Binary files /dev/null and b/Client Server Paradigm - Soket Programming/client differ diff --git a/Client Server Paradigm - Soket Programming/client.c b/Client Server Paradigm - Soket Programming/client.c new file mode 100644 index 00000000..5799f02d --- /dev/null +++ b/Client Server Paradigm - Soket Programming/client.c @@ -0,0 +1,411 @@ +/* Created by pycrash */ + +/* Socket programming in c to implement client server paradigm, this program offers mainly two functionalities - +chatting among server and client using sockets, +and sending files from client to server */ + +/* +provide three arguments +filename server_ip_address port_no + +argv[0] filename +argv[1] server_ip_address +argv[2] port_no + +*/ + +/*Client Model should have following functions +1) Socket +2) Connect +3) Write +4) Read +5) close +*/ + + //Contains declarartions for input and output +#include + //Defines 4 variable types, several macros and various functions + //We will use atoi function to convert the string pointed to, by the argument to an integer +#include + //defines one variable type, one macro, and various functions for manipulating arrays of characters +#include + //for read, write and close +#include + //conatins definitions of a no. of data types used in system calls +#include + //contains constants and structures needed for internet domain addresses e.g. sockaddr_in +#include + //definitions of structures needed for sockets e.g. defines sockaddr structure +#include + //contains definition of Hostent structure +#include + //declares several functions that are useful for testing and mapping characters. +#include + // defines the structure of the data returned by the function fstat() +#include + //defines the following requests and arguments for use by the functions fcntl() and open() +#include + //definitions for internet operations +#include + +//Error function to exit the program +void error(const char *msg) +{ + /*perror is an inbuilt function that interprets the error no. and outputs the + output error description by using STDERR */ + + perror(msg); + exit(1); +} + +int main(int argc, char *argv[]) +{ + /*The user need to provide 3 arguments, first one the file name, + second one -the ip address of server and lastly the port no. */ + + //socketfd is file descriptor + int socketfd, portno, n; + + //sockaddr_in gives internet address + struct sockaddr_in serv_address; + + //hostent structure is used to store info about the host such as host name, an IPv4 address etc. + struct hostent * server; + int sourse_fd; + + //buffer will be transferred in a data stream + char buffer[1024]; + + //variables for operation - send file, chat etc. + int operation, sub_operation; + + //file name variable + char str[20]; + int file_name_len, read_len; + + //checking if user provided 3 arguments or not + if (argc < 3) + { + //Terminating the program as user didnt provide 3 arguments + fprintf(stderr, "usage %s hostname port\n", argv[0]); + exit(0); + } + + //converting the string argument into an int + portno = atoi(argv[2]); + + //socket function returns a file descriptor, if its less than 0 then there is an error opening socket + /*socket function has 3 arguments, first one is domain, here we will use AF_INET which is an IPv4 protocol, + second argument is type, we will use SOCK_STREAM as it for TCP protocol, If we were to use UDP protocl, we would have provide SOCK_DGRAM as second argument, + third argument is protocol, which is 0 for TCP */ + socketfd = socket(AF_INET, SOCK_STREAM, 0); + + if (socketfd < 0) + { + //File descrpitor is less than 0, error opening socket + error("Error opening socket"); + } + + //getting info about host + server = gethostbyname(argv[1]); + if (server == NULL) + { + //server is null, no host exists + fprintf(stderr, "No such host exists"); + } + + //bzero clears data or anything in whatever it is refrenced to + //clearing serv_address so as to do operations on it + bzero((char*) &serv_address, sizeof(serv_address)); + + /*getting info such as port, using htons - host to network short, + converts port no. in host byte order to port no. in network byte order */ + serv_address.sin_family = AF_INET; + bcopy((char*) server->h_addr, (char*) &serv_address.sin_addr.s_addr, server->h_length); + serv_address.sin_port = htons(portno); + + //conneting to host, if file descriptor is less than 0, then the operation failed + if (connect(socketfd, (struct sockaddr *) &serv_address, sizeof(serv_address)) < 0) + error("connection Failed"); + + //clearing everything in the output buffer of a stream + fflush(stdout); + + //Asking user what he wants to do + printf("What do you want me to do ?\n 1) Send File\n 2) Chat with server \nPress other key to terminate\n "); + //getting user input + scanf("%d", &operation); + + //we will send this operation no. to server, so that server can execute operations accordingly + int number_to_send; + fflush(stdout); + number_to_send = operation; + int converted_number = htonl(number_to_send); + + // Telling the server about the operation using write, there is a corresponding read in the server + write(socketfd, &converted_number, sizeof(converted_number)); + + //performing the operation according to user + switch (operation) + { + case 1: + //user selected send file + { + //asking user which type of file he/she wants to send + bzero(str, 20); + printf("Which type of file you want to send? \n1) Text file \n2) Image \n3) Audio \n4) Video \nPress any other key to terminate the program\n"); + + //we will send this sub - operation no. to server, so that server can execute sub-operations accordingly + scanf("%d", &sub_operation); + int sub_number_to_send; + + //Telling the server about the sub - operation + fflush(stdout); + sub_number_to_send = sub_operation; + int sub_converted_number = htonl(sub_number_to_send); + + // Telling the server about the sub-operation + write(socketfd, &sub_converted_number, sizeof(sub_converted_number)); + + switch (sub_operation) + { + //performing the sub operation according to user + case 1: + { + //User selected txt file + //asking the user, the name of the file he wants to send + //Note : The file should be in the same directory as this client.c file + printf("Type the name of your file that you want to send with the extension. Make sure that the file is in same directory as this file\n"); + + //clearing everything in str, so as to save the file name in str + //we will send this file name to server + bzero(str, 20); + scanf("%s", str); + n = write(socketfd, str, strlen(str)); + + //Starting the operation to send the txt file + FILE * f; + + int words = 0; + char c; + f = fopen(str, "r"); + while ((c = getc(f)) != EOF) + //Counting No of words in the file + { + fscanf(f, "%s", buffer); + if (isspace(c) || c == '\t') + words++; + } + //For printing the no. of words + //printf("Words = %d \n", words); + + write(socketfd, &words, sizeof(int)); + rewind(f); + + // tells size of the file. Not required for the functionality in code. + /* + fseek(f, 0L, SEEK_END); + int sz = ftell(f); + printf("Size is %d \n", sz); + rewind(f); + */ + + char ch; + /* + On getting EOF (or error) from standard input, the client Stdin process, before it exits, needs to tell + the server that the client is done and there is nothing more coming down + the socket. The client has to signal "EOF" to the server. + */ + //So we will keep sending the file through buffer until EOF is encountered + while (ch != EOF) + { + + fscanf(f, "%s", buffer); + //For printing every word in the file + //printf("%s\n", buffer); + write(socketfd, buffer, 512); + ch = fgetc(f); + } + //The operation executed successfully + //The file was sent successfully + printf("The file was sent successfully\n"); + break; + } + case 2: + + { + + /*memset copies the character 0 (an unsigned char) to the first 1024 characters of the string pointed to, by the argument buffer*/ + memset(buffer, 0x00, 1024); + + //User selected img file + //asking the user, the name of the file he wants to send + //Note : The file should be in the same directory as this client.c file + printf("Type the name of your image that you want to send with the extension. Make sure that the file is in same directory as this file\n"); + scanf("%s", buffer); + printf("Sending your Image\n"); + file_name_len = strlen(buffer); + + //sending file name to server + send(socketfd, buffer, file_name_len, 0); + + //opening the file in the buffer for reading + sourse_fd = open(buffer, O_RDONLY); + if (!sourse_fd) + { + //error opening the file + perror("Error reading file"); + return 1; + } + + while (1) + { + + //reading the file and then sending it through buffer, if read_len is 0 then there is nothing to send and the loop gets terminated + memset(buffer, 0x00, 1024); + read_len = read(sourse_fd, buffer, 1024); + send(socketfd, buffer, read_len, 0); + if (read_len == 0) + { + break; + } + } + //Image was sent successfully + printf("Image sent\n"); + break; + } + case 3: + { + /* memset copies the character 0 (an unsigned char) to the first 1024 characters of the string pointed to, by the argument buffer*/ + memset(buffer, 0x00, 1024); + + //User selected audio file + //asking the user, the name of the file he wants to send + //Note : The file should be in the same directory as this client.c file + printf("Type the name of your file that you want to send with the extension. Make sure that the file is in same directory as this file\n"); + scanf("%s", buffer); + printf("Sending your audio file\n"); + file_name_len = strlen(buffer); + + //sending file name to server + send(socketfd, buffer, file_name_len, 0); + + //opening the file in the buffer for reading + sourse_fd = open(buffer, O_RDONLY); + if (!sourse_fd) + { + //error opening the file + perror("Error : "); + return 1; + } + + while (1) + { + //reading the file and then sending it through buffer, if read_len is 0 then there is nothing to send and the loop gets terminated + memset(buffer, 0x00, 1024); + read_len = read(sourse_fd, buffer, 1024); + send(socketfd, buffer, read_len, 0); + if (read_len == 0) + { + break; + } + } + //Audio file was sent successfully + printf("Audio sent\n"); + break; + } + case 4: + { + /* memset copies the character 0 (an unsigned char) to the first 1024 characters of the string pointed to, by the argument buffer */ + memset(buffer, 0x00, 1024); + + //User selected video file + //asking the user, the name of the file he wants to send + //Note : The file should be in the same directory as this client.c file + printf("Type the name of your file that you want to send with the extension. Make sure that the file is in same directory as this file\n"); + scanf("%s", buffer); + + printf("Sending your video file\n"); + file_name_len = strlen(buffer); + + //sending file name to server + send(socketfd, buffer, file_name_len, 0); + + //opening the file in the buffer for reading + sourse_fd = open(buffer, O_RDONLY); + if (!sourse_fd) + { + //error opening the file + perror("Error : "); + return 1; + } + + while (1) + { + //reading the file and then sending it through buffer, if read_len is 0 then there is nothing to send and the loop gets terminated + memset(buffer, 0x00, 1024); + read_len = read(sourse_fd, buffer, 1024); + send(socketfd, buffer, read_len, 0); + if (read_len == 0) + { + break; + } + } + //Video file was sent successfully + printf("Video sent\n"); + break; + } + default: + exit(0); + } + break; + } + case 2: + //user selected chat with server + //lets have a chat then + while (1) + { + + //clearing buffer as will stream data through buffer only + fflush(stdout); + bzero(buffer, 1024); + + //fgets reads a line from the specified stream and stores it into the string pointed to by buffer. + fgets(buffer, 1024, stdin); + + //sending whatever is in buffer to sever + n = write(socketfd, buffer, strlen(buffer)); + + if (n < 0) + //file descriptor returns -1 which means write failed + error("Error Writing"); + + //again clearing buffer for reading data from server + bzero(buffer, 512); + //reading data from server + n = read(socketfd, buffer, 1024); + if (n < 0) + { + //file descriptor returns -1 which means read failed + error("Error reading"); + } + printf("Server: %s\n", buffer); + + //Server or client can anytime close the chat with keyword "Bye" + int i = strncmp("Bye", buffer, 3); + if (i == 0) + break; + } + break; + + default: + //user entered other keyword, so we have to terminate the program + printf("Other key entered, terminating"); + exit(0); + } + + //closing the socket + + close(socketfd); + return 0; +} diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss1.png b/Client Server Paradigm - Soket Programming/screenshots/ss1.png new file mode 100644 index 00000000..7483acaf Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss1.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss2.png b/Client Server Paradigm - Soket Programming/screenshots/ss2.png new file mode 100644 index 00000000..8ffbae54 Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss2.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss3.png b/Client Server Paradigm - Soket Programming/screenshots/ss3.png new file mode 100644 index 00000000..87b86af2 Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss3.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss4.png b/Client Server Paradigm - Soket Programming/screenshots/ss4.png new file mode 100644 index 00000000..b2d79042 Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss4.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss5.png b/Client Server Paradigm - Soket Programming/screenshots/ss5.png new file mode 100644 index 00000000..ee00ec6e Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss5.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss6.png b/Client Server Paradigm - Soket Programming/screenshots/ss6.png new file mode 100644 index 00000000..1b15ba62 Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss6.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss7.png b/Client Server Paradigm - Soket Programming/screenshots/ss7.png new file mode 100644 index 00000000..286e141f Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss7.png differ diff --git a/Client Server Paradigm - Soket Programming/screenshots/ss8.png b/Client Server Paradigm - Soket Programming/screenshots/ss8.png new file mode 100644 index 00000000..ffc2201c Binary files /dev/null and b/Client Server Paradigm - Soket Programming/screenshots/ss8.png differ diff --git a/Client Server Paradigm - Soket Programming/server b/Client Server Paradigm - Soket Programming/server new file mode 100644 index 00000000..0d9f125d Binary files /dev/null and b/Client Server Paradigm - Soket Programming/server differ diff --git a/Client Server Paradigm - Soket Programming/server.c b/Client Server Paradigm - Soket Programming/server.c new file mode 100644 index 00000000..08fc102c --- /dev/null +++ b/Client Server Paradigm - Soket Programming/server.c @@ -0,0 +1,408 @@ +/* Created by pycrash */ + +/* Socket programming in c to implement client server paradigm, this program offers mainly two functionalities - +chatting among server and client using sockets, +and sending files from client to server */ + +/* +stdio.h contains declarations for unput and output + +stdlib.h contains declarations of variable types, macros and functions +We will be using atoi function of stlib which converts a string pointed to, by the argument into an int + +unistd.h contains read write close functions + +sys/types.h contains definitions of data types used in sysytem calls + +sys/socket.h contains structers needed for socket. sockaddr structure is in this file only + +netinet/in.h contains constants and structures needed for internet domain address. sockaddr_in is in this file only + +*/ + +/*Server Model should have following functions +1) Socket +2) Bind +3) listen +4) Accept +5) Read +6) Write +7) close +*/ + + //Contains declarartions for input and output +#include + //Defines 4 variable types, several macros and various functions + //We will use atoi function to convert the string pointed to, by the argument to an integer +#include + //defines one variable type, one macro, and various functions for manipulating arrays of characters +#include + //for read, write and close +#include + //conatins definitions of a no. of data types used in system calls +#include + //contains constants and structures needed for internet domain addresses e.g. sockaddr_in +#include + //definitions of structures needed for sockets e.g. defines sockaddr structure +#include + //contains definition of Hostent structure +#include + //declares several functions that are useful for testing and mapping characters. +#include + // defines the structure of the data returned by the function fstat() +#include + //defines the following requests and arguments for use by the functions fcntl() and open() +#include + //definitions for internet operations +#include + //contains system error numbers +#include + +//Error function to exit the program +void error(const char *msg) +{ + /*perror is an inbuilt function that interprets the error no. and outputs the + output error description by using STDERR */ + + perror(msg); + exit(1); +} + +int main(int argc, char *argv[]) +{ + /*The user need to provide 2 arguments, first one the file name, + and secondly the port no. */ + + //checking if user provided 2 arguments or not + if (argc < 2) + { + //Terminating the program as user didnt provide 2 arguments + fprintf(stderr, "Please provide a port number, program is terminated\n"); + exit(1); + } + + //socketfd and newsocketfd is file descriptor, newsocketfd is for client + int socketfd, newsocketfd, portno, n; + + //file name variable + char str[20]; + int client_len, read_len, file_read_len; + int des_fd; + + //variables for operation - send file, chat etc. + int received_int, sub_received_int; + int operation, return_status, sub_return_status; + int sub_operation; + + //buffer will be transferred in a data stream + char buffer[1024]; + + //sockaddr_in gives internet address + struct sockaddr_in serv_address, client_address; + socklen_t clilen; + + //socket function returns a file descriptor, if its less than 0 then there is an error opening socket + /*socket function has 3 arguments, first one is domain, here we will use AF_INET which is an IPv4 protocol, + second argument is type, we will use SOCK_STREAM as it for TCP protocol, If we were to use UDP protocl, we would have provide SOCK_DGRAM as second argument, + third argument is protocol, which is 0 for TCP */ + socketfd = socket(AF_INET, SOCK_STREAM, 0); + + if (socketfd < 0) + { + //File descrpitor is less than 0, error opening socket + error("Error opening socket"); + } + + //bzero clears data or anything in whatever it is refrenced to + //clearing serv_address so as to do operations on it + bzero((char*) &serv_address, sizeof(serv_address)); + + //converting the string argument into an int + portno = atoi(argv[1]); + + /*getting info such as port, using htons - host to network short, + converts port no. in host byte order to port no. in network byte order */ + serv_address.sin_family = AF_INET; + serv_address.sin_addr.s_addr = INADDR_ANY; + serv_address.sin_port = htons(portno); + + /*bind assigns the address specified by addr */ + if (bind(socketfd, (struct sockaddr *) &serv_address, sizeof(serv_address)) < 0) + error("Binding Failed"); + + /*listen marks the socketfd as passive soocket i.e. A socket that will be used for accepting incoming connections using accept */ + listen(socketfd, 5); + clilen = sizeof(client_address); + + /*accept function also returns a file descriptor and waits for connect and whenever connect is triggered by client, accept is called by host */ + newsocketfd = accept(socketfd, (struct sockaddr *) &client_address, &clilen); + + if (newsocketfd < 0) + error("Error Accepting"); + + /*getting the operation by the user */ + return_status = read(newsocketfd, &received_int, sizeof(received_int)); + if (return_status > 0) + { + //printing the opeartion code + fprintf(stdout, "Operation code = %d\n", ntohl(received_int)); + operation = ntohl(received_int); + } + + //performing the operation according to user + switch (operation) + { + case 1: + //user selected send file + { + //asking user which type of file he/she wants to send + sub_return_status = read(newsocketfd, &sub_received_int, sizeof(sub_received_int)); + if (return_status > 0) + { + //printing the sub operation code + fprintf(stdout, "Sub Operation code = %d\n", ntohl(sub_received_int)); + sub_operation = ntohl(sub_received_int); + } + + switch (sub_operation) + { + //performing the sub operation according to user + case 1: + + { + + //User selected txt file + //reading the filename given by user + bzero(str, 20); + n = read(newsocketfd, str, 20); + int len = strlen(str); + + //manupilating the file name, the last 4 chars are the extension, so removing the extension from the name + str[len - 4] = '\0'; + if (n < 0) + error("Error Reading"); + + fprintf(stdout, "Received File Name = %s\n", str); + + //Starting the operation to receive the txt file + FILE * fp; + int ch = 0; + fp = fopen(strcat(str, "_received.txt"), "a"); + int words; + read(newsocketfd, &words, sizeof(int)); + //For counting words in txt file + printf("No of words in file is : %d\n", words); + + /* + Receiving the file until there are no words left + */ + //So we will keep sending the file through buffer until EOF is encountered + while (ch != words) + { + read(newsocketfd, buffer, 512); + fprintf(fp, " %s", buffer); + //For printing every word of file + //printf(" %s %d ", buffer, ch); + ch++; + } + //The operation executed successfully + //The file was recived successfully + printf("The file was received successfully\n"); + printf("The file is saved as %s\n", str); + + break; + } + case 2: + { + + char file_name[1024]; // local val + + /*memset copies the character 0 (an unsigned char) to the first 1024 characters of the string pointed to, by the argument buffer */ + memset(buffer, 0x00, 1024); + + /*file name */ + read_len = read(newsocketfd, buffer, 1024); + if (read_len > 0) + { + /*getting the file name and manupilating the file name, the last 4 chars are the extension, so removing the extension from the name*/ + strcpy(file_name, buffer); + int len = strlen(file_name); + file_name[len - 4] = '\0'; + } + else + { + //Error reading the file name, terminating the program + close(newsocketfd); + break; + } + + /*create file */ + + des_fd = open(strcat(file_name, "received.png"), O_WRONLY | O_CREAT | O_EXCL, 0700); + if (!des_fd) + { + perror("file open error : "); + break; + } + /*file save */ + while (1) + { + memset(buffer, 0x00, 1024); + file_read_len = read(newsocketfd, buffer, 1024); + write(des_fd, buffer, file_read_len); + if (file_read_len == EOF | file_read_len == 0) + { + //if block executed when EOF is encountered, meaning there is nothing left to receive + //The operation executed successfully + //The file was recived successfully + printf("Received Image file\n"); + printf("The file is saved as %s\n", file_name); + break; + } + } + break; + } + case 3: + { + char file_name[1024]; // local val + + /*memset copies the character 0 (an unsigned char) to the first 1024 characters of the string pointed to, by the argument buffer */ + memset(buffer, 0x00, 1024); + + /*file name */ + read_len = read(newsocketfd, buffer, 1024); + if (read_len > 0) + { + /* getting the file name and manupilating the file name, the last 4 chars are the extension, so removing the extension from the name */ + strcpy(file_name, buffer); + int len = strlen(file_name); + file_name[len - 4] = '\0'; + } + else + { + //Error reading the file name, terminating the program + close(newsocketfd); + break; + } + + /*create file */ + + des_fd = open(strcat(file_name, "received.mp3"), O_WRONLY | O_CREAT | O_EXCL, 0700); + if (!des_fd) + { + + perror("file open error : "); + break; + } + /*file save */ + while (1) + { + memset(buffer, 0x00, 1024); + file_read_len = read(newsocketfd, buffer, 1024); + write(des_fd, buffer, file_read_len); + if (file_read_len == EOF | file_read_len == 0) + { + //if block executed when EOF is encountered, meaning there is nothing left to receive + //The operation executed successfully + //The file was recived successfully + printf("Received audio file\n"); + printf("The file is saved as %s\n", file_name); + break; + } + } + break; + } + + case 4: + { + char file_name[1024]; // local val + + /*memset copies the character 0 (an unsigned char) to the first 1024 characters of the string pointed to, by the argument buffer */ + memset(buffer, 0x00, 1024); + + /*file name */ + read_len = read(newsocketfd, buffer, 1024); + if (read_len > 0) + { + /* getting the file name and manupilating the file name, the last 4 chars are the extension, so removing the extension from the name */ + strcpy(file_name, buffer); + int len = strlen(file_name); + file_name[len - 4] = '\0'; + } + else + { + //Error reading the file name, terminating the program + close(newsocketfd); + break; + } + + /*create file */ + + des_fd = open(strcat(file_name, "received.mp4"), O_WRONLY | O_CREAT | O_EXCL, 0700); + if (!des_fd) + { + + perror("file open error : "); + break; + } + /*file save */ + while (1) + { + memset(buffer, 0x00, 1024); + file_read_len = read(newsocketfd, buffer, 1024); + write(des_fd, buffer, file_read_len); + if (file_read_len == EOF | file_read_len == 0) + { + //if block executed when EOF is encountered, meaning there is nothing left to receive + //The operation executed successfully + //The file was recived successfully + printf("Received Video file\n"); + printf("The file is saved as %s\n", file_name); + break; + } + } + break; + } + default: + exit(0); + } + break; + } + case 2: + //user selected to chat + while (1) + { + //clearing buffer as will stream data through buffer only + bzero(buffer, 1024); + + //reading data from client + n = read(newsocketfd, buffer, 1024); + if (n < 0) + error("Error Reading"); + printf("Client: %s\n", buffer); + bzero(buffer, 1024); + //fgets reads a line from the specified stream and stores it into the string pointed to by buffer. + fgets(buffer, 1024, stdin); + + ////sending whatever is in buffer to client + n = write(newsocketfd, buffer, strlen(buffer)); + if (n < 0) + error("Error Writing"); + + //Server or client can anytime close the chat with keyword "Bye" + int i = strncmp("Bye", buffer, 3); + if (i == 0) + break; + } + break; + default: + //user entered other keyword, so we have to terminate the program + printf("Other key entered, terminating\n"); + exit(0); + } + + //closing the socket + close(newsocketfd); + close(socketfd); + return 0; +} diff --git a/Cpp/Bubble_sort.cpp b/Cpp/Bubble_sort.cpp new file mode 100644 index 00000000..6e13d570 --- /dev/null +++ b/Cpp/Bubble_sort.cpp @@ -0,0 +1,41 @@ +#include +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/Cpp/Circular_linked_list.cpp b/Cpp/Circular_linked_list.cpp new file mode 100644 index 00000000..4f84cb2d --- /dev/null +++ b/Cpp/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/Cpp/basic-search.cpp b/Cpp/basic-search.cpp new file mode 100644 index 00000000..fb0de6ee --- /dev/null +++ b/Cpp/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/Cpp/binary-search.cpp b/Cpp/binary-search.cpp new file mode 100644 index 00000000..f64a05af --- /dev/null +++ b/Cpp/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/Cpp/binaryExponentiation.cpp b/Cpp/binaryExponentiation.cpp new file mode 100644 index 00000000..11be513e --- /dev/null +++ b/Cpp/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/Cpp/bubble_sort_recursion.cpp b/Cpp/bubble_sort_recursion.cpp new file mode 100644 index 00000000..51ffa939 --- /dev/null +++ b/Cpp/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/Cpp/counting-sort.cpp b/Cpp/counting-sort.cpp new file mode 100644 index 00000000..ee1050f5 --- /dev/null +++ b/Cpp/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/Cpp/function overloading.cpp b/Cpp/function overloading.cpp new file mode 100644 index 00000000..53fe48bf --- /dev/null +++ b/Cpp/function overloading.cpp @@ -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< +using namespace std; + +int main() +{ + int i,j,n,temp,a[30]; + cout<<"Enter the number of elements : "; + cin>>n; + + cout<<"\nEnter the elements : "; + + for(i=0;i>a[i]; + + for(i=1;i<=n-1;i++) + { + temp=a[i]; + j=i-1; + + while((temp=0)) + { + a[j+1]=a[j]; //moves element forward + j=j-1; + } + + a[j+1]=temp; //insert element in proper place + } + + cout<<"\nSorted list is as follows\n"; + for(i=0;i +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/Cpp/merge-sort.cpp b/Cpp/merge-sort.cpp new file mode 100644 index 00000000..b6de43c3 --- /dev/null +++ b/Cpp/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/Cpp/mergesort.cpp b/Cpp/mergesort.cpp new file mode 100644 index 00000000..4404ed52 --- /dev/null +++ b/Cpp/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/Cpp/milkScheduling_greedy.cpp b/Cpp/milkScheduling_greedy.cpp new file mode 100644 index 00000000..dd8f4225 --- /dev/null +++ b/Cpp/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/Cpp/searching.cpp b/Cpp/searching.cpp new file mode 100644 index 00000000..d3a275a8 --- /dev/null +++ b/Cpp/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/Cpp/stack.cpp b/Cpp/stack.cpp new file mode 100644 index 00000000..a44fea85 --- /dev/null +++ b/Cpp/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/DFStraversal.c b/DFStraversal.c new file mode 100644 index 00000000..aa202fc9 --- /dev/null +++ b/DFStraversal.c @@ -0,0 +1,34 @@ +//a program for DFS traversal +#include +#define max 10 +void buildadjm(int adj[][max], int n) + { + int i,j; + for(i=0;i + + + + + 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(i +#include +struct Node +{ + int data; + struct Node *next; +}*Head; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + Head=(struct Node*)malloc(sizeof(struct Node)); + Head->data=A[0]; + Head->next=Head; + last=Head; + + for(i=1;idata=A[i]; + t->next=last->next; + last->next=t; + last=t; + } +} +void Display(struct Node *h) +{ + do + { + printf("%d ",h->data); + h=h->next; + }while(h!=Head); + printf("\n"); +} +void RDisplay(struct Node *h) +{ + static int flag=0; + if(h!=Head || flag==0) + { + flag=1; + printf("%d ",h->data); + RDisplay(h->next); + } + flag=0; +} +int Length(struct Node *p) +{ + int len=0; + do + { + len++; + p=p->next; + + }while(p!=Head); + return len; +} +void Insert(struct Node *p,int index, int x) +{ + struct Node *t; + int i; + if(index<0 || index > Length(p)) + return; + + if(index==0) + { + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + if(Head==NULL) + { + Head=t; + Head->next=Head; + } + else + { + while(p->next!=Head)p=p->next; + p->next=t; + t->next=Head; + Head=t; + } + + } + else + { + for(i=0;inext; + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + t->next=p->next; + p->next=t; + + } +} +int Delete(struct Node *p,int index) +{ + struct Node *q; + int i,x; + + if(index <0 || index >Length(Head)) + return -1; + if(index==1) + { + while(p->next!=Head)p=p->next; + x=Head->data; + if(Head==p) + { + free(Head); + Head=NULL; + } + else + { + p->next=Head->next; + free(Head); + Head=p->next; + } + } + else + { + for(i=0;inext; + q=p->next; + p->next=q->next; + x=q->data; + free(q); + } + return x; +} +int main() +{ + int A[]={2,3,4,5,6}; + create(A,5); + + Delete(Head,8); + + RDisplay(Head); + return 0; +} diff --git a/Linked List/Concat_LL.c b/Linked List/Concat_LL.c new file mode 100644 index 00000000..14bf6e4e --- /dev/null +++ b/Linked List/Concat_LL.c @@ -0,0 +1,75 @@ +//Concatenate two Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void create2(int A[],int n) +{ + int i; + struct Node *t,*last; + second=(struct Node *)malloc(sizeof(struct Node)); + second->data=A[0]; + second->next=NULL; + last=second; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Concat(struct Node *p,struct Node *q) +{ + third=p; + + while(p->next!=NULL) + p=p->next; + p->next=q; + +} +int main() +{ + + int A[]={10,20,40,50,60}; + int B[]={70,80,90,100,110}; + create(A,5); + create2(B,5); + + + Concat(frist,second); + Display(third); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Count_SumLinked_List.c b/Linked List/Count_SumLinked_List.c new file mode 100644 index 00000000..717065f3 --- /dev/null +++ b/Linked List/Count_SumLinked_List.c @@ -0,0 +1,73 @@ +Count and Sum Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +int count(struct Node *p) +{ + int l=0; + while(p) + { + l++; + p=p->next; + } + return l; +} +int Rcount(struct Node *p) +{ + if(p!=NULL) + return Rcount(p->next)+1; + else + return 0; +} +int sum(struct Node *p) +{ + int s=0; + + while(p!=NULL) + { + s+=p->data; + p=p->next; + } + return s; +} +int Rsum(struct Node *p) +{ + if(p==NULL) + return 0; + else + return Rsum(p->next)+p->data; +} +int main() +{ + int A[]={3,5,7,10,25,8,32,2}; + create(A,8); + + printf(“Count %d\n”,count(first)); + printf(“Sum %d\n”,sum(first); + + + + return 0; +} diff --git a/Linked List/Create_LL_using_Insert.c b/Linked List/Create_LL_using_Insert.c new file mode 100644 index 00000000..70b83470 --- /dev/null +++ b/Linked List/Create_LL_using_Insert.c @@ -0,0 +1,71 @@ +//Insert and create a Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void Insert(struct Node *p,int index,int x) +{ + struct Node *t; + int i; + + if(index < 0 || index > count(p)) + return; + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + + if(index == 0) + { + t->next=first; + first=t; + } + else + { + for(i=0;inext; + t->next=p->next; + p->next=t; + + } +} +int main() +{ + + Insert(first,0,15); + Insert(first,0,8); + Insert(first,0,9); + Insert(first,1,10); + Display(first); + + + + return 0; +} \ No newline at end of file diff --git a/Linked List/Create_and_Display_LL.c b/Linked List/Create_and_Display_LL.c new file mode 100644 index 00000000..56f64b87 --- /dev/null +++ b/Linked List/Create_and_Display_LL.c @@ -0,0 +1,53 @@ +//Display a Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void RDisplay(struct Node *p) +{ + if(p!=NULL) + { + RDisplay(p->next); + printf("%d ",p->data); + + } +} +int main() +{ + struct Node *temp; + int A[]={3,5,7,10,25,8,32,2}; + create(A,8); + + Display(first); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Deleteing_LL.c b/Linked List/Deleteing_LL.c new file mode 100644 index 00000000..c4bf1d7b --- /dev/null +++ b/Linked List/Deleteing_LL.c @@ -0,0 +1,85 @@ +//Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void RDisplay(struct Node *p) +{ + if(p!=NULL) + { + RDisplay(p->next); + printf("%d ",p->data); + + } +} +int Delete(struct Node *p,int index) +{ + struct Node *q=NULL; + int x=-1,i; + + if(index < 1 || index > count(p)) + return -1; + if(index==1) + { + q=first; + x=first->data; + first=first->next; + free(q); + return x; + } + else + { + for(i=0;inext; + } + q->next=p->next; + x=p->data; + free(p); + return x; + + } + + +} +int main() +{ + + int A[]={10,20,30,40,50}; + create(A,5); + + printf(“%d\n",Delete(first),2); + Display(first); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Deleting_from_LL.c b/Linked List/Deleting_from_LL.c new file mode 100644 index 00000000..eed678c1 --- /dev/null +++ b/Linked List/Deleting_from_LL.c @@ -0,0 +1,36 @@ +//Deleting from Linked List +#include +struct Array +{ + int A[10]; + int size; + int length; +}; + void Display(struct Array arr) + { + int i; + printf("\nElements are\n"); + for(i=0;i=0 && indexlength) + { + x=arr->A[index]; + for(i=index;ilength-1;i++) + arr->A[i]=arr->A[i+1]; + arr->length--; + return x; + } + return 0; +} +int main() +{ + struct Array arr1={{2,3,4,5,6},10,5}; + printf("%d",Delete(&arr1,0)); + Display(arr1); + return 0; +} \ No newline at end of file diff --git a/Linked List/Doubly_Linked_List.c b/Linked List/Doubly_Linked_List.c new file mode 100644 index 00000000..fcb68eda --- /dev/null +++ b/Linked List/Doubly_Linked_List.c @@ -0,0 +1,132 @@ +//Doubly Linked List +#include +#include +struct Node +{ + struct Node *prev; + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + struct Node *t,*last; + int i; + + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->prev=first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=last->next; + t->prev=last; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p) + { + printf("%d ",p->data); + p=p->next; + } + printf("\n"); +} +int Length(struct Node *p) +{ + int len=0; + + while(p) + { + len++; + p=p->next; + } + return len; +} +void Insert(struct Node *p,int index,int x) +{ + struct Node *t; + int i; + + if(index < 0 || index > Length(p)) + return; + if(index==0) + { + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + t->prev=NULL; + t->next=first; + first->prev=t; + first=t; + } + else + { + for(i=0;inext; + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + + t->prev=p; + t->next=p->next; + if(p->next)p->next->prev=t; + p->next=t; + + } +} +int Delete(struct Node *p,int index) +{ + //struct Node *q; + int x=-1,i; + + if(index < 1 || index > Length(p)) + return -1; + + if(index==1) + { + first=first->next; + if(first)first->prev=NULL; + + x=p->data; + free(p); + } + else + { + for(i=0;inext; + p->prev->next=p->next; + if(p->next) + p->next->prev=p->prev; + x=p->data; + free(p); + } + return x; + +} +void Reverse(struct Node *p) +{ + struct Node *temp; + + while(p!=NULL) + { + temp=p->next; + p->next=p->prev; + p->prev=temp; + p=p->prev; + if(p!=NULL && p->next==NULL) + first=p; + } +} +int main() +{ + int A[]={10,20,30,40,50}; + create(A,5); + + Reverse(first); + + Display(first); + return 0; +} \ No newline at end of file diff --git a/Linked List/Insert_in_LL.c b/Linked List/Insert_in_LL.c new file mode 100644 index 00000000..587d8b43 --- /dev/null +++ b/Linked List/Insert_in_LL.c @@ -0,0 +1,71 @@ +//Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void Insert(struct Node *p,int index,int x) +{ + struct Node *t; + int i; + + if(index < 0 || index > count(p)) + return; + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + + if(index == 0) + { + t->next=first; + first=t; + } + else + { + for(i=0;inext; + t->next=p->next; + p->next=t; + + } + + +} +int main() +{ + + int A[]={10,20,30,40,50}; + create(A,5); + + + Insert(first,0,5); + Display(first); + return 0; +} \ No newline at end of file diff --git a/Linked List/LinearLinkedList.c b/Linked List/LinearLinkedList.c new file mode 100644 index 00000000..67708497 --- /dev/null +++ b/Linked List/LinearLinkedList.c @@ -0,0 +1,148 @@ +//Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void RDisplay(struct Node *p) +{ + if(p!=NULL) + { + RDisplay(p->next); + printf("%d ",p->data); + + } +} +int count(struct Node *p) +{ + int l=0; + while(p) + { + l++; + p=p->next; + } + return l; +} +int Rcount(struct Node *p) +{ + if(p!=NULL) + return Rcount(p->next)+1; + else + return 0; +} +int sum(struct Node *p) +{ + int s=0; + + while(p!=NULL) + { + s+=p->data; + p=p->next; + } + return s; +} +int Rsum(struct Node *p) +{ + if(p==NULL) + return 0; + else + return Rsum(p->next)+p->data; +} +int Max(struct Node *p) +{ + int max=INT32_MIN; + + while(p) + { + if(p->data>max) + max=p->data; + p=p->next; + } + return max; + +} +int RMax(struct Node *p) +{ + int x=0; + + if(p==0) + return INT32_MIN; + x=RMax(p->next); + if(x>p->data) + return x; + else + return p->data; +} +struct Node * LSearch(struct Node *p,int key) +{ + struct Node *q; + + while(p!=NULL) + { + if(key==p->data) + { + q->next=p->next; + p->next=first; + first=p; + return p; + } + q=p; + p=p->next; + } + return NULL; + +} +struct Node * RSearch(struct Node *p,int key) +{ + if(p==NULL) + return NULL; + if(key==p->data) + return p; + return RSearch(p->next,key); + +} +int main() +{ + struct Node *temp; + int A[]={3,5,7,10,25,8,32,2}; + create(A,8); + + temp=LSearch(first,25); + temp=LSearch(first,8); + if(temp) + printf("Key is Found %d\n",temp->data); + else + printf("Key not found\n"); + + Display(first); + + return 0; +} \ No newline at end of file diff --git a/Linked List/LinkedList_CPP.c b/Linked List/LinkedList_CPP.c new file mode 100644 index 00000000..26232dc9 --- /dev/null +++ b/Linked List/LinkedList_CPP.c @@ -0,0 +1,137 @@ +//Linked List CPP +#include +using namespace std; +class Node +{ +public: + int data; + Node *next; +}; +class LinkedList +{ +private: + Node *first; +public: + LinkedList(){first=NULL;} + LinkedList(int A[],int n); + ~LinkedList(); + + void Display(); + void Insert(int index,int x); + int Delete(int index); + int Length(); +}; +LinkedList::LinkedList(int A[],int n) +{ + Node *last,*t; + int i=0; + + first=new Node; + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +LinkedList::~LinkedList() +{ + Node *p=first; + while(first) + { + first=first->next; + delete p; + p=first; + } +} +void LinkedList::Display() +{ + Node *p=first; + + while(p) + { + cout<data<<" "; + p=p->next; + } + cout<next; + } + return len; +} +void LinkedList::Insert(int index,int x) +{ + Node *t,*p=first; + + if(index <0 || index > Length()) + return; + t=new Node; + t->data=x; + t->next=NULL; + + if(index==0) + { + t->next=first; + first=t; + } + else + { + for(int i=0;inext; + t->next=p->next; + p->next=t; + } +} +int LinkedList::Delete(int index) +{ + Node *p,*q=NULL; + int x=-1; + + if(index < 1 || index > Length()) + return -1; + if(index==1) + { + p=first; + first=first->next; + x=p->data; + delete p; + } + else + { + p=first; + for(int i=0;inext; + } + q->next=p->next; + x=p->data; + delete p; + } + return x; +} +int main() +{ + int A[]={1,2,3,4,5}; + LinkedList l(A,5); + + l.Insert(3,10); + + l.Display(); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Linked_List.c b/Linked List/Linked_List.c new file mode 100644 index 00000000..320a6f24 --- /dev/null +++ b/Linked List/Linked_List.c @@ -0,0 +1,399 @@ +//Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void create2(int A[],int n) +{ + int i; + struct Node *t,*last; + second=(struct Node *)malloc(sizeof(struct +Node)); + second->data=A[0]; + second->next=NULL; + last=second; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void RDisplay(struct Node *p) +{ + if(p!=NULL) + { + RDisplay(p->next); + printf("%d ",p->data); + + } +} +int count(struct Node *p) +{ + int l=0; + while(p) + { + l++; + p=p->next; + } + return l; +} +int Rcount(struct Node *p) +{ + if(p!=NULL) + return Rcount(p->next)+1; + else + return 0; +} +int sum(struct Node *p) +{ + int s=0; + + while(p!=NULL) + { + s+=p->data; + p=p->next; + } + return s; +} +int Rsum(struct Node *p) +{ + if(p==NULL) + return 0; + else + return Rsum(p->next)+p->data; +} +int Max(struct Node *p) +{ + int max=INT32_MIN; + + while(p) + { + if(p->data>max) + max=p->data; + p=p->next; + } + return max; + +} +int RMax(struct Node *p) +{ + int x=0; + + if(p==0) + return INT32_MIN; + x=RMax(p->next); + if(x>p->data) + return x; + else + return p->data; +} +struct Node * LSearch(struct Node *p,int key) +{ + struct Node *q=NULL; + + while(p!=NULL) + { + if(key==p->data) + { + if(p!=first) + { + q->next=p->next; + p->next=first; + first=p; + } + return p; + } + q=p; + p=p->next; + } + return NULL; + +} +struct Node * RSearch(struct Node *p,int key) +{ + if(p==NULL) + return NULL; + if(key==p->data) + return p; + return RSearch(p->next,key); + +} +void Insert(struct Node *p,int index,int x) +{ + struct Node *t; + int i; + + if(index < 0 || index > count(p)) + return; + t=(struct Node *)malloc(sizeof(struct Node)); + t->data=x; + + if(index == 0) + { + t->next=first; + first=t; + } + else + { + for(i=0;inext; + t->next=p->next; + p->next=t; + + } + + +} +void SortedInsert(struct Node *p,int x) +{ + struct Node *t,*q=NULL; + + t=(struct Node*)malloc(sizeof(struct Node)); + t->data=x; + t->next=NULL; + + if(first==NULL) + first=t; + else + { + while(p && p->datanext; + } + if(p==first) + { + t->next=first; + first=t; + } + else + { + t->next=q->next; + q->next=t; + } + } + +} +int Delete(struct Node *p,int index) +{ + struct Node *q=NULL; + int x=-1,i; + + if(index < 1 || index > count(p)) + return -1; + if(index==1) + { + q=first; + x=first->data; + first=first->next; + free(q); + return x; + } + else + { + for(i=0;inext; + } + q->next=p->next; + x=p->data; + free(p); + return x; + + } + + +} +int isSorted(struct Node *p) +{ + int x=-65536; + + while(p!=NULL) + { + if(p->data < x) + return 0; + x=p->data; + p=p->next; + } + return 1; + +} +void RemoveDuplicate(struct Node *p) +{ + struct Node *q=p->next; + + while(q!=NULL) + { + if(p->data!=q->data) + { + p=q; + q=q->next; + } + else + { + p->next=q->next; + free(q); + q=p->next; + } + } + +} +void Reverse1(struct Node *p) +{ + int *A,i=0; + struct Node *q=p; + + A=(int *)malloc(sizeof(int)*count(p)); + + while(q!=NULL) + { + A[i]=q->data; + q=q->next; + i++; + } + q=p; + i--; + while(q!=NULL) + { + q->data=A[i]; + q=q->next; + i--; + } +} +void Reverse2(struct Node *p) +{ + struct Node *q=NULL,*r=NULL; + + while(p!=NULL) + { + r=q; + q=p; + p=p->next; + q->next=r; + } + first=q; +} +void Reverse3(struct Node *q,struct Node *p) +{ + if(p) + { + Reverse3(p,p->next); + p->next=q; + } + else + first=q; +} +void Concat(struct Node *p,struct Node *q) +{ + third=p; + + while(p->next!=NULL) + p=p->next; + p->next=q; + +} +void Merge(struct Node *p,struct Node *q) +{ + struct Node *last; + if(p->data < q->data) + { + third=last=p; + p=p->next; + third->next=NULL; + } + else + { + third=last=q; + q=q->next; + third->next=NULL; + } + while(p && q) + { + if(p->data < q->data) + { + last->next=p; + last=p; + p=p->next; + last->next=NULL; + + } + else + { + last->next=q; + last=q; + q=q->next; + last->next=NULL; + + } + } + if(p)last->next=p; + if(q)last->next=q; + +} +int isLoop(struct Node *f) +{ + struct Node *p,*q; + p=q=f; + + do + { + p=p->next; + q=q->next; + q=q?q->next:q; + }while(p && q && p!=q); + + if(p==q) + return 1; + else + return 0; +} +int main() +{ + struct Node *t1,*t2; + + int A[]={10,20,30,40,50}; + create(A,5); + + t1=first->next->next; + t2=first->next->next->next->next; + t2->next=t1; + + printf("%d\n",isLoop(first)); + + + return 0; +} \ No newline at end of file diff --git a/Linked List/Max_LL.c b/Linked List/Max_LL.c new file mode 100644 index 00000000..f547b9a5 --- /dev/null +++ b/Linked List/Max_LL.c @@ -0,0 +1,62 @@ +//Max element from Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +int Max(struct Node *p) +{ + int max=INT32_MIN; + + while(p) + { + if(p->data>max) + max=p->data; + p=p->next; + } + return max; + +} +int RMax(struct Node *p) +{ + int x=0; + + if(p==0) + return INT32_MIN; + x=RMax(p->next); + if(x>p->data) + return x; + else + return p->data; +} +int main() +{ + int A[]={3,5,7,10,25,8,32,2}; + create(A,8); + + printf(“Max %d\n”,Max(first); + + + + return 0; +} \ No newline at end of file diff --git a/Linked List/Merge_LL.c b/Linked List/Merge_LL.c new file mode 100644 index 00000000..f185db1f --- /dev/null +++ b/Linked List/Merge_LL.c @@ -0,0 +1,104 @@ +//Merge two Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void create2(int A[],int n) +{ + int i; + struct Node *t,*last; + second=(struct Node *)malloc(sizeof(struct Node)); + second->data=A[0]; + second->next=NULL; + last=second; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Merge(struct Node *p,struct Node *q) +{ + struct Node *last; + if(p->data < q->data) + { + third=last=p; + p=p->next; + third->next=NULL; + } + else + { + third=last=q; + q=q->next; + third->next=NULL; + } + while(p && q) + { + if(p->data < q->data) + { + last->next=p; + last=p; + p=p->next; + last->next=NULL; + + } + else + { + last->next=q; + last=q; + q=q->next; + last->next=NULL; + + } + } + if(p)last->next=p; + if(q)last->next=q; + +} +int main() +{ + + int A[]={10,20,40,50,60}; + int B[]={15,18,25,30,55}; + create(A,5); + create2(B,5); + + + Merge(frist,second); + Display(third); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Polynomial_Linked_List.c b/Linked List/Polynomial_Linked_List.c new file mode 100644 index 00000000..67480ee2 --- /dev/null +++ b/Linked List/Polynomial_Linked_List.c @@ -0,0 +1,62 @@ +//Polynomial Linked List +#include +#include +#include +struct Node +{ + int coeff; + int exp; + struct Node *next; +}*poly=NULL; +void create() +{ + struct Node *t,*last=NULL; + int num,i; + + printf("Enter number of terms"); + scanf("%d",&num); + printf("Enter each term with coeff and exp\n"); + + for(i=0;icoeff,&t->exp); + t->next=NULL; + if(poly==NULL) + { + poly=last=t; + } + else + { + last->next=t; + last=t; + } + } +} +void Display(struct Node *p) +{ + while(p) + { + printf("%dx%d +",p->coeff,p->exp); + p=p->next; + } + printf("\n"); +} +long Eval(struct Node *p, int x) +{ + long val=0; + + while(p) + { + val+=p->coeff*pow(x,p->exp); + p=p->next; + } + return val; +} +int main() +{ + create(); + Display(poly); + printf("%ld\n",Eval(poly,1)); + return 0; +} \ No newline at end of file diff --git a/Linked List/Remove_Duplicate_LL.c b/Linked List/Remove_Duplicate_LL.c new file mode 100644 index 00000000..d31a1e73 --- /dev/null +++ b/Linked List/Remove_Duplicate_LL.c @@ -0,0 +1,66 @@ +//Remove Duplicates from Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void RemoveDuplicate(struct Node *p) +{ + struct Node *q=p->next; + + while(q!=NULL) + { + if(p->data!=q->data) + { + p=q; + q=q->next; + } + else + { + p->next=q->next; + free(q); + q=p->next; + } + } + +} +int main() +{ + + int A[]={10,20,20,40,50,50,50,60}; + create(A,8); + + + RemoveDuplicate(frist); + Display(frist); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Reverse_LL.c b/Linked List/Reverse_LL.c new file mode 100644 index 00000000..70abf0cc --- /dev/null +++ b/Linked List/Reverse_LL.c @@ -0,0 +1,91 @@ +//Reverse a Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void Reverse1(struct Node *p) +{ + int *A,i=0; + struct Node *q=p; + + A=(int *)malloc(sizeof(int)*count(p)); + + while(q!=NULL) + { + A[i]=q->data; + q=q->next; + i++; + } + q=p; + i--; + while(q!=NULL) + { + q->data=A[i]; + q=q->next; + i--; + } +} +void Reverse2(struct Node *p) +{ + struct Node *q=NULL,*r=NULL; + + while(p!=NULL) + { + r=q; + q=p; + p=p->next; + q->next=r; + } + first=q; +} +void Reverse3(struct Node *q,struct Node *p) +{ + if(p) + { + Reverse3(p,p->next); + p->next=q; + } + else + first=q; +} +int main() +{ + + int A[]={10,20,40,50,60}; + create(A,5); + + + Reverse1(frist); + Display(frist); + + return 0; +} \ No newline at end of file diff --git a/Linked List/Search_LL.c b/Linked List/Search_LL.c new file mode 100644 index 00000000..9a01b0ec --- /dev/null +++ b/Linked List/Search_LL.c @@ -0,0 +1,64 @@ +//Display a Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL; +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +struct Node * LSearch(struct Node *p,int key) +{ + struct Node *q; + + while(p!=NULL) + { + if(key==p->data) + { + q->next=p->next; + p->next=first; + first=p; + return p; + } + q=p; + p=p->next; + } + return NULL; + +} +struct Node * RSearch(struct Node *p,int key) +{ + if(p==NULL) + return NULL; + if(key==p->data) + return p; + return RSearch(p->next,key); + +} +int main() +{ + struct Node *temp; + int A[]={3,5,7,10,25,8,32,2}; + create(A,8); + temp=Search(first,8); + printf(“%d”,temp->data); + + return 0; +} \ No newline at end of file diff --git a/Linked List/SortedInsert_LL.c b/Linked List/SortedInsert_LL.c new file mode 100644 index 00000000..b21c1cae --- /dev/null +++ b/Linked List/SortedInsert_LL.c @@ -0,0 +1,77 @@ +//Inserting in a Sorted Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +void SortedInsert(struct Node *p,int x) +{ + struct Node *t,*q=NULL; + + t=(struct Node*)malloc(sizeof(struct Node)); + t->data=x; + t->next=NULL; + + if(first==NULL) + first=t; + else + { + while(p && p->datanext; + } + if(p==first) + { + t->next=first; + first=t; + } + else + { + t->next=q->next; + q->next=t; + } + } + +} +int main() +{ + + int A[]={10,20,30,40,50}; + create(A,5); + + + printf(“%d\n”,SortedInsert(first,15)); + Display(first); + + + return 0; +} \ No newline at end of file diff --git a/Linked List/isLoop_LL.c b/Linked List/isLoop_LL.c new file mode 100644 index 00000000..71c7712f --- /dev/null +++ b/Linked List/isLoop_LL.c @@ -0,0 +1,67 @@ +//Checking for Loop Linked List +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +int isLoop(struct Node *f) +{ + struct Node *p,*q; + p=q=f; + + do + { + p=p->next; + q=q->next; + q=q?q->next:q; + }while(p && q && p!=q); + + if(p==q) + return 1; + else + return 0; +} +int main() +{ + struct Node *t1,*t2; + + int A[]={10,20,30,40,50}; + create(A,5); + + t1=first->next->next; + t2=first->next->next->next->next; + t2->next=t1; + + printf("%d\n",isLoop(first)); + + + return 0; +} \ No newline at end of file diff --git a/Linked List/isSorted_LL.c b/Linked List/isSorted_LL.c new file mode 100644 index 00000000..0e0ae180 --- /dev/null +++ b/Linked List/isSorted_LL.c @@ -0,0 +1,60 @@ +//Checking is a Linked List is Sorted +#include +#include +struct Node +{ + int data; + struct Node *next; +}*first=NULL,*second=NULL,*third=NULL; +void Display(struct Node *p) +{ + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } +} +void create(int A[],int n) +{ + int i; + struct Node *t,*last; + first=(struct Node *)malloc(sizeof(struct Node)); + first->data=A[0]; + first->next=NULL; + last=first; + + for(i=1;idata=A[i]; + t->next=NULL; + last->next=t; + last=t; + } +} +int isSorted(struct Node *p) +{ + int x=-65536; + + while(p!=NULL) + { + if(p->data < x) + return 0; + x=p->data; + p=p->next; + } + return 1; + +} +int main() +{ + + int A[]={10,20,30,40,50}; + create(A,5); + + + printf(“%d\n”,isSorted(first)); + + + return 0; +} \ No newline at end of file diff --git a/Python/Bubble_Sort_using_python.py b/Python/Bubble_Sort_using_python.py new file mode 100644 index 00000000..179130a4 --- /dev/null +++ b/Python/Bubble_Sort_using_python.py @@ -0,0 +1,15 @@ +def bubbleSort(arr): + for passnum in range(len(arr)-1,0,-1): + for i in range(passnum): + if arr[i]>arr[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/README.md b/README.md index cd6de503..e544e26b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,11 @@ -

Hacktoberfest 2020

+

Hacktoberfest 2021

*** +

+ + Link To HacktoberFest 2021 + +

## Event details : @@ -10,17 +15,9 @@ - Pull requests can be made in any GitHub-hosted repositories/projects. - You can sign up anytime between October 1 and October 31. -## HactoberFest 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 - -

+## 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). Pull requests can be made in any participating GitHub or GitLab hosted repository/project. Look for the 'hacktoberfest' topic to know if a repository/project is participating in Hacktoberfest. Pull requests must be approved by a maintainer of the repository/project to count. 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 55,000 participants who successfully complete the challenge will be eligible to receive a prize. ***

Whether it’s your first or fiftieth pull request, there’s always more to learn! We’ve put together a few resources that can help you create quality pull requests, keep your repositories pristine, and build on your open source knowledge.

@@ -36,12 +33,19 @@ To earn your Hacktoberfest tee or tree reward, you must register and make four v ## Rules To Contribute To This Repo - Use any language. -- C, C++, JAVA, Data Structure and Algorithms, HTML, CSS. +- C, C++, JAVA, Data Structure and Algorithms, HTML, CSS, Android Projects. - Anything valuable. ## 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/Recursion/Combination.c b/Recursion/Combination.c new file mode 100644 index 00000000..03114146 --- /dev/null +++ b/Recursion/Combination.c @@ -0,0 +1,28 @@ +//Combination Formula +#include +int fact(int n) +{ + if(n==0)return 1; + return fact(n-1)*n; +} +int nCr(int n,int r) +{ + int num,den; + + num=fact(n); + den=fact(r)*fact(n-r); + + return num/den; +} +int NCR(int n,int r) +{ + if(n==r || r==0) + return 1; + return NCR(n-1,r-1)+NCR(n-1,r); + +} +int main() +{ + printf("%d \n",NCR(5,3)); + return 0; +} \ No newline at end of file diff --git a/Recursion/Factorial.c b/Recursion/Factorial.c new file mode 100644 index 00000000..1902d192 --- /dev/null +++ b/Recursion/Factorial.c @@ -0,0 +1,21 @@ +//Factorial of N +int fact(int n) +{ + if(n==0) + return 1; + return fact(n-1)*n; +} +int Ifact(int n) +{ + int f=1,i; + for(i=1;i<=n;i++) + f=f*i; + + return f; +} +int main() +{ + int r=Ifact(5); + printf("%d ",r); + return 0; +} \ No newline at end of file diff --git a/Recursion/Fibonacci.c b/Recursion/Fibonacci.c new file mode 100644 index 00000000..b2a27ba5 --- /dev/null +++ b/Recursion/Fibonacci.c @@ -0,0 +1,49 @@ +//Fibonacci +#include +int fib(int n) +{ + int t0=0,t1=1,s=0,i; + + if(n<=1) return n; + + for(i=2;i<=n;i++) + { + s=t0+t1; + t0=t1; + t1=s; + } + + return s; +} +int rfib(int n) +{ + if(n<=1)return n; + return rfib(n-2)+rfib(n-1); +} +int F[10]; +int mfib(int n) +{ + if(n<=1) + { + F[n]=n; + return n; + } + else + { + if(F[n-2]==-1) + F[n-2]=mfib(n-2); + if(F[n-1]==-1) + F[n-1]=mfib(n-1); + F[n]=F[n-2]+F[n-1]; + return F[n-2]+F[n-1]; + } +} +int main() +{ + int i; + for(i=0;i<10;i++) + F[i]=-1; + + printf("%d \n",mfib(5)); + return 0; +} \ No newline at end of file diff --git a/Recursion/Indirect_Recursion.c b/Recursion/Indirect_Recursion.c new file mode 100644 index 00000000..117cae27 --- /dev/null +++ b/Recursion/Indirect_Recursion.c @@ -0,0 +1,24 @@ +//Indirect Recursion +#include +void funB(int n); +void funA(int n) +{ + if(n>0) + { + printf("%d ",n); + funB(n-1); + } +} +void funB(int n) +{ + if(n>1) + { + printf("%d ",n); + funA(n/2); + } +} +int main() +{ + funA(20); + return 0; +} \ No newline at end of file diff --git a/Recursion/Nested_Recursion.c b/Recursion/Nested_Recursion.c new file mode 100644 index 00000000..cc9276ed --- /dev/null +++ b/Recursion/Nested_Recursion.c @@ -0,0 +1,15 @@ +//Nested Recursion +#include +int fun(int n) +{ + if(n>100) + return n-10; + return fun(fun(n+11)); +} +int main() +{ + int r; + r=fun(95); + printf("%d\n",r); + return 0; +} \ No newline at end of file diff --git a/Recursion/Power.c b/Recursion/Power.c new file mode 100644 index 00000000..040b963c --- /dev/null +++ b/Recursion/Power.c @@ -0,0 +1,22 @@ +//Power Function +int power(int m,int n) +{ + if(n==0) + return 1; + return power(m,n-1)*m; +} +int power1(int m,int n) +{ + if(n==0) + return 1; + if(n%2==0) + return power1(m*m,n/ +2); + return m * power1(m*m,(n-1)/2); +} +int main() +{ + int r=power1(9,3); + printf("%d ",r); + return 0; +} \ No newline at end of file diff --git a/Recursion/StaticGlobal.c b/Recursion/StaticGlobal.c new file mode 100644 index 00000000..6d24988a --- /dev/null +++ b/Recursion/StaticGlobal.c @@ -0,0 +1,44 @@ +//Static Variables in Recursion +#include +int fun(int n) +{ + static int x=0; + if(n>0) + { + x++; + return fun(n-1)+x; + } + return 0; +} +int main() { + int r; + r=fun(5); + printf("%d\n",r); + + r=fun(5); + printf("%d\n",r); + + return 0; +} +Global Variabels in Recursion +#include +int x=0; +int fun(int n) +{ + if(n>0) + { + x++; + return fun(n-1)+x; + } + return 0; +} +int main() { + int r; + r=fun(5); + printf("%d\n",r); + + r=fun(5); + printf("%d\n",r); + + return 0; +} \ No newline at end of file diff --git a/Recursion/Sum_of_N.c b/Recursion/Sum_of_N.c new file mode 100644 index 00000000..910dde03 --- /dev/null +++ b/Recursion/Sum_of_N.c @@ -0,0 +1,21 @@ +//Sum of N natural numbers +int sum(int n) +{ + if(n==0) + return 0; + return sum(n-1)+n; +} +int Isum(int n) +{ + int s=0,i; + for(i=1;i<=n;i++) + s=s+i; + + return s; +} +int main() +{ + int r=sum(5); + printf("%d ",r); + return 0; +} \ No newline at end of file diff --git a/Recursion/TailHead_Recursion.c b/Recursion/TailHead_Recursion.c new file mode 100644 index 00000000..19ec3ee6 --- /dev/null +++ b/Recursion/TailHead_Recursion.c @@ -0,0 +1,36 @@ +//Head Recursion +#include +void fun(int n) +{ + if(n>0) + { + fun(n-1); + printf("%d ",n); + + } +} +int main() { + int x=3; + + fun(x); + return 0; +} +Tail Recursion +#include +void fun(int n) +{ + if(n>0) + { + printf("%d ",n); + fun(n-1); + + } +} +int main() { + int x=3; + + fun(x); + return +0 +; +} \ No newline at end of file diff --git a/Recursion/Tayloer_Series_Iterative.c b/Recursion/Tayloer_Series_Iterative.c new file mode 100644 index 00000000..d0386b44 --- /dev/null +++ b/Recursion/Tayloer_Series_Iterative.c @@ -0,0 +1,22 @@ +//Taylor Serie Iterative +#include +double e(int x, int n) +{ + double s=1; + int i; + double num=1; + double den=1; + + for(i=1;i<=n;i++) + { + num*=x; + den*=i; + s+=num/den; + } + return s; +} +int main() +{ + printf("%lf \n",e(1,10)); + return 0; +} \ No newline at end of file diff --git a/Recursion/Taylor.c b/Recursion/Taylor.c new file mode 100644 index 00000000..02241b4e --- /dev/null +++ b/Recursion/Taylor.c @@ -0,0 +1,55 @@ +//Taylor Series +double e(int x, int n) +{ + static double p=1,f=1; + double r; + + if(n==0) + return 1; + r=e(x,n-1); + p=p*x; + f=f*n; + return r+p/f; +} +int main() +{ + printf("%lf \n",e(4,15)); + return 0; +} +Taylor Series Horner’s Rule +double e(int x, int n) +{ + static double s; + if(n==0) + return s; + s=1+x*s/n; + return e(x,n-1); + +} +int main() +{ + printf("%lf \n",e(2,10)); + return 0; +} +Taylor Serie Iterative +#include +double e(int x, int n) +{ + double s=1; + int i; + double num=1; + double den=1; + + for(i=1;i<=n;i++) + { + num*=x; + den*=i; + s+=num/den; + } + return s; +} +int main() +{ + printf("%lf \n",e(1,10)); + return 0; +} \ No newline at end of file diff --git a/Recursion/Taylor_Series.c b/Recursion/Taylor_Series.c new file mode 100644 index 00000000..e7685783 --- /dev/null +++ b/Recursion/Taylor_Series.c @@ -0,0 +1,18 @@ +//Taylor Series using Static variables +double e(int x, int n) +{ + static double p=1,f=1; + double r; + + if(n==0) + return 1; + r=e(x,n-1); + p=p*x; + f=f*n; + return r+p/f; +} +int main() +{ + printf("%lf \n",e(4,15)); + return 0; +} \ No newline at end of file diff --git a/Recursion/Tower_of_Hanoi.c b/Recursion/Tower_of_Hanoi.c new file mode 100644 index 00000000..87d53b2b --- /dev/null +++ b/Recursion/Tower_of_Hanoi.c @@ -0,0 +1,16 @@ +//Tower of Hanoi +#include +void TOH(int n,int A,int B,int C) +{ + if(n>0) + { + TOH(n-1,A,C,B); + printf("(%d,%d)\n",A,C); + TOH(n-1,B,A,C); + } +} +int main() +{ + TOH(4,1,2,3); + return 0; +} \ No newline at end of file diff --git a/Recursion/TreeRecursion.c b/Recursion/TreeRecursion.c new file mode 100644 index 00000000..c4ccf8b5 --- /dev/null +++ b/Recursion/TreeRecursion.c @@ -0,0 +1,15 @@ +//Tree Recursion +#include +void fun(int n) +{ + if(n>0) + { + printf("%d ",n); + fun(n-1); + fun(n-1); + } +} +int main() { + fun(3); + return 0; +} \ No newline at end of file diff --git a/Remove_whiteSpace_from_string.c b/Remove_whiteSpace_from_string.c new file mode 100644 index 00000000..5c18a7e0 --- /dev/null +++ b/Remove_whiteSpace_from_string.c @@ -0,0 +1,22 @@ +#include + +int main() +{ + char a[1000], r[1000]; + int i = 0, j = 0; + printf("Enter the string: "); + gets(a); + + while(a[i] != '\0') + { + if(a[i] != ' ') + { + r[j]=a[i]; + j++; + } + i++; + } + r[j] = '\0'; + printf("\nResult String without whitespace is:- \n%s", r); + return 0; +} diff --git a/Stack implementation using Linked List.py b/Stack implementation using Linked List.py new file mode 100644 index 00000000..d7202808 --- /dev/null +++ b/Stack implementation using Linked List.py @@ -0,0 +1,52 @@ +#Implementing a stack using a linked list + +class Node: + def __init__(self,data,next): + self.data = data + self.next = next + + +class LinkedStack: + def __init__(self): + self.head = None + self.size = 0 + + def __len__(self): + return self.size + + def is_empty(self): + return self.size == 0 + + def push(self,e): + self.head = Node(e,self.head) + self.size += 1 + + def top(self): + if self.is_empty(): + raise Empty('Stack is empty') + + return self.head.data + + def pop(self): + if self.is_empty(): + raise Empty('Stack is empty') + answer = self.head.data + self.head = self.head.next + self.size -= 1 + return answer + + + def display(self): + temp = self.head + while(temp): + print(temp.data) + temp = temp.next + + +ls = LinkedStack() +ls.push(10) +ls.push(20) +ls.push(30) +ls.push(40) +ls.pop() +ls.display() diff --git a/Stack/Evaulation_Postfix.c b/Stack/Evaulation_Postfix.c new file mode 100644 index 00000000..cee64410 --- /dev/null +++ b/Stack/Evaulation_Postfix.c @@ -0,0 +1,149 @@ +//Evaluation of Postfix +#include +#include +#include +struct Node +{ + int data; + struct Node *next; +}*top=NULL; +void push(int x) +{ + struct Node *t; + t=(struct Node*)malloc(sizeof(struct Node)); + + if(t==NULL) + printf("stack is full\n"); + else + { + t->data=x; + t->next=top; + top=t; + } + +} +int pop() +{ + struct Node *t; + int x=-1; + + if(top==NULL) + printf("Stack is Empty\n"); + else + { + t=top; + top=top->next; + x=t->data; + free(t); + } + return x; +} +void Display() +{ + struct Node *p; + p=top; + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } + printf("\n"); +} +int isBalanced(char *exp) +{ + int i; + + for(i=0;exp[i]!='\0';i++) + { + if(exp[i]=='(') + push(exp[i]); + else if(exp[i]==')') + { + if(top==NULL) + return 0; + pop(); + } + } + if(top==NULL) + return 1; + else + return 0; +} +int pre(char x) +{ + if(x=='+' || x=='-') + return 1; + else if(x=='*' || x=='/') + return 2; + return 0; +} + +int isOperand(char x) +{ + if(x=='+' || x=='-' || x=='*' || x=='/') + return 0; + else + return 1; + +} + +char * InToPost(char *infix) +{ + int i=0,j=0; + char *postfix; + long len=strlen(infix); + postfix=(char *)malloc((len+2)*sizeof(char)); + + while(infix[i]!='\0') + { + if(isOperand(infix[i])) + postfix[j++]=infix[i++]; + else + { + if(pre(infix[i])>pre(top->data)) + push(infix[i++]); + else + { + postfix[j++]=pop(); + } + } + } + while(top!=NULL) + postfix[j++]=pop(); + postfix[j]='\0'; + return postfix; +} +int Eval(char *postfix) +{ + int i=0; + int x1,x2,r=0 ; + + for(i=0;postfix[i]!='\0';i++) + { + if(isOperand(postfix[i])) + { + push(postfix[i]-'0'); + } + else + { + x2=pop();x1=pop(); + switch(postfix[i]) + { + case '+':r=x1+x2; break; + case '-':r=x1-x2; break; + case '*':r=x1*x2; break; + case '/':r=x1/x2; break; + } + push(r); + } + } + return top->data; +} +int main() +{ + char *postfix="234*+82/-"; + + printf("Result is %d\n",Eval(postfix)); + + return 0; +} \ No newline at end of file diff --git a/Stack/InToPost.c b/Stack/InToPost.c new file mode 100644 index 00000000..ec406513 --- /dev/null +++ b/Stack/InToPost.c @@ -0,0 +1,128 @@ +//Infix to Postfix Conversion +#include +#include +#include +struct Node +{ + char data; + struct Node *next; +}*top=NULL; +void push(char x) +{ + struct Node *t; + t=(struct Node*)malloc(sizeof(struct Node)); + + if(t==NULL) + printf("stack is full\n"); + else + { + t->data=x; + t->next=top; + top=t; + } + +} +char pop() +{ + struct Node *t; + char x=-1; + + if(top==NULL) + printf("Stack is Empty\n"); + else + { + t=top; + top=top->next; + x=t->data; + free(t); + } + return x; +} +void Display() +{ + struct Node *p; + p=top; + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } + printf("\n"); +} +int isBalanced(char *exp) +{ + int i; + + for(i=0;exp[i]!='\0';i++) + { + if(exp[i]=='(') + push(exp[i]); + else if(exp[i]==')') + { + if(top==NULL) + return 0; + pop(); + } + } + if(top==NULL) + return 1; + else + return 0; +} +int pre(char x) +{ + if(x=='+' || x=='-') + return 1; + else if(x=='*' || x=='/') + return 2; + return 0; +} + +int isOperand(char x) +{ + if(x=='+' || x=='-' || x=='*' || x=='/') + return 0; + else + return 1; + +} + +char * InToPost(char *infix) +{ + int i=0,j=0; + char *postfix; + int len=strlen(infix); + postfix=(char *)malloc((len+2)*sizeof(char)); + + while(infix[i]!='\0') + { + if(isOperand(infix[i])) + postfix[j++]=infix[i++]; + else + { + if(pre(infix[i])>pre(top->data)) + push(infix[i++]); + else + { + postfix[j++]=pop(); + } + } + } + while(top!=NULL) + postfix[j++]=pop(); + postfix[j]='\0'; + return postfix; +} + +int main() +{ + char *infix="a+b*c-d/e"; + push('#'); + + char *postfix=InToPost(infix); + + printf("%s ",postfix); + + + return 0; +} \ No newline at end of file diff --git a/Stack/Parantheses_Matching.c b/Stack/Parantheses_Matching.c new file mode 100644 index 00000000..fc0d815c --- /dev/null +++ b/Stack/Parantheses_Matching.c @@ -0,0 +1,78 @@ +//Parenthesis Matching +#include +#include +struct Node +{ + char data; + struct Node *next; +}*top=NULL; +void push(char x) +{ + struct Node *t; + t=(struct Node*)malloc(sizeof(struct Node)); + + if(t==NULL) + printf("stack is full\n"); + else + { + t->data=x; + t->next=top; + top=t; + } + +} +char pop() +{ + struct Node *t; + char x=-1; + + if(top==NULL) + printf("Stack is Empty\n"); + else + { + t=top; + top=top->next; + x=t->data; + free(t); + } + return x; +} +void Display() +{ + struct Node *p; + p=top; + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } + printf("\n"); +} +int isBalanced(char *exp) +{ + int i; + + for(i=0;exp[i]!='\0';i++) + { + if(exp[i]=='(') + push(exp[i]); + else if(exp[i]==')') + { + if(top==NULL) + return 0; + pop(); + } + } + if(top==NULL) + return 1; + else + return 0; +} +int main() +{ + char *exp="((a+b)*(c-d)))"; + + printf("%d ",isBalanced(exp)); + + return 0; +} diff --git a/Stack/Stack using array b/Stack/Stack using array new file mode 100644 index 00000000..93964e12 --- /dev/null +++ b/Stack/Stack using array @@ -0,0 +1,85 @@ +#include +#include +#define size 4 +void push(); +void pup(); +void display(); +int top=-1; +int a[size]; +int main() +{ + int d; + while(1) + { + printf("\n\n\n LIST OF CHOICES AND MENU"); + printf("=========================>>"); + printf("\n 1. PUSH"); + printf("\n 2. POP"); + printf("\n 3. DISPLAY"); + printf("\n 4. BYE BYE"); + printf("\n enter your choice="); + scanf("%d",&d); + switch(d) + { + case 1: + { + push(); + break; + } + case 2: + { + pop(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + exit(0); + } + default: + { + printf("\n INVALID INPUT !!!!!!"); + } + } + } +} +void push() +{ + int n; + if(top>" ); + for(i=top;i>=0;i--) + { + printf(" %d ",a[i]); + } +} diff --git a/Stack/Stack_Array.c b/Stack/Stack_Array.c new file mode 100644 index 00000000..77968df3 --- /dev/null +++ b/Stack/Stack_Array.c @@ -0,0 +1,89 @@ +//Stack using Array +#include +#include +struct Stack +{ + int size; + int top; + int *S; +}; +void create(struct Stack *st) +{ + printf("Enter Size"); + scanf("%d",&st->size); + st->top=-1; + st->S=(int *)malloc(st->size*sizeof(int)); +} +void Display(struct Stack st) +{ + int i; + for(i=st.top;i>=0;i--) + printf("%d ",st.S[i]); + printf("\n"); + +} +void push(struct Stack *st,int x) +{ + if(st->top==st->size-1) + printf("Stack overflow\n"); + else + { + st->top++; + st->S[st->top]=x; + } + +} +int pop(struct Stack *st) +{ + int x=-1; + + if(st->top==-1) + printf("Stack Underflow\n"); + else + { + x=st->S[st->top--]; + } + return x; +} +int peek(struct Stack st,int index) +{ + int x=-1; + if(st.top-index+1<0) + printf("Invalid Index \n"); + x=st.S[st.top-index+1]; + + return x; +} +int isEmpty(struct Stack st) +{ + if(st.top==-1) + return 1; + return 0; +} +int isFull(struct Stack st) +{ + return st.top==st.size-1; +} +int stackTop(struct Stack st) +{ + if(!isEmpty(st)) + return st.S[st.top]; + return -1; +} +int main() +{ + struct Stack st; + create(&st); + + push(&st,10); + push(&st,20); + push(&st,30); + push(&st,40); + + printf("%d \n",peek(st,2)); + + + Display(st); + + return 0; +} diff --git a/Stack/Stack_Array_CPP.cpp b/Stack/Stack_Array_CPP.cpp new file mode 100644 index 00000000..19b9644b --- /dev/null +++ b/Stack/Stack_Array_CPP.cpp @@ -0,0 +1,98 @@ +//Stack Class +#include +using namespace std; +template +class Stack +{ +private: + T *st; + int size; + int top; +public: + Stack(){size=10;top=-1;st=new T[size];} + Stack(int size){this->size=size;top=-1;st=new +T[this->size];} + void push(T x); + T pop(); + T peek(int index); + int stacktop(); + int isEmpty(); + int isFull(); + void Display(); +}; +template +void Stack::push(T x) +{ + if(isFull()) + cout<<"Stack Overflow"< +T Stack::pop() +{ + T x=-1; + if(isEmpty()) + cout<<"Stack underlfow"< +T Stack::peek(int index) +{ + T x=-1; + if(top-index+1<0) + cout<<"Invalid Index"< +int Stack::stacktop() +{ + if(isEmpty()) + return -1; + return st[top]; +} +template +int Stack::isFull() +{ + return top==size-1; +} +template +int Stack::isEmpty() +{ + return top==-1; +} +template +void Stack::Display() +{ + for(int i=top;i>=0;i--) + cout< stk(5); + stk.push('a'); + stk.push('b'); + stk.push('c'); + stk.push('d'); + stk.push('e'); + stk.push('f'); + + stk.Display(); + + cout< +#include +struct Node +{ + int data; + struct Node *next; +}*top=NULL; +void push(int x) +{ + struct Node *t; + t=(struct Node*)malloc(sizeof(struct Node)); + + if(t==NULL) + printf("stack is full\n"); + else + { + t->data=x; + t->next=top; + top=t; + } + +} +int pop() +{ + struct Node *t; + int x=-1; + + if(top==NULL) + printf("Stack is Empty\n"); + else + { + t=top; + top=top->next; + x=t->data; + free(t); + } + return x; +} +void Display() +{ + struct Node *p; + p=top; + while(p!=NULL) + { + printf("%d ",p->data); + p=p->next; + } + printf("\n"); +} +int main() +{ + push(10); + push(20); + push(30); + + Display(); + + printf("%d ",pop()); + + return 0; +} diff --git a/Stack/Stack_Linked_List_CPP.cpp b/Stack/Stack_Linked_List_CPP.cpp new file mode 100644 index 00000000..3ad785b7 --- /dev/null +++ b/Stack/Stack_Linked_List_CPP.cpp @@ -0,0 +1,70 @@ +//Stack Linked List CPP +#include +using namespace std; +class Node +{ +public: + int data; + Node *next; +}; +class Stack +{ +private: + Node *top; +public: + Stack(){top=NULL;} + void push(int x); + int pop(); + void Display(); +}; +void Stack::push(int x) +{ + Node *t=new Node; + if(t==NULL) + cout<<"Stak is +Full\n"; + else + { + t->data=x; + t->next=top; + top=t; + } +} +int Stack::pop() +{ + int x=-1; + if(top==NULL) + cout<<"Stack is +Empty\n"; + else + { + x=top->data; + Node *t=top; + top=top->next; + delete t; + } + return x; + +} +void Stack::Display() +{ + Node *p=top; + while(p!=NULL) + { + cout<data<<" "; + p=p->next; + } + cout< -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;i0)break; + } + if(p==-1)return "YES"; + return "NO"; + + + + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int t = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int tItr = 0; tItr < t; tItr++) { + String s = scanner.nextLine(); + + String result = isBalanced(s); + + bufferedWriter.write(result); + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} diff --git a/c++/Bubble_sort.cpp b/c++/Bubble_sort.cpp new file mode 100644 index 00000000..6e13d570 --- /dev/null +++ b/c++/Bubble_sort.cpp @@ -0,0 +1,41 @@ +#include +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++/MysterySeries.CPP b/c++/MysterySeries.CPP new file mode 100644 index 00000000..30ea1ede --- /dev/null +++ b/c++/MysterySeries.CPP @@ -0,0 +1,30 @@ +//Program To Print Mystery Series +#include +#include +void main() +{ +int mys=1,num; +clrscr(); +cout<<"Enter Last Number Of Series: "; +cin>>num; +cout< +#include +#include +void main() +{ +char num[15],temp[2]; +int i=0,len; +clrscr(); + +cout<<"ENTER THE NUMBER: "; +cin>>num; +len=strlen(num); +temp[i]=num[len-1]; +temp[i+1]=num[i]; +num[i]=temp[i]; +num[len-1]=temp[i+1]; + +cout<<"After Swaping First And Last Digit: "< +#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++/heap_sort.cpp b/c++/heap_sort.cpp new file mode 100644 index 00000000..4b35a1f6 --- /dev/null +++ b/c++/heap_sort.cpp @@ -0,0 +1,46 @@ +#include + +using namespace std; +void downheapify(int arr[], int n, int i) +{ +//g=greatest +//l=left +//r=right + int g = i; + int l = 2*i + 1; + int r = 2*i + 2; + if (l < n && arr[l] > arr[g]) + g = l; + + if (r < n && arr[r] > arr[g]) + g = r; + if (g != i) + { + swap(arr[i], arr[g]); + downheapify(arr, n, g); + } +} + +void heapsort(int arr[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + downheapify(arr, n, i); + + for (int i=n-1; i>0; i--) + { + swap(arr[0], arr[i]); + downheapify(arr, i, 0); + } +} + +int main() +{ + int arr[] = {5,4,3,2,1}; + int n = sizeof(arr)/sizeof(arr[0]); + + heapsort(arr, n); + + cout << "Sorted array is \n"; + for (int i=0; i +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/DECTOBIN.C b/c/DECTOBIN.C new file mode 100644 index 00000000..4a051ad0 --- /dev/null +++ b/c/DECTOBIN.C @@ -0,0 +1,19 @@ +#include +#include +void main(){ +int a[10],n,i; +clrscr(); +printf("Enter the number to convert: "); +scanf("%d",&n); +for(i=0;n>0;i++) +{ +a[i]=n%2; +n=n/2; +} +printf("\nBinary of Given Number is="); +for(i=i-1;i>=0;i--) +{ +printf("%d",a[i]); +} +getch(); +} \ No newline at end of file diff --git a/c/DECTOHEX.C b/c/DECTOHEX.C new file mode 100644 index 00000000..f25422ab --- /dev/null +++ b/c/DECTOHEX.C @@ -0,0 +1,19 @@ +#include +#include +void main(){ +int a[10],n,i; +clrscr(); +printf("Enter the number to convert: "); +scanf("%d",&n); +for(i=0;n>0;i++) +{ +a[i]=n%16; +n=n/16; +} +printf("\nHex of Given Number is="); +for(i=i-1;i>=0;i--) +{ +printf("%d",a[i]); +} +getch(); +} \ No newline at end of file diff --git a/c/DEXTOOCT.C b/c/DEXTOOCT.C new file mode 100644 index 00000000..efb00ba7 --- /dev/null +++ b/c/DEXTOOCT.C @@ -0,0 +1,19 @@ +#include +#include +void main(){ +int a[10],n,i; +clrscr(); +printf("Enter the number to convert: "); +scanf("%d",&n); +for(i=0;n>0;i++) +{ +a[i]=n%8; +n=n/8; +} +printf("\Octal of Given Number is="); +for(i=i-1;i>=0;i--) +{ +printf("%d",a[i]); +} +getch(); +} \ No newline at end of file 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/ImplementingQueueUsingTwoStacks-Without_Pointers.C b/c/ImplementingQueueUsingTwoStacks-Without_Pointers.C new file mode 100644 index 00000000..53664717 --- /dev/null +++ b/c/ImplementingQueueUsingTwoStacks-Without_Pointers.C @@ -0,0 +1,131 @@ +//Implementing a Queue using two Stacks.. +#include +#include + +void push1(int); +void push2(int); +int pop1(); +int pop2(); +void enqueue(); +void dequeue(); +void display(); +void reverse(); +void create(); +void front_rear(); + +int s1[100], s2[100]; +int top1 = -1, top2 = -1; +int count = 0; + + void main() + { + int ch; + clrscr(); + printf("\n Choose Operations to implement: "); + printf("\n 1. Insertion"); + printf("\n 2. Deletion"); + printf("\n 3. Display"); + printf("\n 4. Reverse Display"); + printf("\n 5. Front & Rear Element"); + printf("\n 6. Exit Here..\n"); + create(); + + while (1) + { + printf("\n Enter Operation No.: "); + scanf("%d", &ch); + switch (ch) + { + case 1: enqueue(); + break; + case 2: dequeue(); + break; + case 3: display(); + break; + case 4: reverse(); + break; + case 5: front_rear(); + break; + case 6: exit(0); + default: printf("\n Wrong choice !!"); + } + } +} +//Function to create a queue.. +void create() +{ + top1 = top2 = -1; +} +//Function to push the element onto stack - 1.. +void push1(int data) +{ + s1[++top1] = data; +} +//Function to pop the element from the stack - 2.. +int pop1() +{ + return(s1[top1--]); +} +//Function to push an element onto stack - 2.. +void push2(int data) +{ + s2[++top2] = data; +} +//Function to pop an element from the stack - 2.. +int pop2() +{ + return(s2[top2--]); +} +//Function to add an element into the queue using stack.. +void enqueue() +{ + int data, i; + printf("\t Insert an element: "); + scanf("%d", &data); + push1(data); + count++; +} +//Function to delete an element from the queue using stack.. +void dequeue() +{ + int i; + printf("\t Element Deleted !!\n"); + for (i=0;i<=count;i++) + { + push2(pop1()); + } + pop2(); + count--; + + for (i=0;i<=count;i++) + { + push1(pop2()); + } +} +//Function to display the elements in the Queue.. +void display() +{ + int i; + printf("\t Displaying Elements in Queue: "); + for (i=0;i<=top1;i++) + { + printf(" %d", s1[i]); + } + printf("\n"); +} +//Function to display the elements in reverse.. +void reverse() +{ + int i; + printf("\t Displaying Reversed Elements in Queue: "); + for(i=top1;i>=0;i--) + { + printf(" %d", s1[i]); + } + printf("\n"); +} +void front_rear() +{ int i; + printf("\t Front Element: %d", s1[0]); + printf("\n\t Rear Element: %d", s1[top1]); +} 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/The Different Types Of Characters In String.C b/c/The Different Types Of Characters In String.C new file mode 100644 index 00000000..2ba75ac7 --- /dev/null +++ b/c/The Different Types Of Characters In String.C @@ -0,0 +1,22 @@ +#include +#include +#include +void main(){ + char str[1000],ch; + int i,len,cnt[26] = {0}; + clrscr(); + printf("Enter Any String : "); + gets(str); + len = strlen(str); + for(i = 0; i < len; i++){ + if(str[i]>= 65 && str[i] <= 90){ + cnt[str[i] - 65]++; } + else if(str[i] >= 97 && str[i] <= 122){ + cnt[str[i] - 97]++; }} + printf("\nThe Different Types Of Characters Are: \n"); + for(ch = 65,i = 0; ch <= 90; ch++,i++){ + if(cnt[i] != 0) +printf("\n%c Counted %d %s.",ch,cnt[i],(cnt[i] > 1) ? "Times" : "Time"); + } + getch(); +} \ No newline at end of file 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/calculator.cpp b/calculator.cpp new file mode 100644 index 00000000..085456e6 --- /dev/null +++ b/calculator.cpp @@ -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/decimaltobinary.c b/decimaltobinary.c new file mode 100644 index 00000000..f88b6890 --- /dev/null +++ b/decimaltobinary.c @@ -0,0 +1,21 @@ +#include +int dtob(int); +void main() +{ + int n; + printf("Enter any decimal number: "); + scanf("%d",&n); + dtob(n); +} +int dtob(int n) +{ + int r; + if(n==0) + return 0; + else + { + r=n%2+10*dtob(n/2); + printf("%d",r); + } + return 0; +} diff --git a/django/Calculator with Authentication/calculator/asgi.py b/django/Calculator with Authentication/calculator/asgi.py new file mode 100644 index 00000000..aa4b6701 --- /dev/null +++ b/django/Calculator with Authentication/calculator/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for calculator project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calculator.settings') + +application = get_asgi_application() diff --git a/django/Calculator with Authentication/calculator/settings.py b/django/Calculator with Authentication/calculator/settings.py new file mode 100644 index 00000000..4efb78eb --- /dev/null +++ b/django/Calculator with Authentication/calculator/settings.py @@ -0,0 +1,126 @@ +""" +Django settings for calculator project. + +Generated by 'django-admin startproject' using Django 3.1.1. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'fg9t5a0jx=pkwzbu+dz0ngtf0=8b8n%x#yao$xqit3wu16h-%(' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'paid' +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'calculator.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': ['pages'], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'calculator.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ +import os +STATIC_URL = '/static/' +STATICFILES_DIRS = [ + os.path.join(BASE_DIR,'static'), +] + +STATIC_ROOT = os.path.join(BASE_DIR, 'assets') diff --git a/django/Calculator with Authentication/calculator/urls.py b/django/Calculator with Authentication/calculator/urls.py new file mode 100644 index 00000000..58c9cbbf --- /dev/null +++ b/django/Calculator with Authentication/calculator/urls.py @@ -0,0 +1,22 @@ +"""calculator URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path,include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('',include('paid.urls')) +] diff --git a/django/Calculator with Authentication/calculator/wsgi.py b/django/Calculator with Authentication/calculator/wsgi.py new file mode 100644 index 00000000..5169eafc --- /dev/null +++ b/django/Calculator with Authentication/calculator/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for calculator project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calculator.settings') + +application = get_wsgi_application() diff --git a/django/Calculator with Authentication/db.sqlite3 b/django/Calculator with Authentication/db.sqlite3 new file mode 100644 index 00000000..117be742 Binary files /dev/null and b/django/Calculator with Authentication/db.sqlite3 differ diff --git a/django/Calculator with Authentication/manage.py b/django/Calculator with Authentication/manage.py new file mode 100644 index 00000000..dfb5bc1c --- /dev/null +++ b/django/Calculator with Authentication/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calculator.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/django/Calculator with Authentication/pages/base.html b/django/Calculator with Authentication/pages/base.html new file mode 100644 index 00000000..cfa1629a --- /dev/null +++ b/django/Calculator with Authentication/pages/base.html @@ -0,0 +1,33 @@ +{%load static%} + + + + + + Document + + + + + + + +
+
Page : {{pagename}}

+
Hi {{request.user.username}}
+
+ {% if request.user.is_authenticated %} + Logout + Calculator + {%else%} + Sign In + Sign Up + {%endif%} +
+
+

+ {%block content%} + {%endblock%} +
+ + \ No newline at end of file diff --git a/django/Calculator with Authentication/pages/calculator.html b/django/Calculator with Authentication/pages/calculator.html new file mode 100644 index 00000000..4f2796c6 --- /dev/null +++ b/django/Calculator with Authentication/pages/calculator.html @@ -0,0 +1,53 @@ +{% extends "base.html"%} +{%block content%} +

Result {{result}}

+
+ {%csrf_token%} +
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+
+ +
+
+
+ +
+
+
+ + + + + + + + {% for item in ur %} + + + + + + + {%endfor%} +
Num 1Num 2OperatorResult
{{item.num1}}{{item.num2}}{{item.operator}}{{item.result}}
+{%endblock%} \ No newline at end of file diff --git a/django/Calculator with Authentication/pages/signin.html b/django/Calculator with Authentication/pages/signin.html new file mode 100644 index 00000000..211b7466 --- /dev/null +++ b/django/Calculator with Authentication/pages/signin.html @@ -0,0 +1,21 @@ +{% extends "base.html"%} +{%block content%} +
+ {%csrf_token%} +
+
+
+ + +
+
+
+
+ + +
+

+
+ +
+{%endblock%} \ No newline at end of file diff --git a/django/Calculator with Authentication/pages/signup.html b/django/Calculator with Authentication/pages/signup.html new file mode 100644 index 00000000..1c75cae2 --- /dev/null +++ b/django/Calculator with Authentication/pages/signup.html @@ -0,0 +1,35 @@ +{% extends "base.html"%} +{%block content%} +
+ {%csrf_token%} +
+
+
+ + +
+
+
+
+ + +
+
+
+
+
+
+ + +
+
+
+
+ + +
+
+
+ +
+{%endblock%} \ No newline at end of file diff --git a/django/Calculator with Authentication/paid/admin.py b/django/Calculator with Authentication/paid/admin.py new file mode 100644 index 00000000..4218d64b --- /dev/null +++ b/django/Calculator with Authentication/paid/admin.py @@ -0,0 +1,4 @@ +from django.contrib import admin +from .models import UserResult +# Register your models here. +admin.site.register(UserResult) \ No newline at end of file diff --git a/django/Calculator with Authentication/paid/apps.py b/django/Calculator with Authentication/paid/apps.py new file mode 100644 index 00000000..f2266019 --- /dev/null +++ b/django/Calculator with Authentication/paid/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PaidConfig(AppConfig): + name = 'paid' diff --git a/django/Calculator with Authentication/paid/migrations/0001_initial.py b/django/Calculator with Authentication/paid/migrations/0001_initial.py new file mode 100644 index 00000000..a4209331 --- /dev/null +++ b/django/Calculator with Authentication/paid/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# Generated by Django 3.0.5 on 2020-10-02 11:33 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='UserResult', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('num1', models.IntegerField()), + ('num2', models.IntegerField()), + ('operator', models.CharField(max_length=3)), + ('result', models.IntegerField()), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/django/Calculator with Authentication/static/css/index.css b/django/Calculator with Authentication/static/css/index.css new file mode 100644 index 00000000..a4d836a2 --- /dev/null +++ b/django/Calculator with Authentication/static/css/index.css @@ -0,0 +1,14 @@ +.myDiv +{ + background-color: lightblue; + color: black; + font-size: xx-large; + font-family: 'Times New Roman', Times, serif; + font-style: oblique; +} +.buttons{ + float: right; +} +.deleteAll{ + clear: both; +} \ No newline at end of file diff --git a/django/Readme.md b/django/Readme.md new file mode 100644 index 00000000..0cfd81b7 --- /dev/null +++ b/django/Readme.md @@ -0,0 +1,5 @@ +This repository contains django projects. +Django is a python framework for developing websites. + +Run python manage.py collectstatic to collect all static files +Repository is set with sqlite3 as a database. 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/filters.html b/filters.html new file mode 100644 index 00000000..6c6979f6 --- /dev/null +++ b/filters.html @@ -0,0 +1,44 @@ + + + + + filter + + + +

Angular Js filters

+
+

Type a letter in the input field:

+ + +

+ +
    + +
  • + {{ x }} + +
  • +
+
+ + + + \ 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/infixToPostfix.cpp b/infixToPostfix.cpp new file mode 100644 index 00000000..089cf40f --- /dev/null +++ b/infixToPostfix.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +using namespace std; + +int precedence (char ch) { + if (ch == '+' || ch == '-') { + return 1; + } + else if (ch == '*' || ch == '/') { + return 2; + } + else if (ch == '^') { + return 3; + } + else { + return 0; + } +} + +string topostfix(string str){ + stack s; + string expression; + s.push('_'); + + for(int i = 0; i < str.length(); i++){ + + if (isalnum(str[i])) { + expression += str[i]; + } + + else if (str[i] == '(') { + s.push('('); + } + + else if (str[i] == '^') { + s.push('^'); + } + + else if (str[i] == ')') { + while (s.top() != '(' && s.top() != '#') { + expression += s.top(); + s.pop(); + + } + s.pop(); + } + + else { + if (precedence(str[i]) > precedence(s.top())) { + s.push(str[i]); + } + + else { + while (s.top() != '_' && precedence(str[i]) <= precedence(s.top())) { + expression += s.top(); + s.pop(); + } + s.push(str[i]); + } + } + } + + while (s.top() != '_') { + expression += s.top(); + s.pop(); + + } + return expression; +} + + +int main() +{ + string s; + cout << "Enter the expression: "; + cin >>s; + cout << topostfix(s); + + return 0; +} diff --git a/insertionsort.java b/insertionsort.java new file mode 100644 index 00000000..3a66a86f --- /dev/null +++ b/insertionsort.java @@ -0,0 +1,32 @@ +import java.io.*; +import java.lang.*; + +class insertionsort{ + public static void main(String args[]){ + // Creating an Array + int i; + int arr[] = {78,43,3,21,112}; + System.out.println("Array before insertion sort: "); + for( i = 0; i= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + System.out.println(); + System.out.println("Array after Insertion Sort"); + for( i = 0; i +using namespace std; +int interpolation_search(int a[], int bottom, int top, int item) +{ +int mid; +while (bottom <= top) +{ +mid = bottom + (top - bottom) * (item - a[bottom]) / (a[top] - a[bottom]); +if (item == a[mid]) +return mid + 1; +if (item < a[mid]) +interpolation_search(a, bottom, mid-1,item); +else +interpolation_search(a, mid+1, top,item);} +return -1; +} +int main() +{ + int a[]={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39}; + int c=interpolation_search(a,0,19,11); + cout< 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/IsPrime.java b/java/IsPrime.java new file mode 100644 index 00000000..2719cd5a --- /dev/null +++ b/java/IsPrime.java @@ -0,0 +1,12 @@ +public class isPrime(){ +public static boolean isPrime(int number){ + int cont = 2; + boolean prime=true; + while ((prime) && (cont!=number)){ + if (number % cont == 0) + prime = false; + cont++; + } + return prime; +} +} \ No newline at end of file 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(i= n) + return -1; + } + while (inputArr[prev] < x) + { + prev++; + if (prev == Math.min(step, n)) + return -1; + } + if (inputArr[prev] == x) + return prev; + + return -1; + } + + +} diff --git a/launch.json b/launch.json new file mode 100644 index 00000000..440a52cf --- /dev/null +++ b/launch.json @@ -0,0 +1,20 @@ +{ + "version": "0.2.0", + "configurations": [ + + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + }, + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + } + ] +} diff --git a/matrix_transpose.cpp b/matrix_transpose.cpp new file mode 100644 index 00000000..c98435af --- /dev/null +++ b/matrix_transpose.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + int main() + { + int i,j,n,m; + int arr[100][100],trs[100][100]; + cout<<"Enter the number of rows and columns of matrix :"; + cin>>n>>m; + cout<<"Enter the matrix elements :"; + for(i=0;i>arr[i][j]; + } + } + for(i=0;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/matchmaker.py b/python/matchmaker.py new file mode 100644 index 00000000..990c71ad --- /dev/null +++ b/python/matchmaker.py @@ -0,0 +1,52 @@ +""" +@author: Arpit Somani +""" + + +import random +import time +from tkinter import Tk , Button , DISABLED + +def show_symbol(x,y): + global first + global previousx , previousy + buttons[x,y]['text'] = button_symbols[x,y] + buttons[x,y].update_idletasks() + + if first: + previousx = x + previousy = y + first = False + elif previousx != x or previousy != y: + if buttons[previousx,previousy]['text'] != buttons[x,y]['text']: + time.sleep(0.5) + buttons[previousx,previousy]['text'] = ' ' + buttons[x,y]['text'] = ' ' + else: + buttons[previousx,previousy]['command'] = DISABLED + buttons[x,y]['command'] = DISABLED + first = True + +win = Tk() +win.title('Matchmaker') +win.resizable(width=False , height=False) +first = True +previousx = 0 +previousy = 0 +buttons = { } +button_symbols = { } +symbols = [u'\u2702',u'\u2705',u'\u2708',u'\u2709',u'\u270A',u'\u270B', + u'\u270C',u'\u270F',u'\u2712',u'\u2714',u'\u2716',u'\u2728', + u'\u2702',u'\u2705',u'\u2708',u'\u2709',u'\u270A',u'\u270B', + u'\u270C',u'\u270F',u'\u2712',u'\u2714',u'\u2716',u'\u2728'] + +random.shuffle(symbols) + +for x in range(6): + for y in range(4): + button = Button(command = lambda x=x , y=y: show_symbol(x,y) , width = 10, height = 8) + button.grid(column = x , row = y) + buttons[x,y] = button + button_symbols[x,y] = symbols.pop() + +win.mainloop() 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/quick_sort.py b/quick_sort.py new file mode 100644 index 00000000..984687dd --- /dev/null +++ b/quick_sort.py @@ -0,0 +1,31 @@ +def partition(arr, low, high): + i = (low-1) # index of smaller element + pivot = arr[high] # pivot + + for j in range(low, high): + if arr[j] <= pivot: + + # increment index of smaller element + i = i+1 + arr[i], arr[j] = arr[j], arr[i] + + arr[i+1], arr[high] = arr[high], arr[i+1] + return (i+1) +def quickSort(arr, low, high): + if len(arr) == 1: + return arr + if low < high: + pi = partition(arr, low, high) + quickSort(arr, low, pi-1) + quickSort(arr, pi+1, high) + + + +arr = [10, 7, 8, 9, 1, 5] +n = len(arr) +quickSort(arr, 0, n-1) +print("Sorted array is:") +for i in range(n): + print("%d" % arr[i]), + + 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"); + } +}