diff --git a/BST/Delete.c b/BST/Delete.c new file mode 100755 index 00000000..7a1b0d12 --- /dev/null +++ b/BST/Delete.c @@ -0,0 +1,62 @@ +#include +#include + +struct tree{ + int data; + struct tree *left; + struct tree *right; +}*root=NULL,*newn; + +struct tree* create(int n) +{ + newn=(struct tree*)malloc(sizeof(struct tree)); + newn->data=n; + newn->left=NULL; + newn->right=NULL; + return newn; +} + +struct tree* ins(struct tree*r,int dat) +{ + if(r==NULL) + return create(dat); + if(dat < r->data) + r->left=ins(r->left,dat); + else if(dat > r->data) + r->right=ins(r->right,dat); + return r; +} + +int max=-10000,min=10000; + +void preorder(struct tree* n) +{ + if(n==NULL) + return; + else + { + preorder(n->left); + preorder(n->right); + printf("Deleting Node:%d\n",n->data); + free(n); + } +} +int flag=0; + +void main() +{ + int choice=1,t,ne, exit; + printf("Enter Root Node:\n"); + scanf("%d",&ne); + root=ins(root,ne); + while(choice!=0) + { + printf("Enter Value:\n"); + scanf("%d",&t); + ins(root,t); + printf("Want to Continue the tree:1 or 0...?\n"); + scanf("%d",&choice); + } + preorder(root); + scanf("%d", exit); +} diff --git a/BST/Height.c b/BST/Height.c new file mode 100755 index 00000000..7558e727 --- /dev/null +++ b/BST/Height.c @@ -0,0 +1,65 @@ +#include +#include + +struct tree{ + int data; + struct tree* left; + struct tree* right; +}; + +struct tree* create(int dat) +{ + struct tree* n=(struct tree*)malloc(sizeof(struct tree)); + n->data=dat; + n->left=NULL; + n->right=NULL; + return n; +} + +int height(struct tree* n) +{ + int l,r; + if(n==NULL) + return 0; + else + { + l=height(n->left); + r=height(n->right); + if(l>r) + return(l+1); + else + return (r+1); + } +} + +int count=0; + +int node(struct tree* n) +{ + if(n==NULL) + return count; + else + { + node(n->left); + node(n->right); + count++; + } + +} + +void main() +{ + struct tree* root; + int ans, exit; + root=create(30); + ans=height(root); + printf("Height of tree after first insertion: %d\n",ans); + root->left=create(20); + root->right=create(40); + root->left->left=create(60); + ans=height(root); + printf("Height of given tree: %d\n",ans); + ans=node(root); + printf("No. of nodes: %d\n",ans); + scanf("%d", exit); +} diff --git a/BST/Insert & Search.cpp b/BST/Insert & Search.cpp new file mode 100755 index 00000000..1c7d55c2 --- /dev/null +++ b/BST/Insert & Search.cpp @@ -0,0 +1,74 @@ +/****************************************** +* AUTHOR : VIVEK SHAH * +* INSTITUTION : NIT SURAT * +******************************************/ + +#include +#define boost ios_base::sync_with_stdio(false);cin.tie(NULL) +#define ll long long int +#define mod 1000000007 +#define rep(i,a,b) for (ll i = a; idata = data; + tmp->left = NULL; + tmp->right = NULL; + return tmp; +} + +struct node* insert(struct node* root,int data){ + if (root==NULL) + { + root = getNode(data); + } + else if (data <= root->data) + { + root->left = insert(root->left,data); + } + else{ + root->right = insert(root->right,data); + } + return root; +} + +int search(struct node* root, int data){ + if (root==NULL) + { + return 0; + } + else if (root->data = data) + { + return 1; + } + else if (data<=root->data) + { + return search(root->left,data); + } + else{ + return search(root->right,data); + } +} + +int main() +{ + boost; + struct node* root = NULL; + root = insert(root,15); + root = insert(root,10); + root = insert(root,20); + if(search(root,15)){ + cout<<"Found"; + } + else cout<<"Not Found"; + return 0; +} \ No newline at end of file diff --git a/BST/MinMax_8.c b/BST/MinMax_8.c new file mode 100755 index 00000000..7e9002ba --- /dev/null +++ b/BST/MinMax_8.c @@ -0,0 +1,57 @@ +#include +#include +struct tree{ + int data; + struct tree *left; + struct tree *right; +}*root=NULL,*newn; +struct tree* create(int n) +{ + newn=(struct tree*)malloc(sizeof(struct tree)); + newn->data=n; + newn->left=NULL; + newn->right=NULL; + return newn; +} +struct tree* ins(struct tree*r,int dat) +{ + if(r==NULL) + return create(dat); + if(dat < r->data) + r->left=ins(r->left,dat); + else if(dat > r->data) + r->right=ins(r->right,dat); + return r; +} +int max=-10000,min=10000; +void Preo(struct tree* n) +{ + if(n==NULL) + return; + if(n->data>max) + max=n->data; + if(n->datadata; + //printf("%d ",n->data); + Preo(n->left); + Preo(n->right); +} +void main() +{ + int choice=1,t,ne, exit; + printf("Enter Root Node:\n"); + scanf("%d",&ne); + root=ins(root,ne); + while(choice!=0) + { + printf("Enter Data:\n"); + scanf("%d",&t); + ins(root,t); + printf("Want to Continue the tree:1 or 0...?\n"); + scanf("%d",&choice); + } + Preo(root); + printf("Minimum:%d\n",min); + printf("Maximum:%d\n",max); + scanf("%d", exit); +} diff --git a/Backtrack/Rat_Maze_Recurssion_Backtracking.c b/Backtrack/Rat_Maze_Recurssion_Backtracking.c new file mode 100644 index 00000000..56d6e77d --- /dev/null +++ b/Backtrack/Rat_Maze_Recurssion_Backtracking.c @@ -0,0 +1,64 @@ +#include +#define N 4 + +void display(int sol[N][N]) +{ + int i,j; + for(i=0;i=0 && x<4) && (y>=0 && y<3) && maze[x][y]==1) + return 1; + else + return 0; +} + +int solvemaze(int maze[N][N],int x,int y,int sol[N][N]) +{ + if(x==N-1 && y==N-1) + { + sol[x][y]=1; + return 1; + } + + if(issafe(maze,x,y)==1) + { + sol[x][y]=1; + + if(solvemaze(maze,x+1,y,sol)==1) + return 1; + + if(solvemaze(maze,x,y+1,sol)==1) + return 1; + + sol[x][y]=0; + return 0; + } + return 0; +} + +void solve(int maze[N][N]) +{ + int sol[N][N]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; + if(solvemaze(maze,0,0,sol)==0) + { + printf("No Solution possible\n"); + } + else + { + display(sol); + } +} +void main() +{ + int maze[N][N]={{1,0,0,0},{1,1,0,1},{0,1,0,0},{1,1,1,1}}; + solve(maze); +} diff --git a/Backtrack/m-coloring-problem.py b/Backtrack/m-coloring-problem.py new file mode 100644 index 00000000..dc5a1655 --- /dev/null +++ b/Backtrack/m-coloring-problem.py @@ -0,0 +1,60 @@ +class Graph: + def __init__(self,m,v): + self.adj=m + self.V=v + +def mColoring(k,m,g,x): + + while(True): + + x[k]=getNodeColor(k,m,g,x) + if(x[k]==0): + return + if(k==g.V-1): + print(x) + else: + mColoring(k+1,m,g,x) + +def getNodeColor(k,m,g,x): + + while(True): + + x[k]=(x[k]+1)%(m+1) #bcoz any vertex should be assigned from 1 to m + + if(x[k]==0): + return x[k] + + #checking for any collisions of color + for j in range(g.V): + if(g.adj[k][j]==1 and x[k]==x[j]): #same color + break + else: + return x[k] + + + + +def main(): + matrix=[[0,1,1,1], + [1,0,1,0], + [1,1,0,1], + [1,0,1,0] ] + g=Graph(matrix,4) + + m=3 #Number of colors + x=[0 for i in range(g.V)] + mColoring(0,m,g,x) + +if __name__=='__main__': + main() + + +''' +Possible Coloring: +[1, 2, 3, 2] +[1, 3, 2, 3] +[2, 1, 3, 1] +[2, 3, 1, 3] +[3, 1, 2, 1] +[3, 2, 1, 2] +''' diff --git a/Backtrack/nqueen_allsol.py b/Backtrack/nqueen_allsol.py new file mode 100644 index 00000000..59b1c923 --- /dev/null +++ b/Backtrack/nqueen_allsol.py @@ -0,0 +1,53 @@ +def initialize(board,n): + keys=['queen','row','col','pdiag','sdiag'] + for i in keys: + board[i]={} + for i in range(n): + board['queen'][i]=-1 + board['row'][i]=0 + board['col'][i]=0 + for i in range(-(n-1),n): + board['pdiag'][i]=0 + for i in range(0,2*n-1): + board['sdiag'][i]=0 + +def placequeen(r,board,n): + return True + +def printboard(board,n): + for row in board['queen'].keys(): + print('(',row,',',board['queen'][row],')',end=' ') + print('') + +def isfree(i,j,board): + return (board['row'][i]==0 and board['col'][j]==0 and board['pdiag'][j-i]==0 and board['sdiag'][j+i]==0) + +def addqueen(i,j,board): + board['queen'][i]=j + board['row'][i]=1 + board['col'][j]=1 + board['pdiag'][j-i]=1 + board['sdiag'][j+i]=1 + +def undoqueen(i,j,board): + board['queen'][i]=-1 + board['row'][i]=0 + board['col'][j]=0 + board['pdiag'][j-i]=0 + board['sdiag'][j+i]=0 + +def placequeen(i,board,n): + for j in range(n): + if isfree(i,j,board): + addqueen(i,j,board) + if i==n-1: + printboard(board,n) + else: + extend=placequeen(i+1,board,n) + undoqueen(i,j,board) + +#main +n=int(input('Enter the number of queens:')) +board={} +initialize(board,n) +placequeen(0,board,n) diff --git a/Linked_List/Circular_LL.c b/Linked_List/Circular_LL.c new file mode 100755 index 00000000..0b6e0417 --- /dev/null +++ b/Linked_List/Circular_LL.c @@ -0,0 +1,259 @@ +/* + *********************** + Author : Vivek Shah + Question : Circular LL + *********************** +*/ + +#include +#include +#include + +struct node +{ + char name[100]; + int roll; + float cgpa; + struct node* next; +}; + +struct node* head; +void display(); + +struct node* getNode(){ + char name[100]; + int roll; + float cgpa; + printf("Enter name to be inserted\n"); + printf("Enter Roll to be inserted\n"); + printf("Enter CGPA to be inserted\n"); + scanf("%s",name); + scanf("%d",&roll); + scanf("%f",&cgpa); + struct node* temp = (struct node*)malloc(sizeof(struct node)) ; + strcpy(temp->name,name); + temp->roll=roll; + temp->cgpa=cgpa; + temp->next=NULL; + return temp; +} + +int countNode(){ + struct node* temp = head; + int c = 0; + + if (head==NULL) + { + return 0; + } + + do{ + c++; + temp = temp->next; + }while(temp!=head); + + return c; +} + + +void insert_beg(){ + struct node* temp = getNode(); + temp->next = head; + + if (head==NULL) + temp->next = temp; + + else{ + struct node* tm = head; + do{ + tm = tm->next; + }while(tm->next!=head); //traverse through entire list + tm->next = temp; + } + head = temp; + display(); +} + +void insert_btw(){ + printf("Enter the Node no. after wise Node is to be inserted\n"); + int ch; + scanf("%d",&ch); + int count = 0; + if (ch<=0 || ch>countNode()) + { + printf("INVALID NODE No.\n"); + return; + } + else{ + struct node* temp = getNode(); + struct node* tempor = head; + + do{ + count++; + tempor = tempor->next; + }while(tempor->next!=head && ch!=count); + + temp->next = tempor->next; + tempor->next = temp; + display(); + } +} + +void insert_end(){ + struct node* temp = getNode(); + + if (head == NULL) + { + temp->next = temp; + head = temp; + } + + else{ + struct node* t = head; + do{ + t = t->next; + }while(t->next!=head); + t->next = temp; + } + temp->next = head; + display(); +} + + +void delete_beg(){ + if (head==NULL) + { + printf("Nothing to Delete\n"); + } + else{ + struct node* temp = head; + do{ + temp = temp->next; + + }while(temp->next!=head); + head = head->next; + temp->next = head; + } +} + + +void delete_btw(){ + printf("Enter the Node no. to be deleted\n"); + int ch; + scanf("%d",&ch); + int count = 0; + if (ch<=0 || ch>countNode()) + { + printf("INVALID NODE No.\n"); + return; + } + else{ + int c=0; + struct node* tempor = head; + do{ + c++; + tempor = tempor->next; + }while(tempor->next!=head && c==ch-1); + if (tempor->next==head && ch==countNode()) + { + tempor->next=head; + } + else{ + tempor->next = tempor->next->next; + } + } +} + +void delete_end(){ + if (head==NULL)printf("Nothing to Delete\n"); + else if(head->next==NULL)head=NULL; + else{ + struct node* temp = head; + do{ + temp = temp->next; + }while(temp->next->next!=head); + temp->next = head; + } +} + + +void search(){ + int sc; + printf("Enter a roll no to be Searched\n"); + scanf("%d",&sc); + if (head==NULL) + { + printf("No data to search\n"); + return; + } + else{ + struct node* temp = head; + int f=0; + do{ + if(temp->roll==sc){f=1;break;} + temp = temp->next; + }while(temp!=head); + if(f==0)printf("No data found\n"); + else{ + printf("FOUND THE DATA\n"); + printf("\n%s\n%d\n%f\n",temp->name,temp->roll,temp->cgpa); + } + } +} + +void display(){ + if(head==NULL){printf("Nothing to display\n");return;} + struct node* temp = head; + do{ + printf("\n************************************************\n"); + printf("Name : %s\n",temp->name); + printf("Roll No : %d\n",temp->roll); + printf("CGPA : %f\n",temp->cgpa); + temp = temp->next; + }while(temp!=head); + printf("\n************************************************\n\n"); +} + +int main() +{ + head = NULL; + int i,ch; + while(1){ + printf("1.Insert\n2.Delete\n3.Search\n4.Display\n"); + scanf("%d",&i); + if (i==1) + { + printf("1.Insert Begin\n2.Insert Between\n3.Insert End\n"); + scanf("%d",&ch); + if (ch==1) + insert_beg(); + else if (ch==2) + insert_btw(); + else if(ch==3) + insert_end(); + else printf("Invalid Choice\n"); + + } + else if (i==2) + { + printf("1.Delete Begin\n2.Delete Between\n3.Delete End\n"); + scanf("%d",&ch); + if (ch==1) + delete_beg(); + else if (ch==2) + delete_btw(); + else if(ch==3) + delete_end(); + else printf("Invalid Choice\n"); + } + else if(i==3){ + search(); + } + + else if(i==4){ + display(); + } + else printf("Invalid Choice\n"); + } + return 0; +} diff --git a/Linked_List/Doubly LL.c b/Linked_List/Doubly LL.c new file mode 100755 index 00000000..9743621f --- /dev/null +++ b/Linked_List/Doubly LL.c @@ -0,0 +1,258 @@ +/* + *********************** + Author : Vivek Shah + Question : Doubly LL + *********************** +*/ + +#include +#include +#include + +struct node +{ + char name[100]; + int roll; + float cgpa; + struct node* next; + struct node* pre; +}; + +struct node* head; +void display(); + +struct node* getNode(){ + char name[100]; + int roll; + float cgpa; + printf("Enter name to be inserted\n"); + printf("Enter Roll to be inserted\n"); + printf("Enter CGPA to be inserted\n"); + scanf("%s",name); + scanf("%d",&roll); + scanf("%f",&cgpa); + struct node* temp = (struct node*)malloc(sizeof(struct node)) ; + strcpy(temp->name,name); + temp->roll=roll; + temp->cgpa=cgpa; + temp->next = NULL; + temp->pre = NULL; + return temp; +} + +int countNode(){ + struct node* temp = head; + int c = 0; + + if (head==NULL) + { + return 0; + } + + while(temp!=NULL){ + c++; + temp = temp->next; + } + + return c; +} + + +void insert_beg(){ + struct node* temp = getNode(); + temp->next = head; + if(head!=NULL){ + head->pre = temp; + } + head = temp; + display(); +} + +void insert_btw(){ + printf("Enter the Node no. after wise Node is to be inserted\n"); + int ch; + scanf("%d",&ch); + int count = 0; + if (ch<=0 || ch>countNode()) + { + printf("INVALID NODE No.\n"); + return; + } + else{ + struct node* temp = getNode(); + struct node* t = head; + + while(t!=NULL && t!=ch){ + t=t->next; + } + temp->pre = t; + temp->next = t->next; + t->pre->next = temp; + if(t->next!=NULL)t->next->pre = temp; + display(); + } +} + +void insert_end(){ + struct node* temp = getNode(); + + if (head == NULL) + head = temp; + + else{ + struct node* t = head; + while(t->next!=NULL) + t = t->next; + t->next = temp; + temp->pre = NULL; + } + display(); +} + + +void delete_beg(){ + if (head==NULL) + { + printf("Nothing to Delete\n"); + } + else{ + head=head->next; + head->pre=NULL; + } +} + + +void delete_btw(){ + printf("Enter the Node no. to be deleted\n"); + int ch; + scanf("%d",&ch); + int count = 0; + if (ch<=0 || ch>countNode()) + { + printf("INVALID NODE No.\n"); + return; + } + else{ + if(ch==1){ + head=NULL; + return; + } + int c=0; + struct node* t = head; + int f=0; + while(t!=NULL){ + c++; + if (c==ch) + { + f=1; + break; + } + t = t->next; + } + if (f==0) + { + printf("NOT FOUND\n"); + } + else if (t->next!=NULL) + { + t->pre->next = t->next; + t->next->pre = t->pre; + } + else{ + t->pre->next = NULL; + } + } +} + +void delete_end(){ + if (head==NULL)printf("Nothing to Delete\n"); + else if(head->next==NULL)head=NULL; + else{ + struct node* t = head; + while(t->next->next!=NULL) + t = t->next; + t->next=NULL; + } +} + + +void search(){ + int sc; + printf("Enter a roll no to be Searched\n"); + scanf("%d",&sc); + if (head==NULL) + { + printf("No data to search\n"); + return; + } + else{ + struct node* temp = head; + int f=0; + while(temp!=NULL){ + if(temp->roll==sc){f=1;break;} + temp = temp->next; + } + if(f==0)printf("No data found\n"); + else{ + printf("FOUND THE DATA\n"); + printf("\n%s\n%d\n%f\n",temp->name,temp->roll,temp->cgpa); + } + } +} + +void display(){ + if(head==NULL){printf("Nothing to display\n");return;} + struct node* temp = head; + while(temp!=NULL){ + printf("\n************************************************\n"); + printf("Name : %s\n",temp->name); + printf("Roll No : %d\n",temp->roll); + printf("CGPA : %f\n",temp->cgpa); + temp = temp->next; + } + printf("\n************************************************\n\n"); +} + +int main() +{ + head = NULL; + int i,ch; + while(1){ + printf("1.Insert\n2.Delete\n3.Search\n4.Display\n"); + scanf("%d",&i); + if (i==1) + { + printf("1.Insert Begin\n2.Insert Between\n3.Insert End\n"); + scanf("%d",&ch); + if (ch==1) + insert_beg(); + else if (ch==2) + insert_btw(); + else if(ch==3) + insert_end(); + else printf("Invalid Choice\n"); + + } + else if (i==2) + { + printf("1.Delete Begin\n2.Delete Between\n3.Delete End\n"); + scanf("%d",&ch); + if (ch==1) + delete_beg(); + else if (ch==2) + delete_btw(); + else if(ch==3) + delete_end(); + else printf("Invalid Choice\n"); + } + else if(i==3){ + search(); + } + + else if(i==4){ + display(); + } + else printf("Invalid Choice\n"); + } + return 0; +} diff --git a/Linked_List/Insertion_Deletion_SinglyLL.c b/Linked_List/Insertion_Deletion_SinglyLL.c new file mode 100755 index 00000000..7c00b15d --- /dev/null +++ b/Linked_List/Insertion_Deletion_SinglyLL.c @@ -0,0 +1,75 @@ +#include + +struct node{ + int item; + struct node* next; +}; + +struct node* head; + +void Insert(){ + struct node* temp; + temp = (struct node*)malloc(sizeof(struct node)); + int x; + printf("\nEnter element to be inserted : "); + scanf("%d",&x); + printf("\n"); + temp->item = x; + temp->next = NULL; + temp->next = head; + head = temp; +} + +void delete(){ + int x; + if(head==NULL){ + printf("Nothing to be deleted\n"); + return; + } + printf("Enter the position to be deleted : "); + scanf("%d",&x);printf("\n"); + if(head->next==NULL){//only a single element is present + head=NULL; + return; + } + struct node* temp; + temp = head; + int i; + for(i=0;inext; + }//came to n-1th node + temp = temp->next->next; + temp->next = NULL; +} + +void Print(){ + struct node* temp = head; + while(temp!=NULL){ + printf("%d ",temp->item); + temp = temp->next; + } + printf("\n"); +} + +int main(){ + head = NULL; + printf("Enter number of Items : "); + int n; + scanf("%d",&n); + printf("\n"); + int i; + for(i=0;i +#include + +struct Node { + int data; + struct Node* next; +}; +// Two glboal variables to store address of front and rear nodes. +struct Node* front = NULL; +struct Node* rear = NULL; + +// To Enqueue an integer +void Enqueue(int x) { + struct Node* temp = + (struct Node*)malloc(sizeof(struct Node)); + temp->data =x; + temp->next = NULL; + if(front == NULL && rear == NULL){ + front = rear = temp; + return; + } + rear->next = temp; + rear = temp; +} + +// To Dequeue an integer. +void Dequeue() { + struct Node* temp = front; + if(front == NULL) { + printf("Queue is Empty\n"); + return; + } + if(front == rear) { + front = rear = NULL; + } + else { + front = front->next; + } + free(temp); +} + +int Front() { + if(front == NULL) { + printf("Queue is empty\n"); + return; + } + return front->data; +} + +void Print() { + struct Node* temp = front; + while(temp != NULL) { + printf("%d ",temp->data); + temp = temp->next; + } + printf("\n"); +} + +int main(){ + /* Drive code to test the implementation. */ + // Printing elements in Queue after each Enqueue or Dequeue + Enqueue(2); Print(); + Enqueue(4); Print(); + Enqueue(6); Print(); + Dequeue(); Print(); + Enqueue(8); Print(); +} diff --git a/Linked_List/Queue_using_linkedlist.c b/Linked_List/Queue_using_linkedlist.c new file mode 100755 index 00000000..45563aa3 --- /dev/null +++ b/Linked_List/Queue_using_linkedlist.c @@ -0,0 +1,75 @@ +#include + +//insert at beginning and remove at the end + +struct node{ + int item; + struct node* next; +}; + +struct node* head; + +void push(){//insert at the beginning + struct node* ptr = (struct node*)malloc(sizeof(struct node)); + printf("Enter element to be inserted : "); + scanf("%d",&ptr->item); + ptr->next = NULL; + if(head == NULL){ + head = ptr; + return; + } + ptr->next = head; + head = ptr; +} + +void pop(){ + struct node* temp = head; + if(head == NULL){ + printf("Nothing to Pop\n"); + return; + } + else if(head->next == NULL){ + head = NULL; + return; + } + while(temp->next->next!=NULL){ + temp = temp->next; + } + + temp->next = NULL; +} + +void display(){ + struct node* temp = head; + if(temp==NULL){ + printf("Nothing to display\n"); + } + while(temp!=NULL){ + printf("%d ",temp->item); + temp = temp->next; + } + printf("\n"); +} + +int main(){ + head = NULL; + while(1){ + printf("\n1.Push\n2.Pop\n3.Display\nAny other number to Exit\n\n"); + printf("Enter your choice : "); + int ch; + scanf("%d",&ch); + printf("\n"); + if(ch==1){ + push(); + } + else if(ch==2){ + pop(); + } + else if(ch==3){ + display(); + } + else{ + break; + } + } +} diff --git a/Linked_List/Reverse_SinglyLL.c b/Linked_List/Reverse_SinglyLL.c new file mode 100755 index 00000000..3f38b06c --- /dev/null +++ b/Linked_List/Reverse_SinglyLL.c @@ -0,0 +1,63 @@ +#include + +struct node{ + int item; + struct node* next; +}; + +struct node* head; + +struct node* reverse(){ + struct node* pre; + struct node* current; + struct node* post; + current = head; + pre = NULL; + while(current!=NULL){ + post = current->next; + current->next = pre; + pre = current; + current = post; + } + head = pre; + return head; +} + +void insert(int item,int n){ + struct node* temp; + temp = (struct node*)malloc(sizeof(struct node)); + temp->item = item; + temp->next = NULL; + if(n==1){ + temp->next = head; + head = temp; + return; + } + struct node* temp1; + temp1 = head; + int i; + for( i = 0;inext; + } + temp->next = temp1->next; + temp1->next = temp; +} + +void print(){ + struct node* temp = head; + while(temp!=NULL){ + printf("%d ",temp->item); + temp = temp->next; + } + printf("\n"); +} + +int main(){ + head = NULL; + insert(8,1); + insert(51,2); + insert(21,3); + print(); + reverse(); + print(); +} diff --git a/Linked_List/doubly circular.c b/Linked_List/doubly circular.c new file mode 100755 index 00000000..e85d3854 --- /dev/null +++ b/Linked_List/doubly circular.c @@ -0,0 +1,306 @@ +/* + *********************** + Author : Vivek Shah + Question : Doubly Circular LL + *********************** +*/ + +#include +#include +#include + +struct node +{ + char name[100]; + int roll; + float cgpa; + struct node* next; + struct node* pre; +}; + +struct node* head; +struct node* last; +void display(); + +struct node* getNode(){ + char name[100]; + int roll; + float cgpa; + printf("Enter name to be inserted\n"); + printf("Enter Roll to be inserted\n"); + printf("Enter CGPA to be inserted\n"); + scanf("%s",name); + scanf("%d",&roll); + scanf("%f",&cgpa); + struct node* temp = (struct node*)malloc(sizeof(struct node)) ; + strcpy(temp->name,name); + temp->roll=roll; + temp->cgpa=cgpa; + temp->next = NULL; + temp->pre = NULL; + return temp; +} + +int countNode(){ + struct node* temp = head; + int c = 0; + + if (head==NULL) + { + return 0; + } + + do{ + c++; + temp = temp->next; + }while(temp!=head); + + return c; +} + + +void insert_beg(){ + struct node* temp = getNode(); + if (head==NULL) + { + temp->next=temp; + temp->pre=temp; + } + else{ + temp->next=head; + head->pre = temp; + temp->pre = last; + last->next=temp; + } + head = temp; + last = head->pre; + /*struct node* temp = getNode(); + temp->next = head; + struct node* last = head->pre; + struct node* new_node = getNode(); + new_node->next = head; + new_node->pre = last; + last->next = head->pre = new_node; + head = new_node;*/ + + display(); +} + +void insert_btw(){//problem hai... + printf("Enter the Node no. after wise Node is to be inserted\n"); + int ch; + scanf("%d",&ch); + printf("The total count of nodes is %d",countNode()); + int count = 0; + if (ch<=0 || ch>countNode()) + { + printf("INVALID NODE No.\n"); + return; + } + + struct node* temp = getNode(); + struct node* t = head; + + do{ + count++; + t=t->next; + }while(t!=head || count!=ch-1); +/* + printf("The value of count is %d",count); + printf("\n************************************************\n"); + printf("Name : %s\n",t->name); + printf("Roll No : %d\n",t->roll); + printf("CGPA : %f\n",t->cgpa); +*/ + temp->pre = t; + temp->next = t->next; + if(t==last){ + temp->next=head; + last=temp; + } + else t->next->pre = temp; + t->next = temp; + display(); +} + +void insert_end(){ + struct node* temp = getNode(); + + if (head == NULL){ + temp->next=temp; + temp->pre=temp; + head = temp; + last = head->pre; + } + + else{ + temp->next=last->next; + temp->pre = last; + last->next = temp; + last = temp; + last->next = head; + } + display(); +} + + +void delete_beg(){ + if (head==NULL) + { + printf("Nothing to Delete\n"); + } + else if (head==last) + { + head=NULL; + last=NULL; + } + else{ + head=head->next; + head->pre=NULL; + last->next=head; + } + display(); +} + + +void delete_btw(){ + printf("Enter the Node no. to be deleted\n"); + int ch; + scanf("%d",&ch); + int count = 0; + if (ch<=0 || ch>countNode()) + { + printf("INVALID NODE No.\n"); + return; + } + else{ + if(ch==1){ + head=NULL; + last=NULL; + return; + } + int c=0; + struct node* t = head; + int f=0; + while(t!=NULL){ + c++; + if (c==ch) + { + f=1; + break; + } + t = t->next; + } + if (f==0) + { + printf("NOT FOUND\n"); + } + if (t==last) + { + last = last->pre; + last->next=head; + } + else + { + t->pre->next = t->next; + t->next->pre = t->pre; + } + } + display(); +} + +void delete_end(){ + if (last==NULL)printf("Nothing to Delete\n"); + else if(head==last){ + head=NULL; + last=NULL; + } + else{ + last = last->pre; + last->next = head; + } + display(); +} + + +void search(){ + int sc; + printf("Enter a roll no to be Searched\n"); + scanf("%d",&sc); + if (head==NULL) + { + printf("No data to search\n"); + return; + } + else{ + struct node* temp = head; + int f=0; + do{ + if(temp->roll==sc){f=1;break;} + temp = temp->next; + }while(temp!=head); + if(f==0)printf("No data found\n"); + else{ + printf("FOUND THE DATA\n"); + printf("\n%s\n%d\n%f\n",temp->name,temp->roll,temp->cgpa); + } + } +} + +void display(){ + if(head==NULL){printf("Nothing to display\n");return;} + struct node* temp = head; + do{ + printf("\n************************************************\n"); + printf("Name : %s\n",temp->name); + printf("Roll No : %d\n",temp->roll); + printf("CGPA : %f\n",temp->cgpa); + temp = temp->next; + }while(temp!=head); + printf("\n************************************************\n\n"); +} + +int main() +{ + head = NULL; + last = NULL; + int i,ch; + while(1){ + printf("1.Insert\n2.Delete\n3.Search\n4.Display\n"); + scanf("%d",&i); + if (i==1) + { + printf("1.Insert Begin\n2.Insert Between\n3.Insert End\n"); + scanf("%d",&ch); + if (ch==1) + insert_beg(); + else if (ch==2) + insert_btw(); + else if(ch==3) + insert_end(); + else printf("Invalid Choice\n"); + + } + else if (i==2) + { + printf("1.Delete Begin\n2.Delete Between\n3.Delete End\n"); + scanf("%d",&ch); + if (ch==1) + delete_beg(); + else if (ch==2) + delete_btw(); + else if(ch==3) + delete_end(); + else printf("Invalid Choice\n"); + } + else if(i==3){ + search(); + } + + else if(i==4){ + display(); + } + else printf("Invalid Choice\n"); + } + return 0; +} diff --git a/Linked_List/doubly linked list.c b/Linked_List/doubly linked list.c new file mode 100755 index 00000000..99eb8b29 --- /dev/null +++ b/Linked_List/doubly linked list.c @@ -0,0 +1,67 @@ +#include + +struct node{ + int item; + struct node* pre; + struct node* next; +}; + +struct node *head, *ptr; + +struct node* getNode(){ + ptr = (struct node*)malloc(sizeof(struct node)); + printf("Enter element to be inserted in Doubly Linked List : "); + int x; + scanf("%d",&x); + ptr->item = x; + ptr->pre = NULL; + ptr->next = NULL; + return ptr; +} + +void insert(){ + struct node* ptr = getNode(); + ptr->next = head; + if(head == NULL){ + head = ptr; + return; + } + head->pre = ptr; + head = ptr; +} + +void insert1(){ + struct node* ptr = getNode(); + if(head==NULL){ + head = ptr; + return; + } + struct node* temp; + temp=head; + while(temp->next!=NULL){ + temp = temp->next; + }//temp is last element + + temp->next = ptr; + ptr->pre = temp; + ptr->next = NULL; +} + + +void print(){ + struct node* temp; + temp = head; + while(temp!=NULL){ + printf("%d ",temp->item); + temp = temp->next; + } +} + +int main(){ + head = NULL; + insert();//insert inserts at beginning + insert(); + insert1();//insert1 inserts at end + insert1(); + print(); +} diff --git a/Linked_List/linked_list.c b/Linked_List/linked_list.c new file mode 100755 index 00000000..d1d91741 --- /dev/null +++ b/Linked_List/linked_list.c @@ -0,0 +1,203 @@ +#include +#include +#include +struct node +{ + int roll; + char name[100]; + float cgpa; + struct node* next; +}; + +struct node* head; + +struct node* getNode(int roll1,char name1[], float cgpa1){ + struct node* p = (struct node*)malloc(sizeof(struct node)); + p->roll=roll1; + strcpy(p->name,name1); + p->cgpa=cgpa1; + return p; +} + +struct node* getLastNode(){ + struct node* temp = head; + while(temp->next!=NULL) + temp=temp->next; + return temp; +} + +int countNode(){ + struct node* temp = head; + int count=0; + while(temp!=NULL){ + count++; + temp = temp->next; + } + return count; +} + +void ins_beg(int roll,char name[], float cgpa){ + struct node* p =getNode(roll,name,cgpa); + p->next = head; + head = p; +} + +void ins_btw(int roll,char name[], float cgpa,int pos){ + if (pos>0 && pos<=countNode()) + { + struct node* temp = head; + int count=0; + while(count!=(pos-1)){ + temp = temp->next; + } + struct node* p = getNode(roll,name,cgpa); + p->next = temp->next; + temp->next=p; + } + else{ + printf("INVALID POSITIONS\n"); + } +} + +void ins_end(int roll,char name[], float cgpa){ + struct node* p =getNode(roll,name,cgpa); + if (head==NULL)//list is empty + { + head=p; + } + else{ + struct node* temp = head; + while(temp->next!=NULL) + temp=temp->next; + temp->next = p; + } +} + +void del_beg(){ + if(head==NULL)printf("NOTHING TO BE DELETED\n"); + else{ + head = head->next; + } +} + +void del_btw(int pos){ + if (pos>0 && pos<=countNode()) + { + struct node* temp = head; + int count=0; + while(count!=(pos-1)){ + temp = temp->next; + } + temp->next=temp->next->next; + } + else{ + printf("INVALID POSITIONS\n"); + } + +} + +void del_end(){ + if(head==NULL)printf("NOTHING TO BE DELETED\n"); + else if(head->next==NULL)head=NULL; + else{ + struct node* temp = head; + while(temp->next->next!=NULL)temp = temp->next; + temp->next = NULL; + } +} + +void search(int roll){ + struct node* temp = head; + int count=1,flag=0; + while(temp!=NULL){ + if(temp->roll==roll){ + printf("POSITION at %d\n",count); + printf("FOLLOWING DATA OF ROLL NO. :\n"); + printf("ROLL NO. : %d\nNAME : %s\nCGPA : %f\n\n",temp->roll,temp->name,temp->cgpa); + flag=1; + break; + } + ++count; + temp = temp->next; + } + if(flag==0)printf("NOT FOUND\n"); +} + +void DISPLAY(){ + struct node* temp = head; + if(temp==NULL)printf("NOTHING TO DISPLAY\n"); + else{ + while(temp!=NULL){ + printf("ROLL NO: %d\nNAME: %s\nCGPA:%f\n\n",temp->roll,temp->name,temp->cgpa); + temp=temp->next; + } + } +} + +int main() +{ + head = NULL; + while(1){ + printf("1.INSERT : \n2.DELETE : \n3.SEARCH : \n4.DISPLAY : \n"); + int ch; + scanf("%d",&ch); + if (ch==1) + { + int ch1; + printf("1.INSERT at BEGINNING: \n2.INSERT at END: \n3.INSERT at BETWEEN:\n"); + scanf("%d",&ch1); + int roll; + char name[100]; + float cgpa; + printf("Enter UNIQUE ROLL NO. to be inserted\n"); + scanf("%d",&roll); + printf("Enter NAME to be inserted\n"); + gets(name); + printf("Enter CGPA to be inerted\n"); + scanf("%f",&cgpa); + if (ch1==1) + { + ins_beg(roll,name,cgpa); + } + else if (ch1==2) + { + ins_end(roll,name,cgpa); + } + else if (ch1==3) + { + printf("Enter the POSITION where node is to be inserted\n"); + int k; + scanf("%d",&k); + ins_btw(roll,name,cgpa,k); + } + else printf("INVALID INPUT\n"); + } + else if(ch==2){ + int ch1; + printf("1.DELETE at BEGINNING: \n2.DELETE at END: \n3.DELETE at BETWEEN:\n"); + scanf("%d",&ch1); + if(ch1==1){ + del_beg(); + } + else if(ch1==2){ + del_end(); + } + else if(ch1==3){ + printf("Enter the POSITION at which node is to be DELETED\n"); + int k; + del_btw(scanf("%d",&k)); + } + else printf("INVALID POSITION"); + + } + else if(ch==3){ + int roll; + printf("Enter UNIQUE ROLL NO. to be searched\n"); + scanf("%d",&roll); + search(roll); + } + else if(ch==4)DISPLAY(); + else {printf("INVALID INPUT\n");break;} + } + return 0; +} diff --git a/Linked_List/ordered_linked.c b/Linked_List/ordered_linked.c new file mode 100755 index 00000000..ffbfe06d --- /dev/null +++ b/Linked_List/ordered_linked.c @@ -0,0 +1,201 @@ +#include +#include +#include +struct node +{ + int roll; + char name[100]; + float cgpa; + struct node* next; +}; + +struct node* head; + +struct node* getNode(int roll1,char name1[], float cgpa1){ + struct node* p = (struct node*)malloc(sizeof(struct node)); + p->roll=roll1; + strcpy(p->name,name1); + p->cgpa=cgpa1; + p->next=NULL; + return p; +} + +struct node* getLastNode(){ + struct node* temp = head; + while(temp->next!=NULL) + temp=temp->next; + return temp; +} + +int countNode(){ + struct node* temp = head; + int count=0; + while(temp!=NULL){ + count++; + temp = temp->next; + } + return count; +} + +void insert(int roll,char name[], float cgpa){ + struct node* p =getNode(roll,name,cgpa); + if(head==NULL){ + head = p; + } + else if(head->roll > roll){ + p->next=head; + head=p; + } + else{ + struct node* temp = head; + struct node* pre = NULL; + while(temp->roll < roll && temp!=NULL){ + pre = temp; + temp=temp->next; + } + p->next = temp; + pre->next = p; + } +} +/*void ins_beg(int roll,char name[], float cgpa){ + struct node* p =getNode(roll,name,cgpa); + p->next = head; + head = p; +} + +void ins_btw(int roll,char name[], float cgpa,int pos){ + if (pos>0 && pos<=countNode()) + { + struct node* temp = head; + int count=0; + while(count!=(pos-1)){ + temp = temp->next; + } + struct node* p = getNode(roll,name,cgpa); + p->next = temp->next; + temp->next=p; + } + else{ + printf("INVALID POSITIONS\n"); + } +} + +void ins_end(int roll,char name[], float cgpa){ + struct node* p =getNode(roll,name,cgpa); + if (head==NULL)//list is empty + { + head=p; + } + else{ + struct node* temp = head; + while(temp->next!=NULL) + temp=temp->next; + temp->next = p; + } +}*/ + +void del_beg(){ + if(head==NULL)printf("NOTHING TO BE DELETED\n"); + else head = head->next; +} + +void del_btw(int pos){ + if (pos>0 && pos<=countNode()) + { + struct node* temp = head; + int count=0; + while(count!=(pos-1)){ + temp = temp->next; + } + temp->next=temp->next->next; + } + else printf("INVALID POSITIONS\n"); +} + +void del_end(){ + if(head==NULL)printf("NOTHING TO BE DELETED\n"); + else if(head->next==NULL)head=NULL; + else{ + struct node* temp = head; + while(temp->next->next!=NULL)temp = temp->next; + temp->next = NULL; + } +} + +void search(int roll){ + struct node* temp = head; + int count=1,flag=0; + while(temp!=NULL){ + if(temp->roll==roll){ + printf("POSITION at %d\n",count); + printf("FOLLOWING DATA OF ROLL NO. :\n"); + printf("ROLL NO. : %d\nNAME : %s\nCGPA : %f\n\n",temp->roll,temp->name,temp->cgpa); + flag=1; + break; + } + temp = temp->next; + ++count; + } + if(flag==0)printf("NOT FOUND\n"); +} + +void DISPLAY(){ + struct node* temp = head; + if(temp==NULL)printf("NOTHING TO DISPLAY\n"); + else{ + while(temp!=NULL){ + printf("ROLL NO: %d\nNAME: %s\nCGPA:%f\n\n",temp->roll,temp->name,temp->cgpa); + temp=temp->next; + } + } +} + +int main() +{ + head = NULL; + while(1){ + printf("1.INSERT : \n2.DELETE : \n3.SEARCH : \n4.DISPLAY : \n"); + int ch; + scanf("%d",&ch); + if (ch==1) + { + int roll; + char name[100]; + float cgpa; + printf("Enter ROLL NO. to be inserted\n"); + scanf("%d",&roll); + printf("Enter NAME to be inserted\n"); + gets(name); + printf("Enter CGPA to be inerted\n"); + scanf("%f",&cgpa); + insert(roll,name,cgpa); + } + else if(ch==2){ + int ch1; + printf("1.DELETE at BEGINNING: \n2.DELETE at END: \n3.DELETE at BETWEEN:\n"); + scanf("%d",&ch1); + if(ch1==1){ + del_beg(); + } + else if(ch1==2){ + del_end(); + } + else if(ch1==3){ + printf("Enter the POSITION at which node is to be DELETED\n"); + int k; + del_btw(scanf("%d",&k)); + } + else printf("INVALID INPUT"); + + } + else if(ch==3){ + int roll; + printf("Enter ROLL NO. to be searched\n"); + scanf("%d",&roll); + search(roll); + } + else if(ch==4)DISPLAY(); + else {printf("INVALID INPUT\n");break;} + } + return 0; +} diff --git a/Linked_List/stackLinkedList.cpp b/Linked_List/stackLinkedList.cpp new file mode 100755 index 00000000..20e7cb97 --- /dev/null +++ b/Linked_List/stackLinkedList.cpp @@ -0,0 +1,69 @@ +#include + +struct node{ + int item; + struct node* next; +}; + +struct node* head; +int size; + +void insertathead(){ + struct node* ptr; + ptr = (struct node*)malloc(sizeof(struct node)); + printf("Enter data : "); + scanf("%d",&ptr->item); + printf("\n"); + ptr->next = NULL; + if(head == NULL){ + head = ptr; + return; + } + ptr->next = head; + head = ptr; +} + +void pop(){ + if(head==NULL){ + printf("UnderFlow\n"); + return; + } + if(head->next == NULL){ + head=NULL; + return; + } + struct node* temp; + temp = head; + head = head->next; + temp->next = NULL; +} +void print(){ + struct node* temp; + temp = head; + printf("List : "); + while(temp!=NULL){ + printf("%d ",temp->item); + temp = temp->next; + } + printf("\n"); +} + +int main(){ + head=NULL; + printf("Enter the size of array\n"); + scanf("%d",&size); + while(1){ + printf("Enter choice\n1.Insert\n2.Pop\n3.Print\n"); + int ch; + scanf("%d",&ch); + if(ch==1){ + insertathead(); + } + else if(ch==2){ + pop(); + } + else if(ch==3){ + print(); + } + } +} diff --git a/Linked_List/stack_Linked_List.c b/Linked_List/stack_Linked_List.c new file mode 100755 index 00000000..05a5c9ea --- /dev/null +++ b/Linked_List/stack_Linked_List.c @@ -0,0 +1,64 @@ +#include + +struct node{ + int item; + struct node* next; +}; + +struct node* head; +int size; + +void insertathead(){ + struct node* ptr; + ptr = (struct node*)malloc(sizeof(struct node)); + printf("Enter data : "); + scanf("%d",&ptr->item); + printf("\n"); + ptr->next = head; + head = ptr; +} + +void pop(){ + if(head==NULL){ + printf("UnderFlow\n"); + return; + }/* + if(head->next == NULL){ + head=NULL; + return; + } + struct node* temp; + temp = head;*/ + head = head->next; + //temp->next = NULL; +} +void print(){ + struct node* temp; + temp = head; + printf("List : "); + while(temp!=NULL){ + printf("%d ",temp->item); + temp = temp->next; + } + printf("\n"); +} + +int main(){ + head=NULL; + printf("Enter the size of array\n"); + scanf("%d",&size); + while(1){ + printf("Enter choice\n1.Insert\n2.Pop\n3.Print\n"); + int ch; + scanf("%d",&ch); + if(ch==1){ + insertathead(); + } + else if(ch==2){ + pop(); + } + else if(ch==3){ + print(); + } + } +} diff --git a/Python implementation DataStructures/Graph.py b/Python implementation DataStructures/Graph.py new file mode 100644 index 00000000..98586dc3 --- /dev/null +++ b/Python implementation DataStructures/Graph.py @@ -0,0 +1,59 @@ +from collections import defaultdict + + +class Graph(object): + + + def __init__(self, connections, directed=False):#undirected by default + self._graph = defaultdict(set) + self._directed = directed + self.add_connections(connections) + + def add_connections(self, connections): + """ Add connections (list of tuple pairs) to graph """ + + for node1, node2 in connections: + self.add(node1, node2) + + def add(self, node1, node2): + """ Add connection between node1 and node2 """ + + self._graph[node1].add(node2) + if not self._directed: + self._graph[node2].add(node1) + + def remove(self, node): + """ Remove all references to node """ + + for n, cxns in self._graph.iteritems(): + try: + cxns.remove(node) + except KeyError: + pass + try: + del self._graph[node] + except KeyError: + pass + + def is_connected(self, node1, node2): + """ Is node1 directly connected to node2 """ + + return node1 in self._graph and node2 in self._graph[node1] + + def find_path(self, node1, node2, path=[]): + """ Find any path between node1 and node2 (may not be shortest) """ + + path = path + [node1] + if node1 == node2: + return path + if node1 not in self._graph: + return None + for node in self._graph[node1]: + if node not in path: + new_path = self.find_path(node, node2, path) + if new_path: + return new_path + return None + + def __str__(self): + return '{}({})'.format(self.__class__.__name__, dict(self._graph)) diff --git a/Python implementation DataStructures/dfs.py b/Python implementation DataStructures/dfs.py new file mode 100644 index 00000000..0dca2e2b --- /dev/null +++ b/Python implementation DataStructures/dfs.py @@ -0,0 +1,53 @@ +import collections + +class Graph: + def __init__(self): + self.adjList = collections.defaultdict(set) + + def addEdge(self, node1, node2): + self.adjList[node1].add(node2) + self.adjList[node2].add(node1) + +def dfsHelper(current, graph, visited, visitFunc): + if (visited[current]): + return + + visited[current] = True; + + visitFunc(current) + + for neighbor in graph.adjList[current]: + dfsHelper(neighbor, graph, visited, visitFunc) + + +def dfs(current, graph, visitFunc): + visited = collections.defaultdict(bool) + dfsHelper(current, graph, visited, visitFunc) + +def visitPrint(i): + print(i) + +# Testing the depth first search implementation +if __name__ == "__main__": + + # Testing on this tree + # 1 + # / \ + # / \ + # 2 3 + # / \ / \ + # 4 5 6 7 + + g = Graph() + g.addEdge(1, 2) + g.addEdge(1, 3) + g.addEdge(2, 4) + g.addEdge(2, 5) + g.addEdge(3, 6) + g.addEdge(3, 7) + + print("Test 1:") + dfs(1, g, visitPrint) + + print("\nTest2:") + dfs(2, g, visitPrint) diff --git a/Python implementation DataStructures/singly_linked_list.py b/Python implementation DataStructures/singly_linked_list.py new file mode 100644 index 00000000..c5ce313b --- /dev/null +++ b/Python implementation DataStructures/singly_linked_list.py @@ -0,0 +1,55 @@ +class Node(object): + + def __init__(self, data, next): + self.data = data + self.next = next + + +class SingleList(object): + + head = None + tail = None + + def show(self): + print "Showing list data:" + current_node = self.head + while current_node is not None: + print current_node.data, " -> ", + current_node = current_node.next + print None + + def append(self, data): + node = Node(data, None) + if self.head is None: + self.head = self.tail = node + else: + self.tail.next = node + self.tail = node + + def remove(self, node_value): + current_node = self.head + previous_node = None + while current_node is not None: + if current_node.data == node_value: + # if this is the first node (head) + if previous_node is not None: + previous_node.next = current_node.next + else: + self.head = current_node.next + + # needed for the next iteration + previous_node = current_node + current_node = current_node.next + + +s = SingleList() +s.append(31) +s.append(2) +s.append(3) +s.append(4) + +s.show() +s.remove(31) +s.remove(3) +s.remove(2) +s.show() diff --git a/README.md b/README.md index ac4fc3e6..17052557 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # Algo_Ds + ## Overview: +This repo helps you in competitive programming as it contains many advanced algorithms like greedy, graph traversal algorithms including Djikstra's algorithm and Floyd Warshal algorithm, and data structures like queues, stacks, and binary search trees. + -This repo helps you in competitive program as it contains many advanced algorithms like Data structures like queue, stack and binary search tree. At the same time it also includes some very useful algorithms for competitive programmers like greedy, graphs including Djikstra, Floyd Warshal algorithm. ## Contents: @@ -29,11 +31,14 @@ This repo helps you in competitive program as it contains many advanced algorith - Array - Linked List + + ## Languages Used: - C++ + - python + - Java + - C + ## How to contribute: - -Just fork this repo, and start giving any new algorithms which are not in the repo or you can solve any of the issues given. - - At last, star this repo, because this will be handy for you. +Star this repo, if this will be handy for you. diff --git a/STACK_with_Application/Evaluating Postfix Expression.c b/STACK_with_Application/Evaluating Postfix Expression.c new file mode 100644 index 00000000..79a1904f --- /dev/null +++ b/STACK_with_Application/Evaluating Postfix Expression.c @@ -0,0 +1,68 @@ +#include +#include +#define MAX 200 + +int isoperator(char c){ + return (c=='*' || c=='/' || c=='+' || c=='-'); +} + +struct stack +{ + int top; + double a[MAX]; +}s; + +void push(double c){ + s.a[++s.top]=c; +} + +double pop(){ + return s.a[s.top--]; +} + +double perform(double a, double b, char c){ + if (c=='*') + { + return a*b; + } + else if (c=='+') + { + return a+b; + } + else if (c=='/') + { + return a/b; + } + else return a-b; +} + +void post_infix(char a[],int l){ + int i; + for(i=0;i + +int j; +struct temp{ + char a[200]; + int top; +}; +struct temp s; + +void push(char item){ + s.a[++s.top]=item; +} + +int isempty(){ + return s.top==-1; +} + +char pop(){ + if(!isempty())return s.a[s.top--]; +} + +int isoperator(char c){ + if(c=='*'||c=='/'|| c=='+'|| c=='-')return 1; + return 0; +} +int precedence(char c){ + if(c=='+' || c=='-')return 1; + else if(c=='*' || c=='/')return 2; + else if(c=='^')return 3; + return 0; +} +char *infix_postfix(char *p){ + int i; + j=0; + char *p1 = (char *)malloc(100*sizeof(char)); + for(i=0;p[i]!='\0';i++){ + //printf("%d\n",j); + if(isalpha(p[i]) || isdigit(p[i])){ + p1[j++]=p[i]; + } + else if(isoperator(p[i])){//printf("%c\n",p[i]); + while(!isempty() && /*s.a[s.top]!='(' &&*/ (precedence(p[i]) <= precedence(s.a[s.top]))){ + p1[j++] = s.a[s.top]; + pop(); + } + push(p[i]); + } + else if(p[i]=='(')push(p[i]); + else if(p[i]==')'){ + while(!isempty() && s.a[s.top]!='('){ + p1[j++]=s.a[s.top]; + pop(); + } + pop(); + } + } + while(!isempty()){ + //printf("%c ",s.a[s.top]); + p1[j++]=s.a[s.top]; + pop(); + } + //for(i=0;i +#include +#include +#include +using namespace std; + +int main(){ + string str; + printf("Enter a String"); + cin>>str; + int l = str.length(); + stack s; + for(int i=0;i + +struct stack{ + char book_name[200][200]; + int book_id[20]; + int book_price[20]; + int top; +}; + +struct stack *p; +int size; + +void push(){ + if((p->top)==size-1){ + printf("Overflow"); + return; + } + p->top = p->top +1; + //printf("p->top = %d",p->top); + printf("\nEnter elements to be pushed : "); + printf("\nEnter book name:"); + scanf("%s",p->book_name[p->top]); + printf("\nEnter book id:"); + scanf("%d",&p->book_id[p->top]); + printf("\nEnter book price:"); + scanf("%d",&p->book_price[p->top]); +} + +void pop(){ + if(p->top==-1){ + printf("Underflow\n"); + } + else{ + p->top = p->top - 1; + } +} + +void peep(){ + int i= p->top; + printf("\nBook Name : %s",p->book_name[i]); + printf("\nBook ID : %d",p->book_id[i]); + printf("\nBook Price : %d",p->book_price[i]); + printf("\n"); +} + +void print(){ + int x = p->top; + if(x==-1){ + printf("Nothing to be displayed\n"); + } + int i; + for(i=0;i<=x;i++){ + printf("\nBook Name : %s",p->book_name[i]); + printf("\nBook ID : %d",p->book_id[i]); + printf("\nBook Price : %d",p->book_price[i]); + printf("\n"); + } +} + +int main(){ + printf("********************************\t\n"); + printf("Enter stack size : "); + scanf("%d",&size); + p = (struct stack*)malloc(sizeof(struct stack)); + p->top = -1; + while(1){ + printf("\n1.Push\n2.Pop\n3.Peep\n4.Display all elements\n5.Exit\n"); + int ch; + scanf("%d",&ch); + if(ch==1){ + //p->top = p->top + 1; + push(); + } + else if(ch==2){ + pop(); + } + else if(ch==3){ + peep(); + } + else if(ch==4){ + print(); + } + else{ + break; + } + } +} diff --git a/Searching Algorithms/Binary_Search.cpp b/Searching Algorithms/Binary_Search.cpp index cfc7e56c..44d19ddb 100644 --- a/Searching Algorithms/Binary_Search.cpp +++ b/Searching Algorithms/Binary_Search.cpp @@ -1,3 +1,4 @@ +//Time Complexity: O(logn) #include using namespace std; int main() diff --git a/Searching Algorithms/Interpolation Search b/Searching Algorithms/Interpolation Search index 968a9c0a..262d12cf 100644 --- a/Searching Algorithms/Interpolation Search +++ b/Searching Algorithms/Interpolation Search @@ -1,3 +1,5 @@ +//Time Complexity : O(log(logn)) + #include using namespace std; diff --git a/Searching Algorithms/Interpolation_search.cpp b/Searching Algorithms/Interpolation_search.cpp index 6008fa1e..ae046db2 100644 --- a/Searching Algorithms/Interpolation_search.cpp +++ b/Searching Algorithms/Interpolation_search.cpp @@ -1,3 +1,5 @@ +//Time Complexity: O(log(logn)) + #include #include using namespace std; diff --git a/Searching Algorithms/Jump_Search.cpp b/Searching Algorithms/Jump_Search.cpp index 392fbe4e..44a3ef4a 100644 --- a/Searching Algorithms/Jump_Search.cpp +++ b/Searching Algorithms/Jump_Search.cpp @@ -1,3 +1,5 @@ +//Time Complexity: O(sqrt(n)) + #include using namespace std; diff --git a/Searching Algorithms/bst.py b/Searching Algorithms/bst.py new file mode 100644 index 00000000..6248db5d --- /dev/null +++ b/Searching Algorithms/bst.py @@ -0,0 +1,53 @@ +#Time Complexity : O(height) + +# Python program to demonstrate insert operation in binary search tree + +# A utility class that represents an individual node in a BST +class Node: + def __init__(self,key): + self.left = None + self.right = None + self.val = key + +# A utility function to insert a new node with the given key +def insert(root,node): + if root is None: + root = node + else: + if root.val < node.val: + if root.right is None: + root.right = node + else: + insert(root.right, node) + else: + if root.left is None: + root.left = node + else: + insert(root.left, node) + +# A utility function to do inorder tree traversal +def inorder(root): + if root: + inorder(root.left) + print(root.val) + inorder(root.right) + + +# Driver program to test the above functions +# Let us create the following BST +# 50 +# / \ +# 30 70 +# / \ / \ +# 20 40 60 80 +r = Node(50) +insert(r,Node(30)) +insert(r,Node(20)) +insert(r,Node(40)) +insert(r,Node(70)) +insert(r,Node(60)) +insert(r,Node(80)) + +# Print inoder traversal of the BST +inorder(r) + diff --git a/Searching Algorithms/fibonacci_search.cpp b/Searching Algorithms/fibonacci_search.cpp new file mode 100644 index 00000000..c26e1c18 --- /dev/null +++ b/Searching Algorithms/fibonacci_search.cpp @@ -0,0 +1,67 @@ +#include + + +using namespace std; + +int _fibonacci_search(int n, int arr[], int x) +{ + /*Assuming the Input array is sorted*/ + /*Fibonacci Searching algorithm */ + /* Initialize fibonacci numbers */ + int fibMMm2 = 0; // (m-2)'th Fibonacci No. + int fibMMm1 = 1; // (m-1)'th Fibonacci No. + int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci + + /* fibM is going to store the smallest Fibonacci + Number greater than or equal to n */ + while (fibM < n) + { + fibMMm2 = fibMMm1; + fibMMm1 = fibM; + fibM = fibMMm2 + fibMMm1; + } + + // Marks the eliminated range from front + int offset = -1; + + /* while there are elements to be inspected. Note that + we compare arr[fibMm2] with x. When fibM becomes 1, + fibMm2 becomes 0 */ + while (fibM > 1) + { + // Check if fibMm2 is a valid location + int index = min(offset+fibMMm2, n-1); + + /* If x is greater than the value at index fibMm2, + cut the subarray array from offset to i */ + if (arr[index] < x) + { + fibM = fibMMm1; + fibMMm1 = fibMMm2; + fibMMm2 = fibM - fibMMm1; + offset = index; + } + + /* If x is greater than the value at index fibMm2, + cut the subarray after i+1 */ + else if (arr[index] > x) + { + fibM = fibMMm2; + fibMMm1 = fibMMm1 - fibMMm2; + fibMMm2 = fibM - fibMMm1; + } + + /* element found. return index */ + else return index; + } + + /* comparing the last element with x */ + if(fibMMm1 && arr[offset+1]==x)return offset+1; + + /*element not found. return -1 */ + return -1; + + + +} + diff --git a/Searching Algorithms/ternarySearch.cpp b/Searching Algorithms/ternarySearch.cpp new file mode 100644 index 00000000..bd7b3a1b --- /dev/null +++ b/Searching Algorithms/ternarySearch.cpp @@ -0,0 +1,37 @@ +//Time Complexity : O(log3(n)) + +//Ternary Search Uses Divide And Conquer Technique +#include + +/* + * Part of Cosmos by OpenGenus Foundation +*/ + +using namespace std; +int ternarySearch(int arr[],int l,int r, int x){ + if(r>=l){ + int mid1 = l + (r-l)/3; + int mid2 = r - (r-l)/3; + if(arr[mid1] == x) + return mid1; + /* + In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd part of array + */ + if(arr[mid2] == x) + return mid2; + if(xarr[mid2]) + return ternarySearch(arr,mid2+1,r,x); + else + return ternarySearch(arr,mid1+1,mid2-1,x); + } + return -1; // if x is not found in array arr +} +int main(){ + int arr[] = {1, 2, 3, 5}; + int size = sizeof(arr)/ sizeof(arr[0]); + int find = 3; + cout<<"Position of "< arr[i+1]: + arr[i], arr[i+1] = arr[i+1], arr[i] + changed = True + return None diff --git a/Sorting Algorithms/Java/HeapSort.java b/Sorting Algorithms/Java/HeapSort.java new file mode 100644 index 00000000..a881ebac --- /dev/null +++ b/Sorting Algorithms/Java/HeapSort.java @@ -0,0 +1,58 @@ +import java.util.*; +/* + * Part of Cosmos by OpenGenus Foundation +*/ +public class HeapSort { + + public static void main(String[] args) { + // array used for testing + int[] a = {5, 11, 1234, 2, 6}; + System.out.println(Arrays.toString(a)); + sort(a); + System.out.println(Arrays.toString(a)); + } + + public static void sort(int[] a) { + int n = a.length; + // create the heap + for (int i = n / 2 - 1; i >= 0; i--) + heapify(a, n, i); + + // extract element from the heap + for (int i=n-1; i>=0; i--) + { + int temp = a[0]; + a[0] = a[i]; + a[i] = temp; + + // rebuild the heap + heapify(a, i, 0); + } + } + + public static void heapify(int arr[], int n, int i) + { + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } +} diff --git a/Sorting Algorithms/insertion.hpp b/Sorting Algorithms/insertion.hpp index de35e3a2..08e1e87f 100644 --- a/Sorting Algorithms/insertion.hpp +++ b/Sorting Algorithms/insertion.hpp @@ -2,12 +2,11 @@ using namespace std; void insertion_sort(int length, int v[]){ - int j, temp; for(int i=0;i0 && v[j] < v[j-1]){ swap(v[j], v[j-1]); j--; } } -} \ No newline at end of file +} diff --git a/Sorting Algorithms/insertion_sort.py b/Sorting Algorithms/insertion_sort.py new file mode 100644 index 00000000..4c97c188 --- /dev/null +++ b/Sorting Algorithms/insertion_sort.py @@ -0,0 +1,10 @@ +def insertion_sort(my_array): + ordered_array = [] + for pos in range(len(my_array)): + new_pos = pos + while(new_pos > 0 and (my_array[new_pos] < my_array[new_pos-1])): + temp = my_array[new_pos] + my_array[new_pos] = my_array[new_pos-1] + my_array[new_pos-1] = temp + new_pos -= 1 + return my_array diff --git a/Sorting Algorithms/slow.cpp b/Sorting Algorithms/slow.cpp new file mode 100644 index 00000000..c4cd1a64 --- /dev/null +++ b/Sorting Algorithms/slow.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; + +void _slow_sort(int v[], int i, int j) { + if (i >= j) return; + int m = i + (j-i)/2; + _slow_sort(v, i, m); + _slow_sort(v, m+1, j); + if (v[j] < v[m]) + swap(v[j], v[m]); + _slow_sort(v, i, j-1); +} + +void slow_sort(int length, int v[]) { + _slow_sort(v, 0, length-1); +} + diff --git a/Square Root Decomposition/MO's Algorithm/MOAlgo.cpp b/Square Root Decomposition/MO's Algorithm/MOAlgo.cpp new file mode 100644 index 00000000..5944705a --- /dev/null +++ b/Square Root Decomposition/MO's Algorithm/MOAlgo.cpp @@ -0,0 +1,85 @@ +//Problem : http://www.spoj.com/problems/DQUERY/ +//Time Complexity : O((n+q)*sqrt(n)) + +#include + +#define ll long long int +#define mod 1000000007 +#define show(a) for(i=0;i +#define vs vector +#define vll vector +#define pb push_back +#define pi pair +#define si set +#define sll set +#define maxheap priority_queue +#define minheap priority_queue,greater> +#define mp make_pair +#define fast_io() cin.sync_with_stdio(false);cout.sync_with_stdio(false); +#define long_zero 0ll +#define long_one 1ll +inline int sbt(int x){return __builtin_popcount(x);} +using namespace std; +int freq[1111111]; +int BLOCK; +//Mo Sorting +bool f(pair a, pair b){ + if(a.se.fi/BLOCK == b.se.fi/BLOCK) + return a.se.se>b.se.se; + return a.se.fi/BLOCK>b.se.fi/BLOCK; +} +int main() { + //fast_io() + int n; + scanf("%d",&n); + int a[n+3]; + for(int i=0;i>q; + scanf("%d",&Q); + //block size:SQRT(N) + BLOCK = floor(sqrt(1.0*double(n))); + for(int i=0;il){ + freq[a[s-1]]++; + if(freq[a[s-1]]==1) + ans++; + s--; + } + while(e<=r){ + freq[a[e]]++; // mantains frequency + if(freq[a[e]]==1) + ans++; + e++; + } + while(e>r+1){ + freq[a[e-1]]--; + if(freq[a[e-1]]==0) + ans--; + e--; + } + v[q[i].fi]=ans; + } + for(int i=0;i +#include +#include +using namespace std; + + +void createMatrix(int **A4,int size); +void output(int **A, int size); +void standardMult(int **A, int **B, int **C, int size); +void strassens(int **A, int **B, int **C, int size); +void Add(int **A, int **B, int **T, int n); +void Sub(int **A, int **B, int **T, int n); + + + + +int main() { + int size = 8; + + + int **A, **B, **C; + + for(int size=16;size<2048;size*=2){ + + A = new int *[size]; + B = new int *[size]; + C = new int *[size]; + + + for(int i=0; i +using namespace std; + +int knapsack(int n, int w, int weight[], int val[]) +{ + int K[n+1][w+1]; + for(int i=0;i<=n;i++) + { + for(int j=0;j<=w;j++) + { + if(i==0||j==0) + K[i][j]=0; + else + { + if(weight[i-1]<=j) + K[i][j] = max(val[i-1] + K[i-1][j-weight[i-1]], K[i-1][j]); + else + K[i][j] = K[i-1][j]; + } + } + } + return K[n][w]; +} + +int main() { + int t,n,w; + cin>>t; + while(t--) + { + cin>>n; + cin>>w; + int val[n], weight[n]; + for(int i=0;i>val[i]; + } + for(int i=0;i>weight[i]; + } + cout< +#include +#include +#include + +using namespace std; + +inline int min(int a,int b,int c){ + return min(a,min(b,c)); +} + +int dp[100][100]; + +int editDistance(string a,string b,int m,int n){ + if(m==0) + return n; + if(n==0) + return m; + if(dp[m][n]!=-1) + return dp[m][n]; + int ans=0; + if(a[m-1]==b[n-1]) + ans=editDistance(a,b,m-1,n-1); + else + ans=1+min(editDistance(a,b,m-1,n),editDistance(a,b,m,n-1),editDistance(a,b,m-1,n-1)); + return dp[m][n]=ans; +} +int main(){ + memset(dp,-1,sizeof(dp)); + string a,b; + a="coding"; + b="hacking"; + cout< +using namespace std; + +int eggdrop(int n, int k) +{ + int eggs[n+1][k+1]; + for(int i=1;i<=n;i++) + { + eggs[i][0]=0; + eggs[i][1]=1; + } + for(int i=1;i<=k;i++) + { + eggs[1][i]=i; + } + for(int i=2;i<=n;i++) + { + for(int j=2;j<=k;j++) + { + eggs[i][j]=INT_MAX; + for(int x=1; x<=j; x++) + { + int res = 1+max(eggs[i-1][x-1], eggs[i][j-x]); + if(res>t; + while(t--) + { + cin>>n>>k; + cout< +using namespace std; + +int main() { + int t,n,cur_max,max_fin; + cin>>t; + while(t--) + { + + cin>>n; + int arr[n]; + for(int i=0;i>arr[i]; + cur_max=arr[0];max_fin=arr[0]; + for(int i=1;i +using namespace std; + +int main() { + int t,n; + cin>>t; + while(t--) + { + cin>>n; + int arr[n],lis[n]; + for(int i=0;i>arr[i]; + lis[i]=1; + } + int max=1; + for(int i=1;imax) + max=lis[i]; + } + cout< +#include +#include +#include + +using namespace std; +//random matrix sizes +int mat[]={10,5,2,8,16,10,5,3,8,9,18,15,3,6,11,5,3,2,8,3,9,7,4,9,3}; +//5 15 and 25 as number of matrices +int nn[]={5,10,25}; + +//funtion for matrix chain multiplication using div and cnquer +int mcmdnc(int a,int b) +{ + int cost; + //base Case + if(a==b) + cost=0; + else + { + for(int i=a;i +#include +using namespace std; + +vector adj[12]; +bool visited[12]; + +void dfs(int s) { + visited[s] = true; + for(int i = 0;i < adj[s].size();++i) { + if(visited[adj[s][i]] == false) + dfs(adj[s][i]); + } +} + +void initialize() { + for(int i = 0;i < 10;++i) + visited[i] = false; +} + +int main() { + int nodes, edges, x, y, connectedComponents = 0; + cin >> nodes; + cin >> edges; + for(int i = 0;i < edges;++i) { + cin >> x >> y; + adj[x].push_back(y); + adj[y].push_back(x); + } + initialize(); + for(int i = 1;i <= nodes;++i) { + if(visited[i] == false) { + dfs(i); + connectedComponents++; + } + } + cout << "Number of connected components: " << connectedComponents << endl; + return 0; +} diff --git a/graph/dijakstra/Dijkstra.java b/graph/dijakstra/Dijkstra.java new file mode 100644 index 00000000..a6a5ea75 --- /dev/null +++ b/graph/dijakstra/Dijkstra.java @@ -0,0 +1,138 @@ +import java.io.BufferedWriter; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.Scanner; +import java.util.Stack; + +/** + * Input file example: + * + * 6 + * INF 7 9 INF INF 14 + * 7 INF 10 15 INF INF + * 9 10 INF 11 INF 2 + * INF 15 11 INF 6 INF + * INF INF INF 6 INF 9 + * 14 INF 2 INF 9 INF + * 5 1 + * + * First line is number of elements inn graph + * Next n-lines is graph + * Last line is begin and end point + * + * Output file: + * Way from 5 to 1: + * 5 -> 6 -> 3 -> 1 + * Length: 20 + * + */ +public class Dijkstra { + + private static final String INPUT_FILE_PATH = "input.txt"; + + private static final String OUTPUT_FILE_PATH = "output.txt"; + + private static final int INF = Integer.MAX_VALUE / 2; + + private static int begin; + + private static int end; + + public static void main(String[] args) { + int[][] matrix = readMatrixFromFile(); + dijkstra(matrix); + } + + private static int[][] readMatrixFromFile() { + int[][] matrix = null; + + try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) { + int matrixSize = Integer.parseInt(scanner.nextLine()); + matrix = new int[matrixSize][matrixSize]; + + for (int row = 0; row < matrixSize; row++) { + String[] numbers = scanner.nextLine().split(" "); + for (int col = 0; col < matrixSize; col++) { + if (numbers[col].equals("INF")) { + matrix[row][col] = INF; + } else { + matrix[row][col] = Integer.parseInt(numbers[col]); + } + } + } + + begin = scanner.nextInt(); + end = scanner.nextInt(); + } catch (IOException e) { + e.printStackTrace(); + } + + return matrix; + } + + private static void dijkstra(int[][] matrix) { + boolean[] used = new boolean[matrix.length]; + int[] dist = new int[matrix.length]; + int[] way = new int[matrix.length]; + + begin -= 1; + end -= 1; + + Arrays.fill(dist, INF); + Arrays.fill(way, 0); + dist[begin] = 0; + + while (true) { + int v = -1; + for (int nv = 0; nv < matrix.length; nv++) { + if (!used[nv] && (v == -1 || dist[nv] < dist[v])) { + v = nv; + } + } + + if (v == -1) { + break; + } + + used[v] = true; + + for (int nv = 0; nv < matrix.length; nv++) { + if (!used[nv] && matrix[v][nv] + dist[v] < dist[nv]) { + dist[nv] = matrix[v][nv] + dist[v]; + way[nv] = v; + } + } + } + + printSolution(way, dist); + } + + private static void printSolution(int[] trip, int[] dist) { + Stack stack = new Stack<>(); + StringBuilder answer = new StringBuilder(); + answer.append(String.format("Way from %d to %d:\n", begin + 1, end + 1)); + + int lastPoint = end; + + while (lastPoint != begin) { + stack.push(lastPoint); + lastPoint = trip[lastPoint]; + } + + answer.append(begin + 1); + while (!stack.isEmpty()) { + answer.append(" -> ").append(stack.pop() + 1); + } + + answer.append(String.format("\nLength: %d\n", dist[end])); + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) { + writer.write(answer.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/maths/prime/PrimeToNumber.py b/maths/prime/PrimeToNumber.py new file mode 100644 index 00000000..8230c2cf --- /dev/null +++ b/maths/prime/PrimeToNumber.py @@ -0,0 +1,11 @@ +#Python Prime checker. Not the most efficient way to check for primes, but very easy to code! + +num = int(input("Enter a integer to get primes up to ")) #Get highest number for prime +div=2 #Set divisor to intitally 2 +for num in range(2,num): #Check if prime + prime = True #If prime is true set flag. + for div in range(2,num): #If number can be divided by any number, from 2 to the number-1 + if (num % div == 0):#If evenly divided, the number will therefore be notprime. + prime = False #set prime to false + if prime: + print (num) diff --git a/maths/prime/sieveOferatosthenes.cpp b/maths/prime/sieveOferatosthenes.cpp new file mode 100644 index 00000000..ea9310c4 --- /dev/null +++ b/maths/prime/sieveOferatosthenes.cpp @@ -0,0 +1,41 @@ +#include +#include +using namespace std; +void sieve_of_eratosthenes(std::vector& primes, const int max) { + vector isPrime; + // Initially, all the numbers are considered to be prime + for (int i = 0; i <= max; i++) { + isPrime.push_back(true); + } + // 0 and 1 are obviously not prime, so we set it in the isPrime vector + isPrime[0] = isPrime[1] = false; + + // Iterate from 2 up to the square root of max + for (int i = 2; i*i <= max; i++) { + if (isPrime[i]) { + // If the current number is prime, then set i^2, i^2+i, i^2+2i, ... as not prime + for (int j = i * i; j <= max; j += i) { + isPrime[j] = false; + } + } + } + + // Iterate from 2 to max again. All the numbers, that are still set to true, are prime + for (int i = 2; i <= max; i++) { + if (isPrime[i]) { + primes.push_back(i); + } + } +} + +int main() { + int n = 100; + vector primes; + // Find primes up to n + sieve_of_eratosthenes(primes, n); + cout << "Primes up to "< + +using namespace std; + +void createMinSegmentTree(int arr[],int sg[],int index,int begin,int end){ + //create the segment tree. + if(begin == end){ + sg[index] = arr[begin]; + return; + } + int mid = (begin+end)/2; + createMinSegmentTree(arr,sg,2*index,begin,mid); + createMinSegmentTree(arr,sg,2*index+1,mid+1,end); + sg[index] = min(sg[2*index],sg[2*index+1]); + return; + +} + +int queryMinSegmentTree(int sg[],int l,int r,int index,int begin,int end){ + //querying the segment tree + + //complete overlap + if(l <= begin && r >= end){ + return sg[index]; + } + //no overlap + else if(r end){ + return INT_MAX; + } + //partial overlap + else{ + int mid = (begin+end)/2; + return min(queryMinSegmentTree(sg,l,r,2*index,begin,mid),queryMinSegmentTree(sg,l,r,2*index+1,mid+1,end)); + } + +} + +void updateMinSegmentTree(int sg[],int l,int r,int index,int begin,int end,int update){ + + if(begin == end && begin>=l && begin<=r){ + sg[index]+=update; + return; + } + if(l>end || r> n; + + int arr[n]; + + for(int i=0;i> q; + + int l,r,option; + while(q--){ + cin >> option; + + //option 1 to query the segment tree with range [l,r]. + if(option == 1){ + cin >> l >> r; + cout << queryMinSegmentTree(sg,l,r,1,0,n-1)<> l >> r >> update; + updateMinSegmentTree(sg,l,r,1,0,n-1,update); + } + } + + + return 0; +} \ No newline at end of file diff --git a/stack/Stack.java b/stack/Stack.java new file mode 100644 index 00000000..a59158c8 --- /dev/null +++ b/stack/Stack.java @@ -0,0 +1,73 @@ +import java.lang.IndexOutOfBoundsException; +import java.util.Arrays; + +public class Stack { + private int max; + private int top; + private Object[] list; + + public Stack() { + max = 512; + top = 0; + list = new Object[max]; + } + + public Stack(int size) { + max = size; + top = 0; + list = new Object[max]; + } + + @SuppressWarnings("unchecked") + public boolean isEmpty() { + for(E t : (E[]) list) { + if(t != null) { + return false; + } + } + + return true; + } + + @SuppressWarnings("unchecked") + public E peek() { + return (E) list[top]; + } + + @SuppressWarnings("unchecked") + public int size() { + if(top == 0) { + return 0; + } + + int count = 0; + for(E t : (E[]) list) { + if(t != null) { + count++; + } + } + + return count; + } + + @SuppressWarnings("unchecked") + public E pop() { + if(isEmpty()) { + throw new IndexOutOfBoundsException("This stack is empty; nothing to pop."); + } + + E data = (E) list[top]; + + top = (top == 0 ? 0 : top - 1); + return data; + } + + public void push(E data) { + if(top == max - 1) { + list = Arrays.copyOf(list, list.length * 2); + } + + top++; + list[top] = data; + } +} diff --git a/stack/largestRectangleHistogram.cpp b/stack/largestRectangleHistogram.cpp new file mode 100644 index 00000000..a09baa34 --- /dev/null +++ b/stack/largestRectangleHistogram.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; +int main() { + int n; + int a[]={6,2,5,4,5,1,6}; //input array + n = sizeof(a)/sizeof(a[0]); + int i,q; + stack s; // stack to calculate max area + i=0; + int area,maxarea=INT_MIN; + while(i