From 5db5bcba095e48d7cec4f88c124a9197452cd36a Mon Sep 17 00:00:00 2001 From: Navya Date: Mon, 19 Oct 2020 14:47:53 +0530 Subject: [PATCH 1/2] Searching algorithms --- Algorithms/Intro.md | 2 +- C++/FibonacciSearch.cpp | 158 ++--- C++/Intro.md | 4 +- .../Combination_formula.cpp | 42 +- C++/bubblesort.cpp | 110 +-- C/Intro.md | 4 +- Contribution.md | 112 +-- Data Structures/BST.py | 204 +++--- Data Structures/BinaryTree/README.md | 0 .../BinaryTree/libs/hamcrest-core-1.3.jar | Bin .../BinaryTree/libs/junit-4.12.jar | Bin Data Structures/CircularLinkedlist.c | 372 +++++----- Data Structures/DLL.cpp | 638 +++++++++--------- ...ount the no. of nodes in a linked list.cpp | 116 ++-- .../Searching algorithms/Binarysearch.cpp | 25 + .../Searching algorithms/Linearsearch.cpp | 28 + .../Stack-Implementation-LinkedList.cpp | 146 ++-- Java/DynamicDispatch.java | 84 +-- Java/Fibonacci.java | 48 +- Java/Intro.md | 4 +- Java/Palindrome.java | 46 +- Java/Pattern.java | 64 +- Java/ReverseNumber.java | 34 +- JavaScript/Game of Dice | 1 - .../ExampleInstrumentedTest.java | 26 - Python/HandDino | 278 ++++---- Python/Notepad.py | 372 +++++----- Python/castle.py | 610 ++++++++--------- Python/invisible_cloak | 158 ++--- Suduko Solver/README.md | 62 +- TIC TAC TOE USING PYTHON/tictactoe.py | 162 ++--- Websites/Contactme.html | 360 +++++----- 32 files changed, 2148 insertions(+), 2122 deletions(-) mode change 100755 => 100644 Data Structures/BinaryTree/README.md mode change 100755 => 100644 Data Structures/BinaryTree/libs/hamcrest-core-1.3.jar mode change 100755 => 100644 Data Structures/BinaryTree/libs/junit-4.12.jar create mode 100644 Data Structures/Searching algorithms/Binarysearch.cpp create mode 100644 Data Structures/Searching algorithms/Linearsearch.cpp delete mode 160000 JavaScript/Game of Dice delete mode 100644 MemorablePlaces App/app/src/androidTest/java/com/example/memorableplaces/ExampleInstrumentedTest.java diff --git a/Algorithms/Intro.md b/Algorithms/Intro.md index fd69e59..229b272 100644 --- a/Algorithms/Intro.md +++ b/Algorithms/Intro.md @@ -1 +1 @@ -Contribute by writing algorithms in whichever Programming Language you want. +Contribute by writing algorithms in whichever Programming Language you want. diff --git a/C++/FibonacciSearch.cpp b/C++/FibonacciSearch.cpp index b344f40..bcf960e 100644 --- a/C++/FibonacciSearch.cpp +++ b/C++/FibonacciSearch.cpp @@ -1,79 +1,79 @@ -// Cpp program for Fibonacci Search - -#include -using namespace std ; - -// Utility function to find minimum of two elements -int min(int x, int y) { - return (x<=y)? x : y; -} - -/* Returns index of x if present, else returns -1 */ -int fibMonaccianSearch(int arr[], int x, int n) -{ - /* 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 i = 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[i] < x) - { - fibM = fibMMm1; - fibMMm1 = fibMMm2; - fibMMm2 = fibM - fibMMm1; - offset = i; - } - - /* If x is greater than the value at index fibMm2, - cut the subarray after i+1 */ - else if (arr[i] > x) - { - fibM = fibMMm2; - fibMMm1 = fibMMm1 - fibMMm2; - fibMMm2 = fibM - fibMMm1; - } - - /* element found. return index */ - else - return i; - } - - /* comparing the last element with x */ - if(fibMMm1 && arr[offset+1]==x) - return offset+1; - - /*element not found. return -1 */ - return -1; -} - -/* driver function */ -int main(void) -{ - int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; - int n = sizeof(arr)/sizeof(arr[0]); - int x = 85; - cout<<"Found at index: "< +using namespace std ; + +// Utility function to find minimum of two elements +int min(int x, int y) { + return (x<=y)? x : y; +} + +/* Returns index of x if present, else returns -1 */ +int fibMonaccianSearch(int arr[], int x, int n) +{ + /* 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 i = 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[i] < x) + { + fibM = fibMMm1; + fibMMm1 = fibMMm2; + fibMMm2 = fibM - fibMMm1; + offset = i; + } + + /* If x is greater than the value at index fibMm2, + cut the subarray after i+1 */ + else if (arr[i] > x) + { + fibM = fibMMm2; + fibMMm1 = fibMMm1 - fibMMm2; + fibMMm2 = fibM - fibMMm1; + } + + /* element found. return index */ + else + return i; + } + + /* comparing the last element with x */ + if(fibMMm1 && arr[offset+1]==x) + return offset+1; + + /*element not found. return -1 */ + return -1; +} + +/* driver function */ +int main(void) +{ + int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; + int n = sizeof(arr)/sizeof(arr[0]); + int x = 85; + cout<<"Found at index: "< -using namespace std; - -int C(int n,int r) -{ - if(r==0 || n==r) - return 1; - else - return C(n-1,r-1) + C(n-1,r); -} -int main() { - int n; - int r; - cout<<"Combination Formula :\n nCr = n!/(r!*(n-r)!)\n"; - cout<<"Enter the value of n : "; - cin>>n; - cout<<"enter the value of r : "; - cin>>r; - cout<<"\n"< +using namespace std; + +int C(int n,int r) +{ + if(r==0 || n==r) + return 1; + else + return C(n-1,r-1) + C(n-1,r); +} +int main() { + int n; + int r; + cout<<"Combination Formula :\n nCr = n!/(r!*(n-r)!)\n"; + cout<<"Enter the value of n : "; + cin>>n; + cout<<"enter the value of r : "; + cin>>r; + cout<<"\n"< -using namespace std; -#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(0) - -void swap(int *xp, int *yp) -{ - int temp = *xp; - *xp = *yp; - *yp = temp; -} - -// An optimized version of Bubble Sort -void bubbleSort(int arr[], int n) -{ - int i, j; - bool swapped; - for (i = 0; i < n-1; i++) - { - swapped = false; - for (j = 0; j < n-i-1; j++) - { - if (arr[j] > arr[j+1]) - { - swap(&arr[j], &arr[j+1]); - swapped = true; - } - } - - // IF no two elements were swapped by inner loop, then break - if (swapped == false) - break; - } -} - -/* Function to print an array */ -void printArray(int arr[], int size) -{ - int i; - for (i=0; i < size; i++) - cout< +using namespace std; +#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(0) + +void swap(int *xp, int *yp) +{ + int temp = *xp; + *xp = *yp; + *yp = temp; +} + +// An optimized version of Bubble Sort +void bubbleSort(int arr[], int n) +{ + int i, j; + bool swapped; + for (i = 0; i < n-1; i++) + { + swapped = false; + for (j = 0; j < n-i-1; j++) + { + if (arr[j] > arr[j+1]) + { + swap(&arr[j], &arr[j+1]); + swapped = true; + } + } + + // IF no two elements were swapped by inner loop, then break + if (swapped == false) + break; + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + cout< data: - if self.left: - return self.left.insert(data) - else: - self.left = Node(data) - return True - else: - if self.right: - return self.right.insert(data) - else: - self.right = Node(data) - return True - - def find(self, data): - if self.val == data: - return True - elif self.val > data: - if self.left: - return self.left.find(data) - else: - return False - else: - if self.right: - return self.right.find(data) - else: - return False - - def preorder(self): - if self: - print(str(self.val), end=" ") - if self.left: - self.left.preorder() - if self.right: - self.right.preorder() - - def postorder(self): - if self: - if self.left: - self.left.postorder() - if self.right: - self.right.postorder() - print(str(self.val), end=" ") - - def inorder(self): - if self: - if self.left: - self.left.inorder() - print(str(self.val), end=" ") - if self.right: - self.right.inorder() - - -class Tree: - def __init__(self): - self.root = None - - def insert(self, data): - if self.root: - self.root.insert(data) - else: - self.root = Node(data) - return True - - def find(self, data): - if self.root: - return self.root.find(data) - else: - return False - - def preorder(self): - print('Preorder') - self.root.preorder() - - def postorder(self): - print('Postorder') - self.root.postorder() - - def inorder(self): - print('Inorder') - self.root.inorder() - - -bst = Tree() -bst.insert(10) -bst.insert(40) -bst.insert(44) -bst.insert(32) -bst.preorder() -print() -bst.postorder() -print() -bst.inorder() +class Node: + def __init__(self, val): + self.left = None + self.right = None + self.val = val + + def insert(self, data): + if self.val == data: + return False + + elif self.val > data: + if self.left: + return self.left.insert(data) + else: + self.left = Node(data) + return True + else: + if self.right: + return self.right.insert(data) + else: + self.right = Node(data) + return True + + def find(self, data): + if self.val == data: + return True + elif self.val > data: + if self.left: + return self.left.find(data) + else: + return False + else: + if self.right: + return self.right.find(data) + else: + return False + + def preorder(self): + if self: + print(str(self.val), end=" ") + if self.left: + self.left.preorder() + if self.right: + self.right.preorder() + + def postorder(self): + if self: + if self.left: + self.left.postorder() + if self.right: + self.right.postorder() + print(str(self.val), end=" ") + + def inorder(self): + if self: + if self.left: + self.left.inorder() + print(str(self.val), end=" ") + if self.right: + self.right.inorder() + + +class Tree: + def __init__(self): + self.root = None + + def insert(self, data): + if self.root: + self.root.insert(data) + else: + self.root = Node(data) + return True + + def find(self, data): + if self.root: + return self.root.find(data) + else: + return False + + def preorder(self): + print('Preorder') + self.root.preorder() + + def postorder(self): + print('Postorder') + self.root.postorder() + + def inorder(self): + print('Inorder') + self.root.inorder() + + +bst = Tree() +bst.insert(10) +bst.insert(40) +bst.insert(44) +bst.insert(32) +bst.preorder() +print() +bst.postorder() +print() +bst.inorder() bst.find(77) \ No newline at end of file diff --git a/Data Structures/BinaryTree/README.md b/Data Structures/BinaryTree/README.md old mode 100755 new mode 100644 diff --git a/Data Structures/BinaryTree/libs/hamcrest-core-1.3.jar b/Data Structures/BinaryTree/libs/hamcrest-core-1.3.jar old mode 100755 new mode 100644 diff --git a/Data Structures/BinaryTree/libs/junit-4.12.jar b/Data Structures/BinaryTree/libs/junit-4.12.jar old mode 100755 new mode 100644 diff --git a/Data Structures/CircularLinkedlist.c b/Data Structures/CircularLinkedlist.c index cc2401c..1e9d140 100644 --- a/Data Structures/CircularLinkedlist.c +++ b/Data Structures/CircularLinkedlist.c @@ -1,186 +1,186 @@ -#include -#include -typedef struct CirclLL{ - int data; - struct CirclLL* link; -}CLL; -CLL* head=NULL; -void create(){ - int element; - printf("Enter element:"); - scanf("%d",&element); - CLL *p=malloc(sizeof(CLL)); - p->data=element; - head=p; - p->link=head; - return; -} -void insert_begin(){ - CLL* p=malloc(sizeof(CLL)); - int val; - printf("Enter a value:"); - scanf("%d",&val); - p->data=val; - CLL* m=head; - while(m->link!=head){ - m=m->link; - } - p->link=head; - m->link=p; - head=p; - return; -} -void insert_end(){ - CLL* t=head; - CLL* p=malloc(sizeof(CLL)); - int val; - printf("Enter a value:"); - scanf("%d",&val); - p->data=val; - while(t->link!=head){ - t=t->link; - } - t->link=p; - p->link=head; - return; -} -void insert_anywhere(){ - int pos,count=1; - printf("Enter pos:"); - scanf("%d",&pos); - CLL* temp=head; - while(temp->link!=head){ - if(count==pos){ - int x; - CLL* p=malloc(sizeof(CLL)); - printf("Enter a value:"); - scanf("%d",&x); - p->data=x; - p->link=temp->link; - temp->link=p; - return; - } - temp=temp->link; - ++count; - } - printf("Invalid position\n"); - return; -} -void insert(){ - if(head==NULL){ - create(); - }else{ - int choice; - while(1){ - printf("Enter choice(1.insert_begin;2.insert_end;3.insert_anywhere;4.exit;):"); - scanf("%d",&choice); - switch(choice){ - case 1:insert_begin();break; - case 2:insert_end();break; - case 3:insert_anywhere();break; - case 4:return; - } - } - } -} -void delete_begin(){ - CLL* p=head; - CLL* q=head; - while(p->link!=head){ - p=p->link; - } - p->link=q->link; - head=q->link; - printf("%d deleted\n",q->data); - free(q); - return; -} -void delete_end(){ - CLL* p=head; - CLL* q; - while(p->link!=head){ - q=p; - p=p->link; - } - q->link=head; - printf("%d deleted\n",p->data); - free(p); - return; -} -void delete_anywhere(){ - int pos,count=0; - CLL* temp=head; - CLL* p; - printf("Enter pos:"); - scanf("%d",&pos); - while(temp->link!=head){ - if(count==pos){ - p->link=p->link->link; - printf("%d deleted\n",temp->data); - free(temp); - return; - } - p=temp; - temp=temp->link; - count++; - } - printf("Invalid position\n"); - return; -} -void delete(){ - if(head==NULL){ - printf("Deletion can't be performed\n"); - }else{ - int choice; - while(1){ - printf("Enter choice(1.delete_begin;2.delete_end;3.delete_anywhere;4.exit;):"); - scanf("%d",&choice); - switch(choice){ - case 1:delete_begin();break; - case 2:delete_end();break; - case 3:delete_anywhere();break; - case 4:return; - } - } - } -} -void display(){ - CLL* temp=head; - if(head==NULL){ - printf("EMPTY"); - return; - } - while(temp->link!=head){ - printf("%d ",temp->data); - temp=temp->link; - } - printf("%d\n",temp->data); - return; -} -int main(){ - int choice; - while(1){ - printf("Enter choice(1.Insert;2.Delete;3.Display;4.Exit):"); - scanf("%d",&choice); - switch(choice){ - case 1:insert();break; - case 2:delete();break; - case 3:display();break; - case 4:exit(0); - } - } - return 0; -} - - - - - - - - - - - - - +#include +#include +typedef struct CirclLL{ + int data; + struct CirclLL* link; +}CLL; +CLL* head=NULL; +void create(){ + int element; + printf("Enter element:"); + scanf("%d",&element); + CLL *p=malloc(sizeof(CLL)); + p->data=element; + head=p; + p->link=head; + return; +} +void insert_begin(){ + CLL* p=malloc(sizeof(CLL)); + int val; + printf("Enter a value:"); + scanf("%d",&val); + p->data=val; + CLL* m=head; + while(m->link!=head){ + m=m->link; + } + p->link=head; + m->link=p; + head=p; + return; +} +void insert_end(){ + CLL* t=head; + CLL* p=malloc(sizeof(CLL)); + int val; + printf("Enter a value:"); + scanf("%d",&val); + p->data=val; + while(t->link!=head){ + t=t->link; + } + t->link=p; + p->link=head; + return; +} +void insert_anywhere(){ + int pos,count=1; + printf("Enter pos:"); + scanf("%d",&pos); + CLL* temp=head; + while(temp->link!=head){ + if(count==pos){ + int x; + CLL* p=malloc(sizeof(CLL)); + printf("Enter a value:"); + scanf("%d",&x); + p->data=x; + p->link=temp->link; + temp->link=p; + return; + } + temp=temp->link; + ++count; + } + printf("Invalid position\n"); + return; +} +void insert(){ + if(head==NULL){ + create(); + }else{ + int choice; + while(1){ + printf("Enter choice(1.insert_begin;2.insert_end;3.insert_anywhere;4.exit;):"); + scanf("%d",&choice); + switch(choice){ + case 1:insert_begin();break; + case 2:insert_end();break; + case 3:insert_anywhere();break; + case 4:return; + } + } + } +} +void delete_begin(){ + CLL* p=head; + CLL* q=head; + while(p->link!=head){ + p=p->link; + } + p->link=q->link; + head=q->link; + printf("%d deleted\n",q->data); + free(q); + return; +} +void delete_end(){ + CLL* p=head; + CLL* q; + while(p->link!=head){ + q=p; + p=p->link; + } + q->link=head; + printf("%d deleted\n",p->data); + free(p); + return; +} +void delete_anywhere(){ + int pos,count=0; + CLL* temp=head; + CLL* p; + printf("Enter pos:"); + scanf("%d",&pos); + while(temp->link!=head){ + if(count==pos){ + p->link=p->link->link; + printf("%d deleted\n",temp->data); + free(temp); + return; + } + p=temp; + temp=temp->link; + count++; + } + printf("Invalid position\n"); + return; +} +void delete(){ + if(head==NULL){ + printf("Deletion can't be performed\n"); + }else{ + int choice; + while(1){ + printf("Enter choice(1.delete_begin;2.delete_end;3.delete_anywhere;4.exit;):"); + scanf("%d",&choice); + switch(choice){ + case 1:delete_begin();break; + case 2:delete_end();break; + case 3:delete_anywhere();break; + case 4:return; + } + } + } +} +void display(){ + CLL* temp=head; + if(head==NULL){ + printf("EMPTY"); + return; + } + while(temp->link!=head){ + printf("%d ",temp->data); + temp=temp->link; + } + printf("%d\n",temp->data); + return; +} +int main(){ + int choice; + while(1){ + printf("Enter choice(1.Insert;2.Delete;3.Display;4.Exit):"); + scanf("%d",&choice); + switch(choice){ + case 1:insert();break; + case 2:delete();break; + case 3:display();break; + case 4:exit(0); + } + } + return 0; +} + + + + + + + + + + + + + diff --git a/Data Structures/DLL.cpp b/Data Structures/DLL.cpp index 7997094..10fa6ff 100644 --- a/Data Structures/DLL.cpp +++ b/Data Structures/DLL.cpp @@ -1,319 +1,319 @@ -#include -#include -#include -using namespace std; -template class Node -{ public: - T info; - Node *next,*prev; - Node(T data) - { - info=data; - next=prev=NULL; - } -}; -template class DLL -{ private: - Node *head,*tail; - - void insertAtBeg(T data) - { - Node *temp=new Node (data);; - if(head==NULL) - head=tail=temp; - else - { - temp->next=head; - head->prev=temp; - head=temp; - } - } - - void insertAtEnd(T data) - { - Node *temp=new Node(data);; - if(head==NULL) - head=tail=temp; - else - { - tail->next=temp;; - temp->prev=tail; - tail=temp; - } - } - - void insertAtPos(T data,int pos) - { - Node *temp=new Node(data); - if(head==NULL) - head=tail=temp; - else if(head==tail && pos>1) - insertAtEnd(data); - else if(pos==1) - insertAtBeg(data); - else - { - Node *current=head; - while(pos>2&¤t->next!=NULL) - { - current=current->next; - pos--; - } - if(current->next==NULL) - insertAtEnd(data); - else - { - temp->next=current->next; - current->next=temp; - temp->prev=current; - current=current->next->next; - current->prev=temp; - } - - } - } - - T deleteBeg() - { - T val; - if(head==NULL) - throw "\n Linked List Empty"; - else if (head==tail) - { - val=head->info; - delete head; - head=tail=NULL; - return val; - } - else - { - val=head->info; - head=head->next; - delete head->prev; - return val; - } - } - - T deleteEnd() - { - T val; - if(head==NULL) - throw "\n Linked List Empty"; - else if (head==tail) - { - val=head->info; - delete head; - head=tail=NULL; - return val; - } - else - { - val=tail->info; - tail=tail->prev; - delete tail->next; - tail->next=NULL; - return val; - } - } - - void deleteData(T data) - { - if(head==NULL) - throw "\n Linked List Empty"; - else if (head==tail) - { - if(head->info==data) - deleteBeg(); - else - throw "\n No such data in Linked List"; - } - else if(head->info==data) - deleteBeg(); - else if(tail->info==data) - deleteEnd(); - else - { - Node *current=head; - while(current->info!=data&¤t!=tail) - current=current->next; - if(current!=tail) - { - current->prev->next=current->next; - current->next->prev=current->prev; - delete current; - } - else - throw "\n No such data in Linked List"; - } - } - - void count() - { - Node *current=head; - int count=0; - while(current!=NULL) - { - current=current->next; - count++; - } - if(count ==0) - throw "Linked List is empty\n "; - else - cout<<"\n Total Elements in Linked List "< *current=head; - if(current!=NULL) - { - int count=1; - while(current!=NULL) - { - cout<<"S.NO. "<info<<"\n"; - current=current->next; - } - } - else - cout<<"\n Empty Linked List"; - } - - void reverse() - { - if(head!=NULL&&head!=tail) - { - bool tf=1; - Node *current=head; - while(tf) - { - Node *temp=current->prev; - current->prev=current->next; - current->next=temp; - current=current->prev; - if(current==NULL) - { - temp=head; - head=tail; - tail=temp; - tf=0; - } - } - } - } - - bool isPresent(T data) - { - int f=0; - Node *temp=head; - while(temp!=NULL) - { - if(temp->info==data) - { - f=1; - break; - } - temp=temp->next; - } - if(f==1) - return 1; - else - return 0; - } - - - int menu() - { - int ch; - cout<<"\n MENU\n"; - cout<<"1. Insert At Beginning\n"; - cout<<"2. Insert At End\n"; - cout<<"3. Insert At Particular Position\n"; - cout<<"4. Delete At Beginning\n"; - cout<<"5. Delete At End\n"; - cout<<"6. Delete At Particular Data\n"; - cout<<"7. Check if Data is present or Not\n"; - cout<<"8. Reverse\n"; - cout<<"9. Count the number of elements\n"; - cout<<"10. Display\n"; - cout<<"11. EXIT\n"; - cout<<"ENTER CHOICE\n"; - cin>>ch; - return ch; - } - public: - DLL() - { - head=tail=NULL; - } - void prog() - { - T data; - int posdata, ch; - do - { - ch=menu(); - try - { - switch(ch) - { - case 1: cout<<"Enter data to be inserted\n"; - cin>>data; - insertAtBeg(data); - break; - case 2: cout<<"Enter data to be inserted\n"; - cin>>data; - insertAtEnd(data); - break; - case 3: cout<<"Enter data to be inserted\n"; - cin>>data; - cout<<"Enter postion at which insert needed\n"; - cin>>posdata; - insertAtPos(data,posdata); - break; - case 4: data=deleteBeg(); - cout<<"Deleted data value at Beginning: "<>data; - deleteData(data); - break; - case 7: cout<<"Enter data to be searched\n"; - cin>>data; - if(isPresent(data)) - cout<<"Data is present\n"; - else - cout<<"Data is not present\n"; - break; - case 8: cout<<"Old Linked List\n"; - display(); - reverse(); - cout<<"Reversed Linked List\n"; - display(); - break; - case 9:count(); - break; - case 10:display(); - break; - case 11:exit(0); - break; - default:cout<<"\nEntered Choice is Wrong\n"; - exit(0); - } - } - catch (const char* c) - { - cout< LL; - LL.prog(); - getch(); -} +#include +#include +#include +using namespace std; +template class Node +{ public: + T info; + Node *next,*prev; + Node(T data) + { + info=data; + next=prev=NULL; + } +}; +template class DLL +{ private: + Node *head,*tail; + + void insertAtBeg(T data) + { + Node *temp=new Node (data);; + if(head==NULL) + head=tail=temp; + else + { + temp->next=head; + head->prev=temp; + head=temp; + } + } + + void insertAtEnd(T data) + { + Node *temp=new Node(data);; + if(head==NULL) + head=tail=temp; + else + { + tail->next=temp;; + temp->prev=tail; + tail=temp; + } + } + + void insertAtPos(T data,int pos) + { + Node *temp=new Node(data); + if(head==NULL) + head=tail=temp; + else if(head==tail && pos>1) + insertAtEnd(data); + else if(pos==1) + insertAtBeg(data); + else + { + Node *current=head; + while(pos>2&¤t->next!=NULL) + { + current=current->next; + pos--; + } + if(current->next==NULL) + insertAtEnd(data); + else + { + temp->next=current->next; + current->next=temp; + temp->prev=current; + current=current->next->next; + current->prev=temp; + } + + } + } + + T deleteBeg() + { + T val; + if(head==NULL) + throw "\n Linked List Empty"; + else if (head==tail) + { + val=head->info; + delete head; + head=tail=NULL; + return val; + } + else + { + val=head->info; + head=head->next; + delete head->prev; + return val; + } + } + + T deleteEnd() + { + T val; + if(head==NULL) + throw "\n Linked List Empty"; + else if (head==tail) + { + val=head->info; + delete head; + head=tail=NULL; + return val; + } + else + { + val=tail->info; + tail=tail->prev; + delete tail->next; + tail->next=NULL; + return val; + } + } + + void deleteData(T data) + { + if(head==NULL) + throw "\n Linked List Empty"; + else if (head==tail) + { + if(head->info==data) + deleteBeg(); + else + throw "\n No such data in Linked List"; + } + else if(head->info==data) + deleteBeg(); + else if(tail->info==data) + deleteEnd(); + else + { + Node *current=head; + while(current->info!=data&¤t!=tail) + current=current->next; + if(current!=tail) + { + current->prev->next=current->next; + current->next->prev=current->prev; + delete current; + } + else + throw "\n No such data in Linked List"; + } + } + + void count() + { + Node *current=head; + int count=0; + while(current!=NULL) + { + current=current->next; + count++; + } + if(count ==0) + throw "Linked List is empty\n "; + else + cout<<"\n Total Elements in Linked List "< *current=head; + if(current!=NULL) + { + int count=1; + while(current!=NULL) + { + cout<<"S.NO. "<info<<"\n"; + current=current->next; + } + } + else + cout<<"\n Empty Linked List"; + } + + void reverse() + { + if(head!=NULL&&head!=tail) + { + bool tf=1; + Node *current=head; + while(tf) + { + Node *temp=current->prev; + current->prev=current->next; + current->next=temp; + current=current->prev; + if(current==NULL) + { + temp=head; + head=tail; + tail=temp; + tf=0; + } + } + } + } + + bool isPresent(T data) + { + int f=0; + Node *temp=head; + while(temp!=NULL) + { + if(temp->info==data) + { + f=1; + break; + } + temp=temp->next; + } + if(f==1) + return 1; + else + return 0; + } + + + int menu() + { + int ch; + cout<<"\n MENU\n"; + cout<<"1. Insert At Beginning\n"; + cout<<"2. Insert At End\n"; + cout<<"3. Insert At Particular Position\n"; + cout<<"4. Delete At Beginning\n"; + cout<<"5. Delete At End\n"; + cout<<"6. Delete At Particular Data\n"; + cout<<"7. Check if Data is present or Not\n"; + cout<<"8. Reverse\n"; + cout<<"9. Count the number of elements\n"; + cout<<"10. Display\n"; + cout<<"11. EXIT\n"; + cout<<"ENTER CHOICE\n"; + cin>>ch; + return ch; + } + public: + DLL() + { + head=tail=NULL; + } + void prog() + { + T data; + int posdata, ch; + do + { + ch=menu(); + try + { + switch(ch) + { + case 1: cout<<"Enter data to be inserted\n"; + cin>>data; + insertAtBeg(data); + break; + case 2: cout<<"Enter data to be inserted\n"; + cin>>data; + insertAtEnd(data); + break; + case 3: cout<<"Enter data to be inserted\n"; + cin>>data; + cout<<"Enter postion at which insert needed\n"; + cin>>posdata; + insertAtPos(data,posdata); + break; + case 4: data=deleteBeg(); + cout<<"Deleted data value at Beginning: "<>data; + deleteData(data); + break; + case 7: cout<<"Enter data to be searched\n"; + cin>>data; + if(isPresent(data)) + cout<<"Data is present\n"; + else + cout<<"Data is not present\n"; + break; + case 8: cout<<"Old Linked List\n"; + display(); + reverse(); + cout<<"Reversed Linked List\n"; + display(); + break; + case 9:count(); + break; + case 10:display(); + break; + case 11:exit(0); + break; + default:cout<<"\nEntered Choice is Wrong\n"; + exit(0); + } + } + catch (const char* c) + { + cout< LL; + LL.prog(); + getch(); +} diff --git a/Data Structures/LinkedList/Count the no. of nodes in a linked list.cpp b/Data Structures/LinkedList/Count the no. of nodes in a linked list.cpp index 0f70e2c..e0353d5 100644 --- a/Data Structures/LinkedList/Count the no. of nodes in a linked list.cpp +++ b/Data Structures/LinkedList/Count the no. of nodes in a linked list.cpp @@ -1,59 +1,59 @@ -#include -using namespace std; - -struct Node -{ - int data; - Node *next; -}; -Node* insertAtBeg(Node *ptr) -{ - int a; - Node *temp= new Node(); - cout<<"Enter the data to be inserted at the beginning of the linked list - \n"; - cin>>a; - temp->data = a; - temp->next = ptr; - ptr = temp; - return ptr; -} - -int Count (Node *ptr) -{ - int count=0; - while(ptr) - { - count++; - ptr=ptr->next; - } - return count; -} -Node* display(Node *ptr) -{ - while(ptr!=NULL) - { - cout<data<<" "; - ptr = ptr->next; - } - cout<<"\n"; -} -int main() -{ Node* Head = NULL; - int num; - while(1) - { - cout<<"1. Enter 1 to insert an element in linked list\n2. Enter 2 to display element of a linked list\n3. Count the no. of nodes in a linked list\n4. Exit\nEnter you choice : "; - cin>>num; - switch(num) - { - case 1: Head = insertAtBeg(Head); - break; - case 2: display(Head); - break; - case 3: cout< +using namespace std; + +struct Node +{ + int data; + Node *next; +}; +Node* insertAtBeg(Node *ptr) +{ + int a; + Node *temp= new Node(); + cout<<"Enter the data to be inserted at the beginning of the linked list - \n"; + cin>>a; + temp->data = a; + temp->next = ptr; + ptr = temp; + return ptr; +} + +int Count (Node *ptr) +{ + int count=0; + while(ptr) + { + count++; + ptr=ptr->next; + } + return count; +} +Node* display(Node *ptr) +{ + while(ptr!=NULL) + { + cout<data<<" "; + ptr = ptr->next; + } + cout<<"\n"; +} +int main() +{ Node* Head = NULL; + int num; + while(1) + { + cout<<"1. Enter 1 to insert an element in linked list\n2. Enter 2 to display element of a linked list\n3. Count the no. of nodes in a linked list\n4. Exit\nEnter you choice : "; + cin>>num; + switch(num) + { + case 1: Head = insertAtBeg(Head); + break; + case 2: display(Head); + break; + case 3: cout< +using namespace std; +int binarySearch(int arr[], int p, int r, int num) { + if (p <= r) { + int mid = (p + r)/2; + if (arr[mid] == num) + return mid ; + if (arr[mid] > num) + return binarySearch(arr, p, mid-1, num); + if (arr[mid] > num) + return binarySearch(arr, mid+1, r, num); + } + return -1; +} +int main(void) { + int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40}; + int n = sizeof(arr)/ sizeof(arr[0]); + int num = 33; + int index = binarySearch (arr, 0, n-1, num); + if(index == -1) + cout<< num <<" is not present in the array"; + else + cout<< num <<" is present at index "<< index <<" in the array"; + return 0; +} diff --git a/Data Structures/Searching algorithms/Linearsearch.cpp b/Data Structures/Searching algorithms/Linearsearch.cpp new file mode 100644 index 0000000..2093cfc --- /dev/null +++ b/Data Structures/Searching algorithms/Linearsearch.cpp @@ -0,0 +1,28 @@ +// C++ Program to search any element or number in an array +#include +using namespace std; +int main(){ +    int input[100], count, i, num; +    cout << "Enter Number of Elements in Array\n"; +    cin >> count; +      +    cout << "Enter " << count << " numbers \n"; +       +    // Read array elements +    for(i = 0; i < count; i++){ +        cin >> input[i]; +    } +    cout << "Enter a number to serach in Array\n"; +    cin >> num;  +    // search num in inputArray from index 0 to elementCount-1 +    for(i = 0; i < count; i++){ +        if(input[i] == num){ +            cout << "Element found at index " << i; +            break; +        } +    }  +    if(i == count){ +        cout  << "Element Not Present in Input Array\n"; +    } +    return 0; +} \ No newline at end of file diff --git a/Data Structures/Stack-Implementation-LinkedList.cpp b/Data Structures/Stack-Implementation-LinkedList.cpp index 667cdb2..9b94c5f 100644 --- a/Data Structures/Stack-Implementation-LinkedList.cpp +++ b/Data Structures/Stack-Implementation-LinkedList.cpp @@ -1,73 +1,73 @@ -#include -#include -struct node{ - int info; - node *next; -}; -struct node *head=NULL; -struct node* createnode(){ - struct node *n; - n=(struct node*)malloc(sizeof(struct node)); - return n; -} -void pushnode(int a){ - node *n=createnode(); - n->info=a; - if(head==NULL){ - n->next=NULL; - head=n; - } - else{ - n->next=head; - head=n; - } -} -int popnode(){ - node *temp; - int a; - if(head==NULL){ - printf("empty\n"); - return -1; - } - else - { - a=head->info; - temp=head; - head=head->next; - free(temp); - } -return a; -} -void topnode(){ -if(head!=NULL){ - int a=popnode(); - pushnode(a); - printf("%d\n",a); - } - else - { - printf("empty\n"); - } -} -int main(){ - int q,ch,a,b; - head=NULL; - while(1){ - - printf("Enter 1 for inserting in stack\n"); - printf("Enter 2 for deleting top element is stack\n"); - printf("Enter 3 for viewing top element in stack\n"); - printf("Enter 0 for to exit\n"); - scanf("%d",&ch); - switch(ch){ - case 1:scanf("%d",&a); - pushnode(a); - break; - case 2:b=popnode(); - break; - case 3:topnode(); - break; - case 0:return 0; - } - } -} +#include +#include +struct node{ + int info; + node *next; +}; +struct node *head=NULL; +struct node* createnode(){ + struct node *n; + n=(struct node*)malloc(sizeof(struct node)); + return n; +} +void pushnode(int a){ + node *n=createnode(); + n->info=a; + if(head==NULL){ + n->next=NULL; + head=n; + } + else{ + n->next=head; + head=n; + } +} +int popnode(){ + node *temp; + int a; + if(head==NULL){ + printf("empty\n"); + return -1; + } + else + { + a=head->info; + temp=head; + head=head->next; + free(temp); + } +return a; +} +void topnode(){ +if(head!=NULL){ + int a=popnode(); + pushnode(a); + printf("%d\n",a); + } + else + { + printf("empty\n"); + } +} +int main(){ + int q,ch,a,b; + head=NULL; + while(1){ + + printf("Enter 1 for inserting in stack\n"); + printf("Enter 2 for deleting top element is stack\n"); + printf("Enter 3 for viewing top element in stack\n"); + printf("Enter 0 for to exit\n"); + scanf("%d",&ch); + switch(ch){ + case 1:scanf("%d",&a); + pushnode(a); + break; + case 2:b=popnode(); + break; + case 3:topnode(); + break; + case 0:return 0; + } + } +} diff --git a/Java/DynamicDispatch.java b/Java/DynamicDispatch.java index f07623c..933cdcb 100644 --- a/Java/DynamicDispatch.java +++ b/Java/DynamicDispatch.java @@ -1,43 +1,43 @@ -class Base -{ - void func() - { - System.out.println("Inside Base's func method"); - } -} - -class Child1 extends Base -{ - - void func() - { - System.out.println("Inside Child1's func method"); - } -} - -class Child2 extends Child1 -{ - - void func() - { - System.out.println("Inside Child2's func method"); - } -} - - -class DynamicDispatch -{ - public static void main(String args[]) - { - Base b = new Base(); - Child1 c1 = new Child1(); - Child2 c2 = new Child2(); - Base ref; - ref = b; - ref.func(); - ref = c1; - ref.func(); - ref = c2; - ref.func(); - } +class Base +{ + void func() + { + System.out.println("Inside Base's func method"); + } +} + +class Child1 extends Base +{ + + void func() + { + System.out.println("Inside Child1's func method"); + } +} + +class Child2 extends Child1 +{ + + void func() + { + System.out.println("Inside Child2's func method"); + } +} + + +class DynamicDispatch +{ + public static void main(String args[]) + { + Base b = new Base(); + Child1 c1 = new Child1(); + Child2 c2 = new Child2(); + Base ref; + ref = b; + ref.func(); + ref = c1; + ref.func(); + ref = c2; + ref.func(); + } } \ No newline at end of file diff --git a/Java/Fibonacci.java b/Java/Fibonacci.java index 2e244ae..3a5bc7c 100644 --- a/Java/Fibonacci.java +++ b/Java/Fibonacci.java @@ -1,25 +1,25 @@ -import java.util.Scanner; - -public class Fibonacci { - - public static void main(String[] args) { - - Scanner sc = new Scanner(System.in); - System.out.println("Enter the range : "); - int n = sc.nextInt(); - System.out.println("Enter the First term : "); - int f = sc.nextInt(); - System.out.println("Enter the Second term : "); - int s = sc.nextInt(); - System.out.println("First " + n + " terms Are "); - - for (int i = 1; i <= n; ++i) - { - System.out.print(f + " , "); - - int sum = f + s; - f = s; - s = sum; - } - } +import java.util.Scanner; + +public class Fibonacci { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + System.out.println("Enter the range : "); + int n = sc.nextInt(); + System.out.println("Enter the First term : "); + int f = sc.nextInt(); + System.out.println("Enter the Second term : "); + int s = sc.nextInt(); + System.out.println("First " + n + " terms Are "); + + for (int i = 1; i <= n; ++i) + { + System.out.print(f + " , "); + + int sum = f + s; + f = s; + s = sum; + } + } } \ No newline at end of file diff --git a/Java/Intro.md b/Java/Intro.md index 9ff54b5..9b18da9 100644 --- a/Java/Intro.md +++ b/Java/Intro.md @@ -1,2 +1,2 @@ -Write Java programs and participate in #HacktoberFest2020 by contributing to open-source. -You can create new branch for specific projects. +Write Java programs and participate in #HacktoberFest2020 by contributing to open-source. +You can create new branch for specific projects. diff --git a/Java/Palindrome.java b/Java/Palindrome.java index dd1f442..b305008 100644 --- a/Java/Palindrome.java +++ b/Java/Palindrome.java @@ -1,24 +1,24 @@ -import java.util.Scanner; - -class Palindrome -{ - public static void main(String args[]) - { - String str, rev = ""; - Scanner sc = new Scanner(System.in); - - System.out.println("Enter a string or Number : "); - str = sc.nextLine(); - - int length = str.length(); - - for ( int i = length - 1; i >= 0; i-- ) - rev = rev + str.charAt(i); - - if (str.equals(rev)) - System.out.println(str+" is a palindrome"); - else - System.out.println(str+" is not a palindrome"); - - } +import java.util.Scanner; + +class Palindrome +{ + public static void main(String args[]) + { + String str, rev = ""; + Scanner sc = new Scanner(System.in); + + System.out.println("Enter a string or Number : "); + str = sc.nextLine(); + + int length = str.length(); + + for ( int i = length - 1; i >= 0; i-- ) + rev = rev + str.charAt(i); + + if (str.equals(rev)) + System.out.println(str+" is a palindrome"); + else + System.out.println(str+" is not a palindrome"); + + } } \ No newline at end of file diff --git a/Java/Pattern.java b/Java/Pattern.java index 31b9719..b065cb9 100644 --- a/Java/Pattern.java +++ b/Java/Pattern.java @@ -1,33 +1,33 @@ -import java.util.Scanner; - -public class Pattern -{ - public static void main(String[] args) - { - - Scanner scanner = new Scanner(System.in); - - System.out.println("Enter the number of rows : "); - - int rows = scanner.nextInt(); - - System.out.println("...The Pattern..."); - - for (int i = 1; i <= rows; i++) - { - for (int j = rows; j > i; j--) - { - System.out.print(" "); - } - for (int k = 1; k <= i; k++) - { - System.out.print(k); - } - for (int l = i - 1; l >= 1; l--) - { - System.out.print(l); - } - System.out.println(); - } - } +import java.util.Scanner; + +public class Pattern +{ + public static void main(String[] args) + { + + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the number of rows : "); + + int rows = scanner.nextInt(); + + System.out.println("...The Pattern..."); + + for (int i = 1; i <= rows; i++) + { + for (int j = rows; j > i; j--) + { + System.out.print(" "); + } + for (int k = 1; k <= i; k++) + { + System.out.print(k); + } + for (int l = i - 1; l >= 1; l--) + { + System.out.print(l); + } + System.out.println(); + } + } } \ No newline at end of file diff --git a/Java/ReverseNumber.java b/Java/ReverseNumber.java index c247cf9..bb81771 100644 --- a/Java/ReverseNumber.java +++ b/Java/ReverseNumber.java @@ -1,18 +1,18 @@ -import java.util.Scanner; - -public class ReverseNumber -{ - public static void main(String[] args) - { - int n,rev=0; - Scanner sc= new Scanner(System.in); - System.out.println("Enter The Number : "); - n = sc.nextInt(); - System.out.print("Reverse Of "+n+" is "); - while(n>0) - { - System.out.print((rev*10)+n%10); - n=n/10; - } - } +import java.util.Scanner; + +public class ReverseNumber +{ + public static void main(String[] args) + { + int n,rev=0; + Scanner sc= new Scanner(System.in); + System.out.println("Enter The Number : "); + n = sc.nextInt(); + System.out.print("Reverse Of "+n+" is "); + while(n>0) + { + System.out.print((rev*10)+n%10); + n=n/10; + } + } } \ No newline at end of file diff --git a/JavaScript/Game of Dice b/JavaScript/Game of Dice deleted file mode 160000 index 0dbaa9f..0000000 --- a/JavaScript/Game of Dice +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0dbaa9f9f961bd29d5e2f23217ee402cfbe1d722 diff --git a/MemorablePlaces App/app/src/androidTest/java/com/example/memorableplaces/ExampleInstrumentedTest.java b/MemorablePlaces App/app/src/androidTest/java/com/example/memorableplaces/ExampleInstrumentedTest.java deleted file mode 100644 index 0d4171e..0000000 --- a/MemorablePlaces App/app/src/androidTest/java/com/example/memorableplaces/ExampleInstrumentedTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.example.memorableplaces; - -import android.content.Context; - -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - -/** - * Instrumented test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class ExampleInstrumentedTest { - @Test - public void useAppContext() { - // Context of the app under test. - Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); - assertEquals("com.example.memorableplaces", appContext.getPackageName()); - } -} \ No newline at end of file diff --git a/Python/HandDino b/Python/HandDino index a74e929..ee61f1b 100644 --- a/Python/HandDino +++ b/Python/HandDino @@ -1,140 +1,140 @@ -""" -Playing Chrome's Dinosaur game using hand movements via OpenCV and Python. - -Packages Required -OpenCV (cv2) -numpy -math -pyautogui -Execution -Run the program and switch over to chrome and open chrome://dino Keep your hand within the rectangle as you start. Move your hand to make the dino jump. - -Tests and Controls -Change the HSV values to suit your lighting condtions. - -""" - -import numpy as np -import cv2 - -import math -import pyautogui - - -# Open Camera -capture = cv2.VideoCapture(0) - -while capture.isOpened(): - - # Capture frames from the camera - ret, frame = capture.read() - - # Get hand data from the rectangle sub window - cv2.rectangle(frame, (100, 100), (300, 300), (0, 255, 0), 0) - crop_image = frame[100:300, 100:300] - - # Apply Gaussian blur - blur = cv2.GaussianBlur(crop_image, (3, 3), 0) - - # Change color-space from BGR -> HSV - hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) - - # Create a binary image with where white will be skin colors and rest is black - mask2 = cv2.inRange(hsv, np.array([2, 0, 0]), np.array([20, 255, 255])) - - # Kernel for morphological transformation - kernel = np.ones((5, 5)) - - # Apply morphological transformations to filter out the background noise - dilation = cv2.dilate(mask2, kernel, iterations=1) - erosion = cv2.erode(dilation, kernel, iterations=1) - - # Apply Gaussian Blur and Threshold - filtered = cv2.GaussianBlur(erosion, (3, 3), 0) - ret, thresh = cv2.threshold(filtered, 127, 255, 0) -##### - # Find contours - #image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) - contours, hierachy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) - - try: - # Find contour with maximum area - contour = max(contours, key=lambda x: cv2.contourArea(x)) - - # Create bounding rectangle around the contour - x, y, w, h = cv2.boundingRect(contour) - cv2.rectangle(crop_image, (x, y), (x + w, y + h), (0, 0, 255), 0) - - # Find convex hull - hull = cv2.convexHull(contour) - - # Draw contour - drawing = np.zeros(crop_image.shape, np.uint8) - cv2.drawContours(drawing, [contour], -1, (0, 255, 0), 0) - cv2.drawContours(drawing, [hull], -1, (0, 0, 255), 0) - - # Fi convexity defects - hull = cv2.convexHull(contour, returnPoints=False) - defects = cv2.convexityDefects(contour, hull) - - # Use cosine rule to find angle of the far point from the start and end point i.e. the convex points (the finger - # tips) for all defects - count_defects = 0 - - for i in range(defects.shape[0]): - s, e, f, d = defects[i, 0] - start = tuple(contour[s][0]) - end = tuple(contour[e][0]) - far = tuple(contour[f][0]) - - a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) - b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2) - c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2) - angle = (math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 180) / 3.14 - - # if angle >= 90 draw a circle at the far point - if angle <= 90: - count_defects += 1 - cv2.circle(crop_image, far, 1, [0, 0, 255], -1) - - cv2.line(crop_image, start, end, [0, 255, 0], 2) - - # Press SPACE if condition is match - - if count_defects >= 4: - pyautogui.press('space') - cv2.putText(frame, "JUMP", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) - - #PLAY RACING GAMES (WASD) - """ - if count_defects == 1: - pyautogui.press('w') - cv2.putText(frame, "W", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) - if count_defects == 2: - pyautogui.press('s') - cv2.putText(frame, "S", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) - if count_defects == 3: - pyautogui.press('aw') - cv2.putText(frame, "aw", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) - if count_defects == 4: - pyautogui.press('dw') - cv2.putText(frame, "dw", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) - if count_defects == 5: - pyautogui.press('s') - cv2.putText(frame, "s", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) - """ - - except: - pass - - # Show required images - cv2.imshow("Gesture", frame) - - # Close the camera if 'q' is pressed - if cv2.waitKey(1) == ord('q'): - break - -capture.release() -cv2.destroyAllWindows() - +""" +Playing Chrome's Dinosaur game using hand movements via OpenCV and Python. + +Packages Required +OpenCV (cv2) +numpy +math +pyautogui +Execution +Run the program and switch over to chrome and open chrome://dino Keep your hand within the rectangle as you start. Move your hand to make the dino jump. + +Tests and Controls +Change the HSV values to suit your lighting condtions. + +""" + +import numpy as np +import cv2 + +import math +import pyautogui + + +# Open Camera +capture = cv2.VideoCapture(0) + +while capture.isOpened(): + + # Capture frames from the camera + ret, frame = capture.read() + + # Get hand data from the rectangle sub window + cv2.rectangle(frame, (100, 100), (300, 300), (0, 255, 0), 0) + crop_image = frame[100:300, 100:300] + + # Apply Gaussian blur + blur = cv2.GaussianBlur(crop_image, (3, 3), 0) + + # Change color-space from BGR -> HSV + hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) + + # Create a binary image with where white will be skin colors and rest is black + mask2 = cv2.inRange(hsv, np.array([2, 0, 0]), np.array([20, 255, 255])) + + # Kernel for morphological transformation + kernel = np.ones((5, 5)) + + # Apply morphological transformations to filter out the background noise + dilation = cv2.dilate(mask2, kernel, iterations=1) + erosion = cv2.erode(dilation, kernel, iterations=1) + + # Apply Gaussian Blur and Threshold + filtered = cv2.GaussianBlur(erosion, (3, 3), 0) + ret, thresh = cv2.threshold(filtered, 127, 255, 0) +##### + # Find contours + #image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) + contours, hierachy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) + + try: + # Find contour with maximum area + contour = max(contours, key=lambda x: cv2.contourArea(x)) + + # Create bounding rectangle around the contour + x, y, w, h = cv2.boundingRect(contour) + cv2.rectangle(crop_image, (x, y), (x + w, y + h), (0, 0, 255), 0) + + # Find convex hull + hull = cv2.convexHull(contour) + + # Draw contour + drawing = np.zeros(crop_image.shape, np.uint8) + cv2.drawContours(drawing, [contour], -1, (0, 255, 0), 0) + cv2.drawContours(drawing, [hull], -1, (0, 0, 255), 0) + + # Fi convexity defects + hull = cv2.convexHull(contour, returnPoints=False) + defects = cv2.convexityDefects(contour, hull) + + # Use cosine rule to find angle of the far point from the start and end point i.e. the convex points (the finger + # tips) for all defects + count_defects = 0 + + for i in range(defects.shape[0]): + s, e, f, d = defects[i, 0] + start = tuple(contour[s][0]) + end = tuple(contour[e][0]) + far = tuple(contour[f][0]) + + a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) + b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2) + c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2) + angle = (math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 180) / 3.14 + + # if angle >= 90 draw a circle at the far point + if angle <= 90: + count_defects += 1 + cv2.circle(crop_image, far, 1, [0, 0, 255], -1) + + cv2.line(crop_image, start, end, [0, 255, 0], 2) + + # Press SPACE if condition is match + + if count_defects >= 4: + pyautogui.press('space') + cv2.putText(frame, "JUMP", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) + + #PLAY RACING GAMES (WASD) + """ + if count_defects == 1: + pyautogui.press('w') + cv2.putText(frame, "W", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) + if count_defects == 2: + pyautogui.press('s') + cv2.putText(frame, "S", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) + if count_defects == 3: + pyautogui.press('aw') + cv2.putText(frame, "aw", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) + if count_defects == 4: + pyautogui.press('dw') + cv2.putText(frame, "dw", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) + if count_defects == 5: + pyautogui.press('s') + cv2.putText(frame, "s", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2) + """ + + except: + pass + + # Show required images + cv2.imshow("Gesture", frame) + + # Close the camera if 'q' is pressed + if cv2.waitKey(1) == ord('q'): + break + +capture.release() +cv2.destroyAllWindows() + #try changing color code with your background \ No newline at end of file diff --git a/Python/Notepad.py b/Python/Notepad.py index 3a42f08..b55d026 100644 --- a/Python/Notepad.py +++ b/Python/Notepad.py @@ -1,186 +1,186 @@ -from tkinter import * -import os -from tkinter import messagebox as msg -import tkinter.filedialog as log - - -window = Tk() -window.geometry("600x400") -window.title("untitled - Notepad") -# window.wm_iconbitmap("Notepad.ico") - -# variables -menu_index = IntVar() -name = "" - - -# functions -def menu(event): - global menu_index - index = window.call(event.widget, "index", "active") - if index != "none": - menu_index.set(index) - - -def background(): - a = True - while a: - index = menu_index.get() - if index == 0: - note.configure(bg="White") - elif index == 1: - note.configure(bg="Blue") - elif index == 2: - note.configure(bg="Yellow") - elif index == 3: - note.configure(bg="Green") - elif index == 4: - note.configure(bg="Pink") - - window.wait_variable(menu_index) - background() - - -def new(): - global file - file = None - note.delete(1.0, END) - - -def opening(): - global file - global name - fil = log.askopenfilename(defaultextension=".txt", - filetypes=[("All files", "*.*"), ("Text Document", "*.txt")]) - - name = fil - if fil == "": - file = None - - else: - window.title(os.path.basename(fil) + " - Notepad") - note.delete(1.0, END) - with open(fil, "r") as f: - note.insert(1.0, f.read()) - - -def save_as(): - global file - file = log.asksaveasfilename(initialfile="Untitled.txt", - defaultextension=".txt", - filetypes=[("All Files", "*.*"), ("Text Document", "*.txt")]) - - if file == "": - file = None - else: - with open(file, "w") as f: - f.write(note.get(1.0, END)) - - window.title(os.path.basename(file) + " - Notepad") - msg.Message("File Saved") - - -def save(): - global name - try: - with open(name, "w") as f: - f.write(note.get(1.0, END)) - - window.title(os.path.basename(name) + " - Notepad") - print(name) - except: - save_as() - - -def cut(): - note.event_generate("<>") - - -def copy(): - note.event_generate("<>") - - -def paste(): - note.event_generate("<>") - - -def undo(): - note.edit_undo() - - -def redo(): - note.edit_redo() - - -def about(): - msg.showinfo("About Us", "We are a developer company from INDIA.\nMaking software for smoother life.") - - -def donate(): - msg.showinfo("Donate Us", "We are providing these types\n " - "of free software for you.\n " - "Would you like to buy a cup\n " - "of coffee for the developer.\n ThankYou") - - -# start of Menubar - -mainmenu = Menu(window) - -File = Menu(mainmenu, tearoff=0, activebackground="cyan") -File.add_cascade(label="New", command=new) -File.add_cascade(label="Open", command=opening) -File.add_cascade(label="Save", command=save) -File.add_cascade(label="Save As", command=save_as) -File.add_separator() -File.add_cascade(label="Quit", command=window.destroy) -mainmenu.add_cascade(label="File", menu=File) - -Edit = Menu(mainmenu, tearoff=0, activebackground="cyan") -Edit.add_cascade(label="Undo", command=undo) -Edit.add_cascade(label="Redo", command=redo) -Edit.add_separator() -Edit.add_cascade(label="Cut", command=cut) -Edit.add_cascade(label="Copy", command=copy) -Edit.add_cascade(label="Paste", command=paste) -mainmenu.add_cascade(label="Edit", menu=Edit) - -Font = Menu(mainmenu, tearoff=0, activebackground="cyan") -Font.add_command(label="White") -Font.add_command(label="Blue") -Font.add_command(label="Yellow") -Font.add_command(label="Green") -Font.add_command(label="Pink") -mainmenu.add_cascade(label="Font", menu=Font) - -Help = Menu(mainmenu, tearoff=0, activebackground="cyan") -Help.add_cascade(label="Help", command=help) -Help.add_cascade(label="About", command=about) -mainmenu.add_cascade(label="Help", menu=Help) - -# Donate -mainmenu.add_cascade(label="Donate Us", command=donate) - -Font.bind("<>", menu) -window.config(menu=mainmenu) - -# end of menubar - - -# start of textarea - -note = Text(window, undo=True) -file = None -note.pack(expand=True, fill=BOTH) - -# end of textarea - - -# scrollbar -scroll = Scrollbar(note) -scroll.pack(side=RIGHT, fill=Y) -scroll.config(command=note.yview) -note.config(yscrollcommand=scroll.set) - -background() -window.mainloop() +from tkinter import * +import os +from tkinter import messagebox as msg +import tkinter.filedialog as log + + +window = Tk() +window.geometry("600x400") +window.title("untitled - Notepad") +# window.wm_iconbitmap("Notepad.ico") + +# variables +menu_index = IntVar() +name = "" + + +# functions +def menu(event): + global menu_index + index = window.call(event.widget, "index", "active") + if index != "none": + menu_index.set(index) + + +def background(): + a = True + while a: + index = menu_index.get() + if index == 0: + note.configure(bg="White") + elif index == 1: + note.configure(bg="Blue") + elif index == 2: + note.configure(bg="Yellow") + elif index == 3: + note.configure(bg="Green") + elif index == 4: + note.configure(bg="Pink") + + window.wait_variable(menu_index) + background() + + +def new(): + global file + file = None + note.delete(1.0, END) + + +def opening(): + global file + global name + fil = log.askopenfilename(defaultextension=".txt", + filetypes=[("All files", "*.*"), ("Text Document", "*.txt")]) + + name = fil + if fil == "": + file = None + + else: + window.title(os.path.basename(fil) + " - Notepad") + note.delete(1.0, END) + with open(fil, "r") as f: + note.insert(1.0, f.read()) + + +def save_as(): + global file + file = log.asksaveasfilename(initialfile="Untitled.txt", + defaultextension=".txt", + filetypes=[("All Files", "*.*"), ("Text Document", "*.txt")]) + + if file == "": + file = None + else: + with open(file, "w") as f: + f.write(note.get(1.0, END)) + + window.title(os.path.basename(file) + " - Notepad") + msg.Message("File Saved") + + +def save(): + global name + try: + with open(name, "w") as f: + f.write(note.get(1.0, END)) + + window.title(os.path.basename(name) + " - Notepad") + print(name) + except: + save_as() + + +def cut(): + note.event_generate("<>") + + +def copy(): + note.event_generate("<>") + + +def paste(): + note.event_generate("<>") + + +def undo(): + note.edit_undo() + + +def redo(): + note.edit_redo() + + +def about(): + msg.showinfo("About Us", "We are a developer company from INDIA.\nMaking software for smoother life.") + + +def donate(): + msg.showinfo("Donate Us", "We are providing these types\n " + "of free software for you.\n " + "Would you like to buy a cup\n " + "of coffee for the developer.\n ThankYou") + + +# start of Menubar + +mainmenu = Menu(window) + +File = Menu(mainmenu, tearoff=0, activebackground="cyan") +File.add_cascade(label="New", command=new) +File.add_cascade(label="Open", command=opening) +File.add_cascade(label="Save", command=save) +File.add_cascade(label="Save As", command=save_as) +File.add_separator() +File.add_cascade(label="Quit", command=window.destroy) +mainmenu.add_cascade(label="File", menu=File) + +Edit = Menu(mainmenu, tearoff=0, activebackground="cyan") +Edit.add_cascade(label="Undo", command=undo) +Edit.add_cascade(label="Redo", command=redo) +Edit.add_separator() +Edit.add_cascade(label="Cut", command=cut) +Edit.add_cascade(label="Copy", command=copy) +Edit.add_cascade(label="Paste", command=paste) +mainmenu.add_cascade(label="Edit", menu=Edit) + +Font = Menu(mainmenu, tearoff=0, activebackground="cyan") +Font.add_command(label="White") +Font.add_command(label="Blue") +Font.add_command(label="Yellow") +Font.add_command(label="Green") +Font.add_command(label="Pink") +mainmenu.add_cascade(label="Font", menu=Font) + +Help = Menu(mainmenu, tearoff=0, activebackground="cyan") +Help.add_cascade(label="Help", command=help) +Help.add_cascade(label="About", command=about) +mainmenu.add_cascade(label="Help", menu=Help) + +# Donate +mainmenu.add_cascade(label="Donate Us", command=donate) + +Font.bind("<>", menu) +window.config(menu=mainmenu) + +# end of menubar + + +# start of textarea + +note = Text(window, undo=True) +file = None +note.pack(expand=True, fill=BOTH) + +# end of textarea + + +# scrollbar +scroll = Scrollbar(note) +scroll.pack(side=RIGHT, fill=Y) +scroll.config(command=note.yview) +note.config(yscrollcommand=scroll.set) + +background() +window.mainloop() diff --git a/Python/castle.py b/Python/castle.py index d973746..1c773cc 100644 --- a/Python/castle.py +++ b/Python/castle.py @@ -1,305 +1,305 @@ -from os import system -from random import randint - -gametitle = "Castle Dungeons- An interactive story game" - -system("mode 110,30") -system("Title"+gametitle) - - -def cls(): - system("cls") - - -character_name = None -character_class = None -character_race = None -character_strength = None -character_magic = None -character_dexterity = None -character_life = None - -cls() -print("Castle Dungeons- An interactive story fiction game in python") - - -def intro(): - print("") - print("In this story, you are the hero") - print("") - print("Your main goal is to protect and save your fellow friends from the evil socerer's prison") - print("") - print("Your princess is also held captive in his castle.") - print("") - print("Defeat the socerer and win your princess back to be the most powerful being in this mystic universe") - print("") - print("Your choices, skills and your luck will determine the outcome of the game") - print("") - print("So buckle up and get ready to fight for your life") - print("") - input("Press Enter to Start...") - - -intro() - - -def create_character(): - cls() - global character_name - character_name = input(""" - Lets begin the game by making your character, - What's the name of your hero? - - >""") - global character_race - while character_race is None: - race_choice = input(""" - Choose a race for your character: - 1. Human - 2. Elf - >""") - if race_choice == "1": - character_race = "Human" - elif race_choice == "2": - character_race = "Elf" - else: - print("Not a valid choice, please try again.") - - cls() - global character_class - while character_class is None: - class_choice = input(""" - Excellent choice. - You are """+character_race + """ - Now Time for you to choose your class: - 1. Warrior - 2. Magician - >""") - if class_choice == "1": - character_class = "Warrior" - elif class_choice == "2": - character_class = "Magician" - else: - print("Invalid Input, Please enter a Valid input") - - -create_character() - - -def create_character_skill_sheet(): - global character_name, character_race, character_class, character_dexterity, character_magic, character_life, character_strength - print(""" - Now let's determine your chatacter's skills, which you will use throughout the game. - In this game, your character has four skills: - - -Strength, which you will use in a combat - -Magic, which will help you cast spells - -Dexterity, which you will use in a ability test - -Life, which determines your life energy, points will be lost when hurt - and when the life becomes 0, the character dies. - - Depending upon your Race and Class, - you will have a certain point base already calculated automically. - - You will shortly be able to increase your skill points by rolling a 6-faced Dice. - - Here is your base character skill sheet:""") - character_strength = 5 - character_magic = 0 - character_dexterity = 3 - character_life = 10 - - if character_race == "Human": - character_strength = character_strength+3 - character_magic = character_magic+1 - character_dexterity = character_dexterity+5 - character_life = character_life+5 - elif character_race == "Dwarf": - character_strength = character_strength+1 - character_magic = character_magic+5 - character_dexterity = character_dexterity+3 - character_life = character_life+7 - if character_class == "Warrior": - character_strength = character_strength+10 - character_magic = character_magic+5 - character_life = character_life+10 - character_dexterity = character_dexterity+5 - elif character_class == "Magician": - character_strength = character_strength+5 - character_magic = character_magic+10 - character_life = character_life+5 - character_dexterity = character_dexterity+10 - print("Name: "+character_name) - print("Race: "+character_race) - print("Class: "+character_class) - print("Strength: "+str(character_strength)) - print("Magic: "+str(character_magic)) - print("Dexterity: "+str(character_dexterity)) - print("Life "+str(character_life)) - input("Press enter") - - -create_character_skill_sheet() - - -def modify_skills(): - cls() - global character_dexterity, character_strength, character_life - print("""To modify your skills, roll a 6-faced dice to determine the modified skill. - This is purely based on your luck - Let's see how lucky you are ;)""") - input("Press enter to roll for strength") - roll = randint(1, 6) - print("you rolled: "+str(roll)) - character_strength = character_strength+roll - input("Press enter to roll for dexterity") - roll = randint(1, 6) - print("you rolled: "+str(roll)) - character_dexterity = character_dexterity+roll - input("Press enter to roll for Life") - roll = randint(1, 6) - print("you rolled: "+str(roll)) - character_life = character_life+roll - input("Press enter to continue...") - cls() - print("Your updated skill sheet is:") - print("Name: "+character_name) - print("Race: "+character_race) - print("Class: "+character_class) - print("Strength: "+str(character_strength)) - print("Magic: "+str(character_magic)) - print("Dexterity: "+str(character_dexterity)) - print("Life "+str(character_life)) - print() - input("Press Enter to enter your adventure...") - - -modify_skills() - - -def scene_1(): - cls() - choice = None - while choice is None: - user_input = input(""" - You have entered the castle. - It is dark but thankfully your torch is lit and you can see upto 20ft from you. - The stone walls are damp and the smell of rats and orc is strong. - you walk down a narrow corridor, untill you reach a thick stone wall. - - The corridor continues on the left and on right. - - Its your choice now: - 1. Turn Left - 2. Turn Right - """) - if user_input == "1" or user_input == "turn left": - choice = "1" - scene_2() - elif user_input == "2" or user_input == "turn right": - choice = "2" - scene_3() - else: - print(""" - Not a valid choice, enter a number or enter - "turn left" or "turn right" to continue... """) - - -def scene_2(): - cls() - choice = None - while choice is None: - user_input = input(""" - From the darkness behind you, you hear a strange noise... - - What will you do? - 1. Continue walking - 2. Stop to listen - >""") - if user_input == "1" or user_input == "continue": - choice = "1" - combat() - elif user_input == "2" or user_input == "stop": - choice = "2" - skill_check() - else: - print("""Not a valid choice, please enter a number or enter - "continue" or "stop" """) - - -def scene_3(): - cls() - choice = None - while choice is None: - user_input = input(""" - From the darkness ahead of you, you hear a strange noise... - - What will you do? - 1. Continue walking - 2. Stop to listen - >""") - if user_input == "1" or user_input == "continue": - choice = "1" - combat() - elif user_input == "2" or user_input == "stop": - choice = "2" - skill_check() - else: - print(""" - Not a valid choice, please enter a number or enter - "continue" or "stop""") - - -def skill_check(): - cls() - print("""A giant rock falls from the ceiling. - Roll a die to see if You can dodge it... or you'll die from it - - The number you get from rolling the die added to your dexterity is greater than 15 than you'll survive. - OR - YOU WILL DIE!""") - input("Click enter to roll a die...") - roll = randint(1, 6) - print("you rolled "+str(roll)) - if roll+character_dexterity >= 15: - print("""You've survived the stone fall - BUT - the strange noise from the darkness is still here and danger is not over yet... - Prepare for next survival task...""") - print() - input("Press Enter to continue...") - combat() - else: - print( - "Sorry but you've failed to survive the stone fall and you are buried under it.") - print("GAME OVER!!") - input("Press enter to exit the game") - exit() - - -def combat(): - cls() - global character_life - print("A horrible orc attacks you out of no where...") - input("Press Enter to combat...") - orc = [15, 10] - while orc[1] > 0 or character_life > 0: - char_roll = randint(1, 6) - print("You rolled: " + str(char_roll)) - orc_roll = randint(1, 6) - print("The Orc rolled: " + str(orc_roll)) - if char_roll+character_strength >= orc_roll+orc[0]: - print("You've hit the Orc!!") - orc[1] = orc[1] - randint(1, 6) - else: - print("The Orc hits you!!") - character_life = character_life - randint(1, 6) - if character_life > 0: - print("You've defeated the Orc and won the game!!") - input("Press enter to exit the game") - else: - print("The Orc defeated you!!") - input("Press Enter to exit") - - -scene_1() +from os import system +from random import randint + +gametitle = "Castle Dungeons- An interactive story game" + +system("mode 110,30") +system("Title"+gametitle) + + +def cls(): + system("cls") + + +character_name = None +character_class = None +character_race = None +character_strength = None +character_magic = None +character_dexterity = None +character_life = None + +cls() +print("Castle Dungeons- An interactive story fiction game in python") + + +def intro(): + print("") + print("In this story, you are the hero") + print("") + print("Your main goal is to protect and save your fellow friends from the evil socerer's prison") + print("") + print("Your princess is also held captive in his castle.") + print("") + print("Defeat the socerer and win your princess back to be the most powerful being in this mystic universe") + print("") + print("Your choices, skills and your luck will determine the outcome of the game") + print("") + print("So buckle up and get ready to fight for your life") + print("") + input("Press Enter to Start...") + + +intro() + + +def create_character(): + cls() + global character_name + character_name = input(""" + Lets begin the game by making your character, + What's the name of your hero? + + >""") + global character_race + while character_race is None: + race_choice = input(""" + Choose a race for your character: + 1. Human + 2. Elf + >""") + if race_choice == "1": + character_race = "Human" + elif race_choice == "2": + character_race = "Elf" + else: + print("Not a valid choice, please try again.") + + cls() + global character_class + while character_class is None: + class_choice = input(""" + Excellent choice. + You are """+character_race + """ + Now Time for you to choose your class: + 1. Warrior + 2. Magician + >""") + if class_choice == "1": + character_class = "Warrior" + elif class_choice == "2": + character_class = "Magician" + else: + print("Invalid Input, Please enter a Valid input") + + +create_character() + + +def create_character_skill_sheet(): + global character_name, character_race, character_class, character_dexterity, character_magic, character_life, character_strength + print(""" + Now let's determine your chatacter's skills, which you will use throughout the game. + In this game, your character has four skills: + + -Strength, which you will use in a combat + -Magic, which will help you cast spells + -Dexterity, which you will use in a ability test + -Life, which determines your life energy, points will be lost when hurt + and when the life becomes 0, the character dies. + + Depending upon your Race and Class, + you will have a certain point base already calculated automically. + + You will shortly be able to increase your skill points by rolling a 6-faced Dice. + + Here is your base character skill sheet:""") + character_strength = 5 + character_magic = 0 + character_dexterity = 3 + character_life = 10 + + if character_race == "Human": + character_strength = character_strength+3 + character_magic = character_magic+1 + character_dexterity = character_dexterity+5 + character_life = character_life+5 + elif character_race == "Dwarf": + character_strength = character_strength+1 + character_magic = character_magic+5 + character_dexterity = character_dexterity+3 + character_life = character_life+7 + if character_class == "Warrior": + character_strength = character_strength+10 + character_magic = character_magic+5 + character_life = character_life+10 + character_dexterity = character_dexterity+5 + elif character_class == "Magician": + character_strength = character_strength+5 + character_magic = character_magic+10 + character_life = character_life+5 + character_dexterity = character_dexterity+10 + print("Name: "+character_name) + print("Race: "+character_race) + print("Class: "+character_class) + print("Strength: "+str(character_strength)) + print("Magic: "+str(character_magic)) + print("Dexterity: "+str(character_dexterity)) + print("Life "+str(character_life)) + input("Press enter") + + +create_character_skill_sheet() + + +def modify_skills(): + cls() + global character_dexterity, character_strength, character_life + print("""To modify your skills, roll a 6-faced dice to determine the modified skill. + This is purely based on your luck + Let's see how lucky you are ;)""") + input("Press enter to roll for strength") + roll = randint(1, 6) + print("you rolled: "+str(roll)) + character_strength = character_strength+roll + input("Press enter to roll for dexterity") + roll = randint(1, 6) + print("you rolled: "+str(roll)) + character_dexterity = character_dexterity+roll + input("Press enter to roll for Life") + roll = randint(1, 6) + print("you rolled: "+str(roll)) + character_life = character_life+roll + input("Press enter to continue...") + cls() + print("Your updated skill sheet is:") + print("Name: "+character_name) + print("Race: "+character_race) + print("Class: "+character_class) + print("Strength: "+str(character_strength)) + print("Magic: "+str(character_magic)) + print("Dexterity: "+str(character_dexterity)) + print("Life "+str(character_life)) + print() + input("Press Enter to enter your adventure...") + + +modify_skills() + + +def scene_1(): + cls() + choice = None + while choice is None: + user_input = input(""" + You have entered the castle. + It is dark but thankfully your torch is lit and you can see upto 20ft from you. + The stone walls are damp and the smell of rats and orc is strong. + you walk down a narrow corridor, untill you reach a thick stone wall. + + The corridor continues on the left and on right. + + Its your choice now: + 1. Turn Left + 2. Turn Right + """) + if user_input == "1" or user_input == "turn left": + choice = "1" + scene_2() + elif user_input == "2" or user_input == "turn right": + choice = "2" + scene_3() + else: + print(""" + Not a valid choice, enter a number or enter + "turn left" or "turn right" to continue... """) + + +def scene_2(): + cls() + choice = None + while choice is None: + user_input = input(""" + From the darkness behind you, you hear a strange noise... + + What will you do? + 1. Continue walking + 2. Stop to listen + >""") + if user_input == "1" or user_input == "continue": + choice = "1" + combat() + elif user_input == "2" or user_input == "stop": + choice = "2" + skill_check() + else: + print("""Not a valid choice, please enter a number or enter + "continue" or "stop" """) + + +def scene_3(): + cls() + choice = None + while choice is None: + user_input = input(""" + From the darkness ahead of you, you hear a strange noise... + + What will you do? + 1. Continue walking + 2. Stop to listen + >""") + if user_input == "1" or user_input == "continue": + choice = "1" + combat() + elif user_input == "2" or user_input == "stop": + choice = "2" + skill_check() + else: + print(""" + Not a valid choice, please enter a number or enter + "continue" or "stop""") + + +def skill_check(): + cls() + print("""A giant rock falls from the ceiling. + Roll a die to see if You can dodge it... or you'll die from it + + The number you get from rolling the die added to your dexterity is greater than 15 than you'll survive. + OR + YOU WILL DIE!""") + input("Click enter to roll a die...") + roll = randint(1, 6) + print("you rolled "+str(roll)) + if roll+character_dexterity >= 15: + print("""You've survived the stone fall + BUT + the strange noise from the darkness is still here and danger is not over yet... + Prepare for next survival task...""") + print() + input("Press Enter to continue...") + combat() + else: + print( + "Sorry but you've failed to survive the stone fall and you are buried under it.") + print("GAME OVER!!") + input("Press enter to exit the game") + exit() + + +def combat(): + cls() + global character_life + print("A horrible orc attacks you out of no where...") + input("Press Enter to combat...") + orc = [15, 10] + while orc[1] > 0 or character_life > 0: + char_roll = randint(1, 6) + print("You rolled: " + str(char_roll)) + orc_roll = randint(1, 6) + print("The Orc rolled: " + str(orc_roll)) + if char_roll+character_strength >= orc_roll+orc[0]: + print("You've hit the Orc!!") + orc[1] = orc[1] - randint(1, 6) + else: + print("The Orc hits you!!") + character_life = character_life - randint(1, 6) + if character_life > 0: + print("You've defeated the Orc and won the game!!") + input("Press enter to exit the game") + else: + print("The Orc defeated you!!") + input("Press Enter to exit") + + +scene_1() diff --git a/Python/invisible_cloak b/Python/invisible_cloak index a887f09..643e5da 100644 --- a/Python/invisible_cloak +++ b/Python/invisible_cloak @@ -1,79 +1,79 @@ -import cv2 -import time -import numpy as np - -## Preparation for writing the ouput video -fourcc = cv2.VideoWriter_fourcc(*'XVID') -out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) - -##reading from the webcam -cap = cv2.VideoCapture(0) - -## Allow the system to sleep for 3 seconds before the webcam starts -time.sleep(3) -count = 0 -background = 0 - -## Capture the background in range of 60 -for i in range(60): - ret, background = cap.read() -background = np.flip(background, axis=1) - -## Read every frame from the webcam, until the camera is open -while (cap.isOpened()): - ret, img = cap.read() - if not ret: - break - count += 1 - img = np.flip(img, axis=1) - - ## Convert the color space from BGR to HSV - hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) - - ## Generat masks to detect red color - lower_red = np.array([0, 120, 50]) - upper_red = np.array([10, 255,255]) - mask1 = cv2.inRange(hsv, lower_red, upper_red) - - lower_red = np.array([170, 120, 70]) - upper_red = np.array([180, 255, 255]) - mask2 = cv2.inRange(hsv, lower_red, upper_red) - - mask1 = mask1 + mask2 - - ## Open and Dilate the mask image - mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) - mask1 = cv2.morphologyEx(mask1, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8)) - - ## Create an inverted mask to segment out the red color from the frame - mask2 = cv2.bitwise_not(mask1) - - ## Segment the red color part out of the frame using bitwise and with the inverted mask - res1 = cv2.bitwise_and(img, img, mask=mask2) - - ## Create image showing static background frame pixels only for the masked region - res2 = cv2.bitwise_and(background, background, mask=mask1) - - ## Generating the final output and writing - finalOutput = cv2.addWeighted(res1, 1, res2, 1, 0) - out.write(finalOutput) - cv2.imshow("magic", finalOutput) - cv2.waitKey(1) - - -cap.release() -out.release() -cv2.destroyAllWindows() - -#------------------------------ -#colors code - -#skin color -#lower_red = np.array([0, 0, 60]) -#upper_red = np.array([100, 250,250]) -# mask1 = cv2.inRange(hsv, lower_red, upper_red) - -# lower_red = np.array([170, 120, 70]) -# upper_red = np.array([180, 255, 255]) - -#------------------------------- +import cv2 +import time +import numpy as np + +## Preparation for writing the ouput video +fourcc = cv2.VideoWriter_fourcc(*'XVID') +out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) + +##reading from the webcam +cap = cv2.VideoCapture(0) + +## Allow the system to sleep for 3 seconds before the webcam starts +time.sleep(3) +count = 0 +background = 0 + +## Capture the background in range of 60 +for i in range(60): + ret, background = cap.read() +background = np.flip(background, axis=1) + +## Read every frame from the webcam, until the camera is open +while (cap.isOpened()): + ret, img = cap.read() + if not ret: + break + count += 1 + img = np.flip(img, axis=1) + + ## Convert the color space from BGR to HSV + hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) + + ## Generat masks to detect red color + lower_red = np.array([0, 120, 50]) + upper_red = np.array([10, 255,255]) + mask1 = cv2.inRange(hsv, lower_red, upper_red) + + lower_red = np.array([170, 120, 70]) + upper_red = np.array([180, 255, 255]) + mask2 = cv2.inRange(hsv, lower_red, upper_red) + + mask1 = mask1 + mask2 + + ## Open and Dilate the mask image + mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) + mask1 = cv2.morphologyEx(mask1, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8)) + + ## Create an inverted mask to segment out the red color from the frame + mask2 = cv2.bitwise_not(mask1) + + ## Segment the red color part out of the frame using bitwise and with the inverted mask + res1 = cv2.bitwise_and(img, img, mask=mask2) + + ## Create image showing static background frame pixels only for the masked region + res2 = cv2.bitwise_and(background, background, mask=mask1) + + ## Generating the final output and writing + finalOutput = cv2.addWeighted(res1, 1, res2, 1, 0) + out.write(finalOutput) + cv2.imshow("magic", finalOutput) + cv2.waitKey(1) + + +cap.release() +out.release() +cv2.destroyAllWindows() + +#------------------------------ +#colors code + +#skin color +#lower_red = np.array([0, 0, 60]) +#upper_red = np.array([100, 250,250]) +# mask1 = cv2.inRange(hsv, lower_red, upper_red) + +# lower_red = np.array([170, 120, 70]) +# upper_red = np.array([180, 255, 255]) + +#------------------------------- diff --git a/Suduko Solver/README.md b/Suduko Solver/README.md index dcd2ff1..228ee62 100644 --- a/Suduko Solver/README.md +++ b/Suduko Solver/README.md @@ -1,31 +1,31 @@ -### Problem Description - -A program to solve a Sudoku puzzle by filling the empty cells. -Empty cells are indicated by the character '.' - -### Example -#### Input: - -5 3 . . 7 . . . . -6 . . 1 9 5 . . . -. 9 8 . . . . 6 . -8 . . . 6 . . . 3 -4 . . 8 . 3 . . 1 -7 . . . 2 . . . 6 -. 6 . . . . 2 8 . -. . . 4 1 9 . . 5 -. . . . 8 . . 7 9 - -#### Output: -5 3 4 6 7 8 9 1 2 -6 7 2 1 9 5 3 4 8 -1 9 8 3 4 2 5 6 7 -8 5 9 7 6 1 4 2 3 -4 2 6 8 5 3 7 9 1 -7 1 3 9 2 4 8 5 6 -9 6 1 5 3 7 2 8 4 -2 8 7 4 1 9 6 3 5 -3 4 5 2 8 6 1 7 9 - -##### Contributed by -[Priyanshu Gangwar](https://github.com/PriyanshuGangwar) +### Problem Description + +A program to solve a Sudoku puzzle by filling the empty cells. +Empty cells are indicated by the character '.' + +### Example +#### Input: + +5 3 . . 7 . . . . +6 . . 1 9 5 . . . +. 9 8 . . . . 6 . +8 . . . 6 . . . 3 +4 . . 8 . 3 . . 1 +7 . . . 2 . . . 6 +. 6 . . . . 2 8 . +. . . 4 1 9 . . 5 +. . . . 8 . . 7 9 + +#### Output: +5 3 4 6 7 8 9 1 2 +6 7 2 1 9 5 3 4 8 +1 9 8 3 4 2 5 6 7 +8 5 9 7 6 1 4 2 3 +4 2 6 8 5 3 7 9 1 +7 1 3 9 2 4 8 5 6 +9 6 1 5 3 7 2 8 4 +2 8 7 4 1 9 6 3 5 +3 4 5 2 8 6 1 7 9 + +##### Contributed by +[Priyanshu Gangwar](https://github.com/PriyanshuGangwar) diff --git a/TIC TAC TOE USING PYTHON/tictactoe.py b/TIC TAC TOE USING PYTHON/tictactoe.py index 938c640..51610c8 100644 --- a/TIC TAC TOE USING PYTHON/tictactoe.py +++ b/TIC TAC TOE USING PYTHON/tictactoe.py @@ -1,82 +1,82 @@ -def tic_tac_toe(): - board = ["_", "_", "_", "_", "_", "_", "_", "_", "_"] - end = False - win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) - - def draw(): - print(board[0], board[1], board[2]) - print(board[3], board[4], board[5]) - print(board[6], board[7], board[8]) - print() - - def player1(): - n = choose_number() - if board[n] == "X" or board[n] == "O": - print("\nYou can't go there. Try again") - player1() - else: - board[n] = "X" - - def player2(): - n = choose_number() - if board[n] == "X" or board[n] == "O": - print("\nYou can't go there. Try again") - player2() - else: - board[n] = "O" - - def choose_number(): - while True: - while True: - a = input() - try: - a = int(a) - a -= 1 - if a in range(0, 9): - return a - else: - print("\nThat's not on the board. Try again") - continue - except ValueError: - print("\nThat's not a number. Try again") - continue - - def check_board(): - count = 0 - for a in win_commbinations: - if board[a[0]] == board[a[1]] == board[a[2]] == "X": - print("Player 1 Wins!\n") - print("Congratulations!\n") - return True - - if board[a[0]] == board[a[1]] == board[a[2]] == "O": - print("Player 2 Wins!\n") - print("Congratulations!\n") - return True - for a in range(9): - if board[a] == "X" or board[a] == "O": - count += 1 - if count == 9: - print("The game ends in a Tie\n") - return True - - while not end: - draw() - end = check_board() - if end == True: - break - print("Player 1 choose where to place a cross") - player1() - print() - draw() - end = check_board() - if end == True: - break - print("Player 2 choose where to place a nought") - player2() - print() - - if input("Play again (y/n)\n") == "y": - tic_tac_toe() - +def tic_tac_toe(): + board = ["_", "_", "_", "_", "_", "_", "_", "_", "_"] + end = False + win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) + + def draw(): + print(board[0], board[1], board[2]) + print(board[3], board[4], board[5]) + print(board[6], board[7], board[8]) + print() + + def player1(): + n = choose_number() + if board[n] == "X" or board[n] == "O": + print("\nYou can't go there. Try again") + player1() + else: + board[n] = "X" + + def player2(): + n = choose_number() + if board[n] == "X" or board[n] == "O": + print("\nYou can't go there. Try again") + player2() + else: + board[n] = "O" + + def choose_number(): + while True: + while True: + a = input() + try: + a = int(a) + a -= 1 + if a in range(0, 9): + return a + else: + print("\nThat's not on the board. Try again") + continue + except ValueError: + print("\nThat's not a number. Try again") + continue + + def check_board(): + count = 0 + for a in win_commbinations: + if board[a[0]] == board[a[1]] == board[a[2]] == "X": + print("Player 1 Wins!\n") + print("Congratulations!\n") + return True + + if board[a[0]] == board[a[1]] == board[a[2]] == "O": + print("Player 2 Wins!\n") + print("Congratulations!\n") + return True + for a in range(9): + if board[a] == "X" or board[a] == "O": + count += 1 + if count == 9: + print("The game ends in a Tie\n") + return True + + while not end: + draw() + end = check_board() + if end == True: + break + print("Player 1 choose where to place a cross") + player1() + print() + draw() + end = check_board() + if end == True: + break + print("Player 2 choose where to place a nought") + player2() + print() + + if input("Play again (y/n)\n") == "y": + tic_tac_toe() + tic_tac_toe() \ No newline at end of file diff --git a/Websites/Contactme.html b/Websites/Contactme.html index 170e657..58750b5 100644 --- a/Websites/Contactme.html +++ b/Websites/Contactme.html @@ -1,181 +1,181 @@ - - - - - - - - - - -
-

Hi there!

-

Feel free to contact me

-
-
-
- -
-
- -
-
- -
-
-
-
- -
-
- -
-
-
-
- -
-
- - -
-
-
-
- -
- -
- -
-
- -
-
- -
-
- -
- -
-
- -
-
- -
-
- - - -
-
- -
-
- -
-
-
-
- -
-
- -
-
-
- -
- -
- - - + + + + + + + + + + +
+

Hi there!

+

Feel free to contact me

+
+
+
+ +
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ + +
+
+
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+ +
+ +
+
+ +
+
+ +
+
+ + + +
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+ +
+ +
+ + + \ No newline at end of file From b3b803ad9c4ef572554446fb4ae0e1587c9e7c99 Mon Sep 17 00:00:00 2001 From: NavyaIyanampudi <68003146+NavyaIyanampudi@users.noreply.github.com> Date: Tue, 20 Oct 2020 11:32:40 +0530 Subject: [PATCH 2/2] Update Binarysearch.cpp --- Data Structures/Searching algorithms/Binarysearch.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Data Structures/Searching algorithms/Binarysearch.cpp b/Data Structures/Searching algorithms/Binarysearch.cpp index db9ef32..ac6255c 100644 --- a/Data Structures/Searching algorithms/Binarysearch.cpp +++ b/Data Structures/Searching algorithms/Binarysearch.cpp @@ -23,3 +23,4 @@ int main(void) { cout<< num <<" is present at index "<< index <<" in the array"; return 0; } +O/p:is present at index 1 in the array