diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..6506be174 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve. Report bugs found while using the project +title: "[BUG]" +labels: bug +assignees: '' + +--- + + + +## Description + + +## Expected Behavior + + +## Actual Behavior + + +## Possible Fix + + +## Steps to Reproduce + + +1. +2. +3. +4. + +## Context + diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..2d1696261 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest features, propose improvements, discuss new ideas. +title: "[FEATURE]" +labels: enhancement +assignees: '' + +--- + + + +## Detailed Description + + +## Context + + + +## Possible Implementation + diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..efaaf3765 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,21 @@ +#### Description of Change + + +#### Checklist + + +- [ ] Added description of change +- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#New-File-Name-guidelines) +- [ ] Added tests and example, test must pass +- [ ] Relevant documentation/comments is changed or added +- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#Commit-Guidelines) +- [ ] Search previous suggestions before making a new one, as yours may be a duplicate. +- [ ] Sort by alphabetical order +- [ ] I acknowledge that all my contributions will be made under the project's license. + +Notes: \ No newline at end of file diff --git a/.github/workflows/cpplint.yml b/.github/workflows/cpplint.yml new file mode 100644 index 000000000..a6999e1f2 --- /dev/null +++ b/.github/workflows/cpplint.yml @@ -0,0 +1,13 @@ +name: cpplint +on: [push, pull_request] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-python@v1 + - run: pip install cpplint + # - run: cpplint --filter= # print out all cpplint rules + - run: cpplint --recursive . || true # all issues to be fixed + # TODO: Remove each filter one at a time and fix those failures + - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml new file mode 100644 index 000000000..07a32ece9 --- /dev/null +++ b/.github/workflows/cpplint_modified_files.yml @@ -0,0 +1,64 @@ +# GitHub Action that enables a repo to achieve gradual compliance with cpplint by +# linting only those files that have been added or modified (vs. origin/master). +# 1. runs cpplint only on those files that have been modified vs. origin/master. +# 2. compiles with g++ only those files that have been modified vs. origin/master. +# 3. other optional filepath verifications may be commented out at the end of this file. +# From: https://github.com/cpplint/GitHub-Action-for-cpplint + +name: cpplint_modified_files +on: [push, pull_request] +jobs: + cpplint_modified_files: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 # v2 is broken for git diff + - uses: actions/setup-python@v1 + - run: python -m pip install cpplint + - run: git remote -v + - run: git branch + - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - name: cpplint_modified_files + shell: python + run: | + import os + import subprocess + import sys + + print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 + with open("git_diff.txt") as in_file: + modified_files = sorted(in_file.read().splitlines()) + print("{} files were modified.".format(len(modified_files))) + + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] + print(f"{len(cpp_files)} C++ files were modified.") + if not cpp_files: + sys.exit(0) + + print("cpplint:") + subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_files, check=True, text=True) + + print("g++:") + # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) + # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] + subprocess.run(["g++"] + cpp_files, check=True, text=True) + + upper_files = [file for file in cpp_files if file != file.lower()] + if upper_files: + print(f"{len(upper_files)} files contain uppercase characters:") + print("\n".join(upper_files) + "\n") + + space_files = [file for file in cpp_files if " " in file or "-" in file] + if space_files: + print(f"{len(space_files)} files contain space or dash characters:") + print("\n".join(space_files) + "\n") + + nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] + if nodir_files: + print(f"{len(nodir_files)} files are not in one and only one directory:") + print("\n".join(nodir_files) + "\n") + + bad_files = len(upper_files + space_files + nodir_files) + if bad_files: + sys.exit(bad_files) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml new file mode 100644 index 000000000..1d63374b0 --- /dev/null +++ b/.github/workflows/update_directory_md.yml @@ -0,0 +1,68 @@ +# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push +name: update_directory_md +on: [push] +jobs: + update_directory_md: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v1 + - name: update_directory_md + shell: python + run: | + import os + from typing import Iterator + + URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" + g_output = [] + + + def good_filepaths(top_dir: str = ".") -> Iterator[str]: + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() in cpp_exts: + yield os.path.join(dirpath, filename).lstrip("./") + + + def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + + def print_path(old_path: str, new_path: str) -> str: + global g_output + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + + def build_directory_md(top_dir: str = ".") -> str: + global g_output + old_path = "" + for filepath in sorted(good_filepaths(), key=str.lower): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + g_output.append(f"{md_prefix(indent)} [{filename}]({url})") + return "\n".join(g_output) + + + with open("DIRECTORY.md", "w") as out_file: + out_file.write(build_directory_md(".") + "\n") + + - name: Update DIRECTORY.md + run: | + cat DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..1a5f7b618 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +.DS_Store + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..8b117a5fd --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,67 @@ +{ + "files.associations": { + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "codecvt": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "csetjmp": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cuchar": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "forward_list": "cpp", + "list": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "vector": "cpp", + "exception": "cpp", + "fstream": "cpp", + "functional": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "memory": "cpp", + "mutex": "cpp", + "new": "cpp", + "numeric": "cpp", + "optional": "cpp", + "ostream": "cpp", + "ratio": "cpp", + "scoped_allocator": "cpp", + "shared_mutex": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "thread": "cpp", + "type_traits": "cpp", + "tuple": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "utility": "cpp", + "valarray": "cpp", + "algorithm": "cpp" + } +} \ No newline at end of file diff --git a/Backtracking/Rat_maze.cpp b/Backtracking/Rat_maze.cpp deleted file mode 100644 index db50c5e2a..000000000 --- a/Backtracking/Rat_maze.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - A Maze is given as N*N binary matrix of blocks where source block is the upper - left most block i.e., maze[0][0] and destination block is lower rightmost - block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. - The rat can move only in two directions: forward and down. In the maze matrix, - 0 means the block is dead end and 1 means the block can be used in the path - from source to destination. -*/ -#include -#define size 4 - -using namespace std; - -int solveMaze(int currposrow,int currposcol,int maze[size][size],int soln[size][size]) -{ - if((currposrow==size-1) && (currposcol==size-1)) - { - soln[currposrow][currposcol]=1; - for(int i=0;i -using namespace std; -///N=9; -int n=9; - - -bool isPossible(int mat[][9],int i,int j,int no){ - ///Row or col nahin hona chahiye - for(int x=0;x -#include -#include - -float eq(float i) -{ - return (pow(i,3)-(4*i)-9); // original equation -} - -void main() -{ - float a,b,x,z; - clrscr(); - for(int i=0;i<100;i++) - { - z=eq(i); - if(z>=0) - { - b=i; - a=--i; - goto START; - } - } - - START: - - cout<<"\nFirst initial: "< 0 && z<0.0009) // stoping criteria - { - goto END; - } - } - - END: - cout<<"\n\nRoot: "< -using namespace std; - -int main() -{ - int mat_size,i,j,step; - - cout<<"Matrix size: "; - cin>>mat_size; - - double mat[mat_size+1][mat_size+1], x[mat_size][mat_size+1]; - - cout<>mat[i][j]; //Enter (mat_size*mat_size) value of the matrix. - } - } - - for(step=0;step=0;i--) - { - double sum = 0; - for(j=mat_size-1;j>i;j--) - { - x[i][j] = x[j][j] * x[i][j]; - sum = x[i][j] + sum; - } - if(x[i][i]==0) - x[i][i] = 0; - else - x[i][i] = (x[i][mat_size] - sum)/(x[i][i]); - - cout<<"x"< -#include -#include - -float eq(float i) -{ - return (pow(i,3)-(4*i)-9); // original equation -} -float eq_der(float i) -{ - return ((3*pow(i,2))-4); // derivative of equation -} - -void main() -{ - float a,b,z,c,m,n; - clrscr(); - for(int i=0;i<100;i++) - { - z=eq(i); - if(z>=0) - { - b=i; - a=--i; - goto START; - } - } - - START: - - cout<<"\nFirst initial: "< 0 && m<0.009) // stoping criteria - { - goto END; - } - } - - END: - cout<<"\n\nRoot: "< -#include -#include - -float eq(float i) -{ - return (pow(i,3)-(4*i)-9); // original equation -} - -void main() -{ - float a,b,z,c,m,n; - clrscr(); - for(int i=0;i<100;i++) - { - z=eq(i); - if(z>=0) - { - b=i; - a=--i; - goto START; - } - } - - START: - - cout<<"\nFirst initial: "< 0 && z<0.09) // stoping criteria - { - goto END; - } - } - - END: - cout<<"\n\nRoot: "< -#include -#include - -float eq(float i) -{ - return (pow(i,3)-(4*i)-9); // origial equation -} - -void main() -{ - float a,b,z,c,m,n; - clrscr(); - for(int i=0;i<100;i++) - { - z=eq(i); - if(z>=0) - { - b=i; - a=--i; - goto START; - } - } - - START: - - cout<<"\nFirst initial: "< 0 && z<0.09) // stoping criteria - { - goto END; - } - } - - END: - cout<<"\n\nRoot: "< -#include -#include -float eq(float y) -{ - return((3*y)-(cos(y))-2); -} -float eqd(float y) -{ - return((0.5)*((cos(y))+2)); -} - -void main() -{ - float y,x1,x2,x3,sum,s,a,f1,f2,gd; - int i,n; - - clrscr(); - for(i=0;i<10;i++) - { - sum=eq(y); - cout<<"value of equation at "<"; - cin>>x1; - cout<<"enter the no iteration to perform->\n"; - cin>>n; - - for(i=0;i<=n;i++) - { - x2=eqd(x1); - cout<<"\nenter the x2->"< -using namespace std; - - -struct node -{ - int val; - node *left; - node *right; -}; - -struct queue -{ - node *t[100]; - int front; - int rear; -}; - -queue q; - - -void enqueue(node *n) -{ - q.t[q.rear++]=n; -} - -node * dequeue() -{ - return (q.t[q.front++]); -} - - - -void Insert(node *n, int x) -{ - if (xval) - { - if (n->left==NULL) - { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; - } - else - { - Insert(n->left, x); - } - } - else - { - if (n->right==NULL) - { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; - } - else - { - Insert(n->right, x); - } - } -} - - - - -int findMaxInLeftST(node *n) -{ - while(n->right!=NULL) - { - n=n->right; - } - return n->val; -} - -void Remove(node *p, node *n, int x) -{ - if (n->val==x) - { - if (n->right==NULL && n->left==NULL) - { - if (xval) - { - p->right=NULL; - } - else - { - p->left=NULL; - } - } - else if (n->right==NULL) - { - if (xval) - { - p->right=n->left; - } - else - { - p->left=n->left; - } - } - else if (n->left==NULL) - { - if (xval) - { - p->right=n->right; - } - else - { - p->left=n->right; - } - } - else - { - int y=findMaxInLeftST(n->left); - n->val=y; - Remove(n, n->right, y); - } - } - else if (xval) - { - Remove(n, n->left, x); - } - else - { - Remove(n, n->right, x); - } -} - - - - -void BFT(node *n) -{ - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } -} - -void Pre(node *n) -{ - if (n!=NULL) - { - cout<val<<" "; - Pre(n->left); - Pre(n->right); - } -} - -void In(node *n) -{ - if (n!=NULL) - { - In(n->left); - cout<val<<" "; - In(n->right); - } -} - - -void Post(node *n) -{ - if (n!=NULL) - { - Post(n->left); - Post(n->right); - cout<val<<" "; - } -} - - - -int main() -{ - q.front=0; - q.rear=0; - int value; - int ch; - node *root=new node; - cout<<"\nEnter the value of root node :"; - cin>>value; - root->val=value; - root->left=NULL; - root->right=NULL; - do - { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Breadth First"; - cout<<"\n4. Preorder Depth First"; - cout<<"\n5. Inorder Depth First"; - cout<<"\n6. Postorder Depth First"; - - cout<<"\nEnter Your Choice : "; - cin>>ch; - int x; - switch(ch) - { - case 1: - cout<<"\nEnter the value to be Inserted : "; - cin>>x; - Insert(root, x); - break; - case 2: - cout<<"\nEnter the value to be Deleted : "; - cin>>x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; - } - } - while(ch!=0); -} diff --git a/Data Structure/Binaryheap.cpp b/Data Structure/Binaryheap.cpp deleted file mode 100644 index 92bcb275a..000000000 --- a/Data Structure/Binaryheap.cpp +++ /dev/null @@ -1,159 +0,0 @@ -// A C++ program to demonstrate common Binary Heap Operations -#include -#include -using namespace std; - -// Prototype of a utility function to swap two integers -void swap(int *x, int *y); - -// A class for Min Heap -class MinHeap -{ - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap -public: - // Constructor - MinHeap(int capacity); - - // to heapify a subtree with the root at given index - void MinHeapify(int ); - - int parent(int i) { return (i-1)/2; } - - // to get index of left child of node at index i - int left(int i) { return (2*i + 1); } - - // to get index of right child of node at index i - int right(int i) { return (2*i + 2); } - - // to extract the root which is the minimum element - int extractMin(); - - // Decreases key value of key at index i to new_val - void decreaseKey(int i, int new_val); - - // Returns the minimum key (key at root) from min heap - int getMin() { return harr[0]; } - - // Deletes a key stored at index i - void deleteKey(int i); - - // Inserts a new key 'k' - void insertKey(int k); -}; - -// Constructor: Builds a heap from a given array a[] of given size -MinHeap::MinHeap(int cap) -{ - heap_size = 0; - capacity = cap; - harr = new int[cap]; -} - -// Inserts a new key 'k' -void MinHeap::insertKey(int k) -{ - if (heap_size == capacity) - { - cout << "\nOverflow: Could not insertKey\n"; - return; - } - - // First insert the new key at the end - heap_size++; - int i = heap_size - 1; - harr[i] = k; - - // Fix the min heap property if it is violated - while (i != 0 && harr[parent(i)] > harr[i]) - { - swap(&harr[i], &harr[parent(i)]); - i = parent(i); - } -} - -// Decreases value of key at index 'i' to new_val. It is assumed that -// new_val is smaller than harr[i]. -void MinHeap::decreaseKey(int i, int new_val) -{ - harr[i] = new_val; - while (i != 0 && harr[parent(i)] > harr[i]) - { - swap(&harr[i], &harr[parent(i)]); - i = parent(i); - } -} - -// Method to remove minimum element (or root) from min heap -int MinHeap::extractMin() -{ - if (heap_size <= 0) - return INT_MAX; - if (heap_size == 1) - { - heap_size--; - return harr[0]; - } - - // Store the minimum value, and remove it from heap - int root = harr[0]; - harr[0] = harr[heap_size-1]; - heap_size--; - MinHeapify(0); - - return root; -} - - -// This function deletes key at index i. It first reduced value to minus -// infinite, then calls extractMin() -void MinHeap::deleteKey(int i) -{ - decreaseKey(i, INT_MIN); - extractMin(); -} - -// A recursive method to heapify a subtree with the root at given index -// This method assumes that the subtrees are already heapified -void MinHeap::MinHeapify(int i) -{ - int l = left(i); - int r = right(i); - int smallest = i; - if (l < heap_size && harr[l] < harr[i]) - smallest = l; - if (r < heap_size && harr[r] < harr[smallest]) - smallest = r; - if (smallest != i) - { - swap(&harr[i], &harr[smallest]); - MinHeapify(smallest); - } -} - -// A utility function to swap two elements -void swap(int *x, int *y) -{ - int temp = *x; - *x = *y; - *y = temp; -} - -// Driver program to test above functions -int main() -{ - MinHeap h(11); - h.insertKey(3); - h.insertKey(2); - h.deleteKey(1); - h.insertKey(15); - h.insertKey(5); - h.insertKey(4); - h.insertKey(45); - cout << h.extractMin() << " "; - cout << h.getMin() << " "; - h.decreaseKey(2, 1); - cout << h.getMin(); - return 0; -} diff --git a/Data Structure/Doubly Linked List.cpp b/Data Structure/Doubly Linked List.cpp deleted file mode 100644 index db550d422..000000000 --- a/Data Structure/Doubly Linked List.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *prev; - node *next; -}; - -node *start; - -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - node *n= new node; - t->next=n; - n->prev=t; - n->val=x; - n->next=NULL; - } - else - { - node *n= new node; - n->val=x; - n->prev=NULL; - n->next=NULL; - start=n; - } -} - -void remove(int x) -{ - node *t=start; - while(t->val!=x) - { - t=t->next; - } - t->prev->next=t->next; - t->next->prev=t->prev; - delete t; -} - -void search(int x) -{ - node *t= start; - int found =0; - while(t!=NULL) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } -} - -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - -} - -void reverseShow() -{ - node *t=start; - while(t->next!=NULL) - { - t=t->next; - } - while(t!=NULL) - { - cout<val<<"\t"; - t=t->prev; - } -} - -int main() -{ - int choice, x; - do - { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Forward print"; - cout<<"\n5. Reverse print"; - cout<<"\n\nEnter you choice : "; - cin>>choice; - switch (choice) - { - case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x;; - insert(x); break; - case 2 : cout<<"\nEnter the element to be removed : "; - cin>>x; - remove(x); break; - case 3 : cout<<"\nEnter the element to be searched : "; - cin>>x; - search(x); break; - case 4 : show(); break; - case 5 : reverseShow(); break; - } - } - while(choice!=0); - - return 0; -} diff --git a/Data Structure/Linked List.cpp b/Data Structure/Linked List.cpp deleted file mode 100644 index 5abebd584..000000000 --- a/Data Structure/Linked List.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *start; - -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - node *n= new node; - t->next=n; - n->val=x; - n->next=NULL; - } - else - { - node *n= new node; - n->val=x; - n->next=NULL; - start=n; - } -} - -void remove(int x){ - - if( start == NULL ){ - cout<<"\nLinked List is empty\n"; - return ; - } - else if( start->val == x ){ - node *temp = start; - start = start->next; - delete temp; - return ; - } - - node *temp = start, *parent = start; - - while( temp != NULL && temp->val != x ){ - parent = temp; - temp = temp->next; - } - - if( temp == NULL ){ - cout <next = temp->next; - delete temp; -} - -void search(int x) -{ - node *t= start; - int found =0; - while(t!=NULL) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } -} - -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - -} - -int main() -{ - int choice, x; - do - { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Print"; - cout<<"\n0. Exit"; - cout<<"\n\nEnter you choice : "; - cin>>choice; - switch (choice) - { - case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x;; - insert(x); break; - case 2 : cout<<"\nEnter the element to be removed : "; - cin>>x; - remove(x); break; - case 3 : cout<<"\nEnter the element to be searched : "; - cin>>x; - search(x); break; - case 4 : show(); - cout<<"\n"; break; - } - } - while(choice!=0); - - return 0; -} diff --git a/Data Structure/List Array.cpp b/Data Structure/List Array.cpp deleted file mode 100644 index 21f5c6ae5..000000000 --- a/Data Structure/List Array.cpp +++ /dev/null @@ -1,185 +0,0 @@ -#include -using namespace std; - -struct list -{ - int data[50]; - int top=0; - bool isSorted=false; - - int BinarySearch(int *array, int first, int last, int x) - { - if(lastarray[mid]) - return (BinarySearch(array, mid+1, last, x)); - } - - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i]==x) - { - return i; - } - } - - return -1; - } - - int Search(int x) - { - int pos=-1; - - if (isSorted) - { - pos=BinarySearch(data, 0, top-1, x); - } - - else - { - pos=LinarSearch(data, x); - } - - if (pos!=-1) - { - cout<<"\nElement found at position : "< pos; i--) - { - data[i]=data[i-1]; - } - top++; - data[pos]=x; - } - } - - void Remove(int x) - { - int pos=Search(x); - cout<<"\n"<>choice; - switch (choice) - { - case 1: cout<<"\nEnter the element to be inserted : "; - cin>>x; - L.insert(x); - break; - case 2: cout<<"\nEnter the element to be removed : "; - cin>>x; - L.Remove(x); - break; - case 3: cout<<"\nEnter the element to be searched : "; - cin>>x; - L.Search(x); - break; - case 4: L.Sort(); - break; - case 5: L.Show(); - break; - } - } - while(choice!=0); - return 0; -} diff --git a/Data Structure/Queue Using Array.cpp b/Data Structure/Queue Using Array.cpp deleted file mode 100644 index 7b5816f84..000000000 --- a/Data Structure/Queue Using Array.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include -using namespace std; - -int queue[10]; -int front=0; -int rear=0; - -void Enque(int x) -{ - if(rear==10) - { - cout<<"\nOverflow"; - } - else - { - queue[rear++]=x; - } -} - -void Deque() -{ - if (front==rear) - { - cout<<"\nUnderflow"; - } - - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; -} - diff --git a/Data Structure/Queue Using Linked List.cpp b/Data Structure/Queue Using Linked List.cpp deleted file mode 100644 index acf32ebd5..000000000 --- a/Data Structure/Queue Using Linked List.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - - -node *front, *rear; - - -void Enque(int x) -{ - if (rear==NULL) - { - node *n= new node; - n->val=x; - n->next=NULL; - rear=n; - front=n; - } - - else - { - - node *n = new node; - n->val=x; - n->next=NULL; - rear->next=n; - rear=n; - } -} - -void Deque() -{ - if (rear==front) - { - cout<<"\nUnderflow"; - } - else - { - node *t = front; - cout<<"\n"<val<<" deleted"; - front=front->next; - delete t; - } -} - -void show() -{ - node *t=front; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } -} - -int main() -{ - int ch, x; - do - { - cout<<"\n1. Enque"; - cout<<"\n2. Deque"; - cout<<"\n3. Print"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; -} - diff --git a/Data Structure/Stack Using Array.cpp b/Data Structure/Stack Using Array.cpp deleted file mode 100644 index c5ad146cb..000000000 --- a/Data Structure/Stack Using Array.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -using namespace std; - -int *stack; -int top=0, size; - -void push(int x) -{ - if(top==size) - { - cout<<"\nOverflow"; - } - else - { - stack[top++]=x; - } -} - -void pop() -{ - if (top==0) - { - cout<<"\nUnderflow"; - } - else - { - cout<<"\n"<>size; - stack = new int[size]; - int ch, x; - do - { - cout<<"\n1. Push"; - cout<<"\n2. Pop"; - cout<<"\n3. Print"; - cout<<"\n4. Print topmost element:"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - push(x); - } - else if (ch==2) - { - pop(); - } - else if (ch==3) - { - show(); - } - else if(ch==4) - { - topmost(); - } - } - while(ch!=0); - - return 0; -} - diff --git a/Data Structure/Stack Using Linked List.cpp b/Data Structure/Stack Using Linked List.cpp deleted file mode 100644 index 753fda8ed..000000000 --- a/Data Structure/Stack Using Linked List.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - - -node *top; - -void push(int x) -{ - node *n = new node; - n->val=x; - n->next=top; - top=n; -} - -void pop() -{ - if (top==NULL) - { - cout<<"\nUnderflow"; - } - else - { - node *t = top; - cout<<"\n"<val<<" deleted"; - top=top->next; - delete t; - } -} - -void show() -{ - node *t=top; - while(t!=NULL) - { - cout<val<<"\n"; - t=t->next; - } -} - -int main() -{ - int ch, x; - do - { - cout<<"\n1. Push"; - cout<<"\n2. Pop"; - cout<<"\n3. Print"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - push(x); - } - else if (ch==2) - { - pop(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; -} - diff --git a/Data Structure/Tree.cpp b/Data Structure/Tree.cpp deleted file mode 100644 index 963779abe..000000000 --- a/Data Structure/Tree.cpp +++ /dev/null @@ -1,160 +0,0 @@ -#include -using namespace std; - - -struct node -{ - int val; - node *left; - node *right; -}; - -struct queue -{ - node *t[100]; - int front; - int rear; -}; - -queue q; - - -void enqueue(node *n) -{ - q.t[q.rear++]=n; -} - -node * dequeue() -{ - return (q.t[q.front++]); -} - - - -void CreateTree(node *curr, node *n, int x, char pos) -{ - if(n!=NULL) - { - char ch; - cout<<"\nLeft or Right of "<val<<" : "; - cin>>ch; - if(ch=='l') - CreateTree(n, n->left, x, ch); - else if(ch=='r') - CreateTree(n, n->right, x, ch); - } - - else - { - node *t=new node; - t->val=x; - t->left=NULL; - t->right=NULL; - if (pos=='l') - { - curr->left=t; - } - else if(pos=='r') - { - curr->right=t; - } - } -} - - -void BFT(node *n) -{ - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } -} - -void Pre(node *n) -{ - if (n!=NULL) - { - cout<val<<" "; - Pre(n->left); - Pre(n->right); - } -} - -void In(node *n) -{ - if (n!=NULL) - { - In(n->left); - cout<val<<" "; - In(n->right); - } -} - - -void Post(node *n) -{ - if (n!=NULL) - { - Post(n->left); - Post(n->right); - cout<val<<" "; - } -} - - - -int main() -{ - q.front=0; - q.rear=0; - int value; - int ch; - node *root=new node; - cout<<"\nEnter the value of root node :"; - cin>>value; - root->val=value; - root->left=NULL; - root->right=NULL; - do - { - cout<<"\n1. Insert : "; - cout<<"\n2. Breadth First"; - cout<<"\n3. Preorder Depth First"; - cout<<"\n4. Inorder Depth First"; - cout<<"\n5. Postorder Depth First"; - - cout<<"\nEnter Your Choice : "; - cin>>ch; - switch(ch) - { - case 1: - int x; - char pos; - cout<<"\nEnter the value to be Inserted : "; - cin>>x; - cout<<"\nLeft or Right of Root : "; - cin>>pos; - if(pos=='l') - CreateTree(root, root->left, x, pos); - else if(pos=='r') - CreateTree(root, root->right, x, pos); - break; - case 2: - BFT(root); - break; - case 3: - Pre(root); - break; - case 4: - In(root); - break; - case 5: - Post(root); - break; - } - } - while(ch!=0); -} diff --git a/Data Structure/TrieTree.cpp b/Data Structure/TrieTree.cpp deleted file mode 100644 index 866087d87..000000000 --- a/Data Structure/TrieTree.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -using namespace std; -// structure definition -typedef struct trie -{ - struct trie *arr[26]; - bool isEndofWord; -} trie; -// create a new node for trie -trie *createNode() -{ - trie *nn = new trie(); - for (int i = 0; i < 26; i++) - nn->arr[i] = NULL; - nn->isEndofWord = false; - return nn; -} - -// insert string into the trie -void insert(trie *root, char* str) -{ - for (int i = 0; i < strlen(str); i++) - { - int j = str[i] - 'a'; - if (root->arr[j]) - { - root = root->arr[j]; - } - else - { - root->arr[j] = createNode(); - root = root->arr[j]; - } - } - root->isEndofWord = true; -} - -// search a string exists inside the trie -bool search(trie *root, char* str, int index) -{ - if (index == strlen(str)) - { - if (!root->isEndofWord) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root->arr[j]) - return false; - return search(root->arr[j], str, index + 1); -} -/* removes the string if it is not a prefix of any other - string, if it is then just sets the endofword to false, else - removes the given string*/ -bool deleteString (trie *root, char* str, int index) -{ - if (index == strlen(str)) - { - if (!root->isEndofWord) - return false; - root->isEndofWord = false; - for (int i = 0; i < 26; i++) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root->arr[j]) - return false; - bool var = deleteString (root, str, index + 1); - if (var) - { - root->arr[j] = NULL; - if (root->isEndofWord) - return false; - else - { - int i; - for (i = 0; i < 26; i++) - if (root->arr[i]) - return false; - return true; - } - } -} - -int main() -{ - trie *root = createNode(); - insert(root, "hello"); - insert(root, "world"); - int a = search(root, "hello", 0); - int b = search(root, "word", 0); - printf("%d %d ", a, b); - return 0; -} \ No newline at end of file diff --git a/Data Structure/linkedList_implentation_usingArray.cpp b/Data Structure/linkedList_implentation_usingArray.cpp deleted file mode 100644 index ca08653de..000000000 --- a/Data Structure/linkedList_implentation_usingArray.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* The difference between the pointer implementation of linked list and array implementation of linked list: - 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. -*/ - -#include -using namespace std; -struct Node{ - int data; - int next; -}; -Node AvailArray[100]; //array that will act as nodes of a linked list. -int head=-1; -int avail=0; -void initialise_list() -{ - for(int i=0;i<=98;i++) - { - AvailArray[i].next=i+1; - } - AvailArray[99].next=-1; //indicating the end of the linked list. - -} - -int getnode() //This will return the index of the first free node present in the avail list -{ - int NodeIndexToBeReturned=avail; - avail=AvailArray[avail].next; - return NodeIndexToBeReturned; -} - -void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. -{ - AvailArray[nodeToBeDeleted].next=avail; - avail=nodeToBeDeleted; -} - -void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. -{ - int newNode=getnode(); - AvailArray[newNode].data=data; - AvailArray[newNode].next=head; - head=newNode; - -} - -void insertAtTheEnd(int data) -{ - int newNode=getnode(); - int temp=head; - while(AvailArray[temp].next!=-1) - { - temp=AvailArray[temp].next; - - } - //temp is now pointing to the end node. - AvailArray[newNode].data=data; - AvailArray[newNode].next=-1; - AvailArray[temp].next=newNode; -} - - -void display() -{ - int temp=head; - while(temp!=-1) - { - cout<"; - temp=AvailArray[temp].next; - } - cout<<"-1"<>z; - switch(z) - { - case 1: - cout<<"Enter the number you want to enter"<>x; - insertAtTheBeginning(x); - break; - case 2: - cout<<"Enter the number you want to enter"<>y; - insertAtTheEnd(y); - break; - case 3: - cout<<"The linked list contains the following element in order"< -#include -int main() -{ - int n,k,d,s=0; - cout<<"Enter a number:"; - cin>>n; - k=n; - while(k!=0) - { - d=k%10; - s+=(int)pow(d,3); - k/=10; - } - if(s==n) - cout< -#include - -using namespace std; - -//Wrapper class for storing an edge -class Edge{ - public: int src,dst,weight; -}; - -//Wrapper class for storing a graph -class Graph{ - public: - int vertexNum,edgeNum; - Edge* edges; - - //Constructs a graph with V vertices and E edges - Graph(int V,int E){ - this->vertexNum = V; - this->edgeNum = E; - this->edges =(Edge*) malloc(E * sizeof(Edge)); - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ - static int edgeInd = 0; - if(edgeInd < this->edgeNum){ - Edge newEdge; - newEdge.src = src; - newEdge.dst = dst; - newEdge.weight = weight; - this->edges[edgeInd++] = newEdge; - } - - } - -}; - -//Utility function to print distances -void print(int dist[], int V){ - cout<<"\nVertex Distance"<>V; - cout<<"Enter number of edges: "; - cin>>E; - Graph G(V,E); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; - G.addEdge(src, dst, weight); - } - cout<<"\nEnter source: "; - cin>>gsrc; - BellmanFord(G,gsrc); - - return 0; -} diff --git a/Dynamic Programming/Cut Rod.cpp b/Dynamic Programming/Cut Rod.cpp deleted file mode 100644 index 90e12a532..000000000 --- a/Dynamic Programming/Cut Rod.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/*Given a rod of length n inches and an array of prices that -contains prices of all pieces of size smaller than n. Determine -the maximum value obtainable by cutting up the rod and selling -the pieces.*/ - -#include -using namespace std; -int cutrod(int p[],int n) -{ - int r[n+1]; - r[0]=0; - for(int j=0;j -#include -using namespace std; - -int min(int x, int y, int z){ - return min(min(x,y), z); -} - -/* A Naive recursive C++ program to find - * minimum number of operations to convert - * str1 to str2. - * O(3^m) - */ -int editDist(string str1, string str2, int m, int n) { - if(m == 0) return n; - if(n == 0) return m; - - //If last characters are same then continue - //for the rest of them. - if(str1[m-1] == str2[n-1]) - return editDist(str1, str2, m-1, n-1); - - //If last not same, then 3 possibilities - //a.Insert b.Remove c. Replace - //Get min of three and continue for rest. - return 1 + min ( editDist(str1, str2, m, n-1), - editDist(str1, str2, m-1, n), - editDist(str1, str2, m-1, n-1) - ); -} - -/* A DP based program - * O(m x n) - */ -int editDistDP(string str1, string str2, int m, int n) { - - //Create Table for SubProblems - int dp[m+1][n+1]; - - //Fill d[][] in bottom up manner - for(int i=0; i<=m; i++) { - for(int j=0; j<=n; j++) { - //If str1 empty. Then add all of str2 - if(i==0) - dp[i][j] = j; - - //If str2 empty. Then add all of str1 - else if(j==0) - dp[i][j] = i; - - //If character same. Recur for remaining - else if(str1[i-1] == str2[j-1]) - dp[i][j] = dp[i-1][j-1]; - - else - dp[i][j] = 1 + min(dp[i][j-1],//Insert - dp[i-1][j],//Remove - dp[i-1][j-1]//Replace - ); - } - } - - return dp[m][n]; -} - -int main() { - string str1 = "sunday"; - string str2 = "saturday"; - - cout << editDist(str1, str2, str1.length(), str2.length()) << endl; - cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl; - - return 0; -} diff --git a/Dynamic Programming/Fibonacci_Bottom_Up.cpp b/Dynamic Programming/Fibonacci_Bottom_Up.cpp deleted file mode 100644 index cbd0912e8..000000000 --- a/Dynamic Programming/Fibonacci_Bottom_Up.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include -using namespace std; -int fib(int n){ - int res[n+1]; - res[0] = 0; res[1] = 1; - for(int i=2;i<=n;i++){ - res[i] = res[i-1] + res[i-2]; - } - return res[n]; -} -int main(int argc, char const *argv[]) -{ - int n; - cout<<"Enter n: "; - cin>>n; - cout<<"Fibonacci number is "; - cout< -using namespace std; -int arr[1000000]; -int fib(int n){ - if(arr[n]==-1){ - if(n<=1) - arr[n] = n; - else - arr[n] = fib(n-1) + fib(n-2); - } - return arr[n]; -} -int main(int argc, char const *argv[]) -{ - int n; - cout<<"Enter n: "; - cin>>n; - for (int i = 0; i < n+1; ++i) - { - arr[i] = -1; - } - cout<<"Fibonacci number is "< -#include -#include - -using namespace std; - -//Wrapper class for storing a graph -class Graph{ - public: - int vertexNum; - int** edges; - - //Constructs a graph with V vertices and E edges - Graph(int V){ - this->vertexNum = V; - this->edges =(int**) malloc(V * sizeof(int*)); - for(int i=0; iedges[i] = (int*) malloc(V * sizeof(int)); - for(int j=0; jedges[i][j] = INT_MAX; - this->edges[i][i] = 0; - } - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ - this->edges[src][dst] = weight; - } - - -}; - - -//Utility function to print distances -void print(int dist[], int V){ - cout<<"\nThe Distance matrix for Floyd - Warshall"<>V; - cout<<"Enter number of edges: "; - cin>>E; - Graph G(V); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; - G.addEdge(src, dst, weight); - } - FloydWarshall(G); - - return 0; -} diff --git a/Dynamic Programming/Longest Common Subsequence.cpp b/Dynamic Programming/Longest Common Subsequence.cpp deleted file mode 100644 index aba1eeb54..000000000 --- a/Dynamic Programming/Longest Common Subsequence.cpp +++ /dev/null @@ -1,87 +0,0 @@ -//Longest common subsequence - Dynamic Programming -#include -using namespace std; - -void Print(int trace[20][20], int m, int n, string a) -{ - if (m==0 || n==0) - { - return; - } - if (trace[m][n]==1) - { - Print(trace, m-1, n-1, a); - cout<res[i][j-1]) - { - res[i][j]=res[i-1][j]; - trace[i][j]=2; // 2 means trace the matrix in upwards direction. - } - else - { - res[i][j]=res[i][j-1]; - trace[i][j]=3; // means trace the matrix in left direction. - } - } - } - } - Print(trace, m, n, a); - return res[m][n]; -} - - - - -int main() -{ - string a,b; - cin>>a>>b; - cout< -using namespace std; -class graph{ - int v; - list *adj; - public: - graph(int v); - void addedge(int src,int dest); - void printgraph(); - void bfs(int s); -}; -graph::graph(int v){ - this->v = v; - this->adj = new list[v]; -} -void graph::addedge(int src,int dest){ - src--;dest--; - adj[src].push_back(dest); - //adj[dest].push_back(src); -} -void graph::printgraph(){ - for(int i=0;iv;i++){ - cout<<"Adjacency list of vertex "<::iterator it; - for(it=adj[i].begin();it!=adj[i].end();++it){ - cout<<*it+1<<" "; - } - cout<v+1]; - memset(visited,false,sizeof(bool)*(this->v+1)); - visited[s]=true; - list q; - q.push_back(s); - list::iterator it; - while(!q.empty()){ - int u = q.front(); - cout< -using namespace std; -int v = 4; -void DFSUtil_(int graph[4][4],bool visited[],int s){ - visited[s] = true; - cout< -#include -#include -#include -using namespace std; -#define INF 10000010 -vector < pair > graph[5*100001]; -int dis[5*100001]; -int dij(vector > * v,int s,int * dis) { - priority_queue < pair , vector < pair >,greater < pair > > pq; - // source distance to zero. - pq.push(make_pair(0,s)); - dis[s] = 0; - int u; - while(!pq.empty()) { - u = (pq.top()).second; - pq.pop(); - for( vector > :: iterator it = v[u].begin(); it != v[u].end();it++) { - if(dis[u] + it->first < dis[it->second]) { - dis[it->second] = dis[u] + it->first; - pq.push(make_pair(dis[it->second],it->second)); - } - } - } -} -int main() { - int m,n,l,x,y,s; - // n--> number of nodes , m --> number of edges - cin>>n>>m; - for(int i = 0;i < m;i++) { - // input edges. - scanf("%d%d%d",&x,&y,&l); - graph[x].push_back(make_pair(l,y)); - graph[y].push_back(make_pair(l,x)); // comment this line for directed graph - } - // start node. - scanf("%d",&s); - // intialise all distances to infinity. - for(int i = 1;i <= n;i++) - dis[i] = INF; - dij(graph,s,dis); - - for(int i = 1;i <= n;i++) - if(dis[i] == INF) - cout<<"-1 "; - else - cout< -//using namespace boost::multiprecision; -const int mx = 1e6+5; -const long int inf = 2e9; -typedef long long ll; -#define rep(i,n) for(i=0;i -#define vpii vector< pii > -#define vi vector -#define vll vector -#define r(x) scanf("%d",&x) -#define rs(s) scanf("%s",s) -#define gc getchar_unlocked -#define pc putchar_unlocked -#define mp make_pair -#define pb push_back -#define lb lower_bound -#define ub upper_bound -#define endl "\n" -#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -using namespace std; -void in(int &x) -{ - register int c = gc(); x = 0; int neg = 0; - for(;((c<48 || c>57) && c != '-');c = gc());if(c=='-') {neg=1;c=gc();} for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} - if(neg) x=-x; -} -void out (int n) { int N = n, rev, count = 0;rev = N; if (N == 0) { pc('0'); return ;} while ((rev % 10) == 0) { count++; rev /= 10;} rev = 0;while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;}while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;} -while (count--) pc('0'); -} -ll parent[mx],arr[mx],node,edge; -vector>>v; -void initial() -{ - int i; - rep(i,node+edge) - parent[i] = i; -} -int root(int i) -{ - while(parent[i] != i) - { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - return i; -} -void join(int x,int y) -{ - int root_x = root(x); //Disjoint set union by rank - int root_y = root(y); - parent[root_x] = root_y; -} -ll kruskal() -{ - ll mincost=0,i,x,y; - rep(i,edge) - { - x = v[i].second.first; - y = v[i].second.second; - if(root(x) != root(y)) - { - mincost += v[i].first; - join(x,y); - } - } - return mincost; -} -int main(){ - fast; - while(1) - { - int i,j,from,to,cost,totalcost=0; - cin>>node>>edge; //Enter the nodes and edges - if(node==0 && edge==0) break; //Enter 0 0 to break out - initial(); //Initialise the parent array - rep(i,edge) - { - cin>>from>>to>>cost; - v.pb(mp(cost,mp(from,to))); - totalcost += cost; - } - sort(v.begin(),v.end()); - // rep(i,v.size()) - // cout< -using namespace std; - -struct Item -{ - int weight; - int profit; -}; - - -float profitPerUnit(Item x) -{ - return (float)x.profit/(float)x.weight; -} - -int partition (Item arr[], int low, int high) -{ - Item pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element - - for (int j = low; j >capacity; - cout<<"\n Enter the number of Items : "; - int n; - cin>>n; - Item itemArray[n]; - for (int i = 0; i < n; i++) - { - cout<<"\nEnter the weight and profit of item "<>itemArray[i].weight; - cin>>itemArray[i].profit; - } - - quickSort(itemArray, 0, n-1); - - // show(itemArray, n); - - float maxProfit=0; - int i=n; - while(capacity>0 && --i>=0) - { - if(capacity>=itemArray[i].weight) - { - maxProfit+=itemArray[i].profit; - capacity-=itemArray[i].weight; - cout<<"\n\t"< -using namespace std; - -#define V 4 -#define INFINITY 99999 - -int graph[V][V] = { - {0, 5, 1, 2}, - {5, 0, 3, 3}, - {1, 3, 0, 4}, - {2, 3, 4, 0} -}; - - -struct mst -{ - bool visited; - int key; - int near; -}; - -mst MST_Array[V]; - -void initilize() -{ - for (int i = 0; i < V; i++) - { - MST_Array[i].visited=false; - MST_Array[i].key=INFINITY; // considering INFINITY as inifinity - MST_Array[i].near=i; - } - - MST_Array[0].key=0; -} - -void updateNear() -{ - for (int v = 0; v < V; v++) - { - int min=INFINITY; - int minIndex=0; - for (int i = 0; i < V; i++) - { - if (MST_Array[i].key -#include -using namespace std; - -struct Node { - int data; - struct Node *next; -} *head[100],*curr; - -void init() { - for(int i=0;i<100;i++) - head[i]=NULL; -} - -void add(int x,int h) { - struct Node *temp = new Node; - temp->data = x; - temp->next = NULL; - if(!head[h]) { - head[h] = temp; - curr = head[h]; - } - else { - curr=head[h]; - while(curr->next) - curr = curr->next; - curr->next = temp; - } -} - -void display(int mod) { - struct Node *temp; - int i; - for(i=0;inext; - } - cout<data; - cout<data !=x && temp->next) - temp=temp->next; - if(temp->next) - cout<<"Element found"; - else{ - if(temp->data == x) - cout<<"Element found"; - else - cout<< "Element not found"; - } -} - -int main(void) { - init(); - int c,x,mod,h; - cout<<"Enter the size of Hash Table. = "; - cin>>mod; - bool loop = true; - while(loop) { - cout<>c; - switch(c) { - case 1: - cout<<"Enter element to add = "; - cin>>x; - h = hash(x,mod); - h = fabs(h); - add(x,h); - break; - case 2: - cout<<"Enter element to search = "; - cin>>x; - h = hash(x,mod); - find(x,h); - break; - case 3: - cout<<"Enter element to generate hash = "; - cin>>x; - cout<<"Hash of "< -using namespace std; -int main(){ - int n,k; - cout<<"Enter size of array=\t"; - cin>>n; - cout<<"Enter Number of indeces u want to rotate the array to left=\t"; - cin>>k; - int a[n]; - cout<<"Enter elements of array=\t"; - for(int i=0;i>a[i]; - } - int temp=0; - for(int i=0;i -using namespace std; -int main(){ - int n,k; - cout<<"Enter size of array=\t"; - cin>>n; - cout<<"Enter Number of indices u want to rotate the array to right=\t"; -cin>>k; -int a[n]; -cout<<"Enter elements of array=\t"; - for(int i=0;i>a[i]; - int temp=0; - for(int i=0;i=0;j--){ - if(j==0){ - a[j]=temp; - } - else{ - a[j]=a[j-1];} - - } - - } - cout<<"Your rotated array is=\t"; - for(int i=0;i -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *start; - -void insert(int x) -{ - node *t=start; - - if (start!=NULL) - { - while(t->next!=start) - { - t=t->next; - } - node *n= new node; - t->next=n; - n->val=x; - n->next=start; - } - else - { - node *n= new node; - n->val=x; - start=n; - n->next=start; - } -} - -void remove(int x) -{ - node *t=start; - node *p; - while(t->val!=x) - { - p=t; - t=t->next; - } - p->next=t->next; - delete t; -} - -void search(int x) -{ - node *t= start; - int found =0; - while(t->next!=start) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } -} - -void show() -{ - node *t=start; - do - { - cout<val<<"\t"; - t=t->next; - } - while(t!=start); - -} - -int main() -{ - int choice, x; - do - { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Print"; - cout<<"\n\nEnter you choice : "; - cin>>choice; - switch (choice) - { - case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x; - insert(x); break; - case 2 : cout<<"\nEnter the element to be removed : "; - cin>>x; - remove(x); break; - case 3 : cout<<"\nEnter the element to be searched : "; - cin>>x; - search(x); break; - case 4 : show(); break; - } - } - while(choice!=0); - - return 0; -} diff --git a/Operations on Datastructures/Circular Queue Using Array.cpp b/Operations on Datastructures/Circular Queue Using Array.cpp deleted file mode 100644 index d91f31af3..000000000 --- a/Operations on Datastructures/Circular Queue Using Array.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include -using namespace std; - -int queue[10]; -int front=0; -int rear=0; -int count=0; - -void Enque(int x) -{ - if(count==10) - { - cout<<"\nOverflow"; - } - else - { - queue[rear]=x; - rear=(rear+1)%10; - count++; - } -} - -void Deque() -{ - if (front==rear) - { - cout<<"\nUnderflow"; - } - - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; -} - diff --git a/Operations on Datastructures/Intersection_of_2_arrays.cpp b/Operations on Datastructures/Intersection_of_2_arrays.cpp deleted file mode 100644 index e2c064e1b..000000000 --- a/Operations on Datastructures/Intersection_of_2_arrays.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include -int main() -{ - int i,j,m,n; - cout <<"Enter size of array 1:"; - cin >> m; - cout <<"Enter size of array 2:"; - cin >> n; - int a[m]; - int b[n]; - cout <<"Enter elements of array 1:"; - for(i=0;i> a[i]; - for(i=0;i> b[i]; - i=0;j=0; - while((ib[j]) - j++; - else - { - cout << a[i++]<<" "; - j++; - } - } - return 0; -} diff --git a/Operations on Datastructures/Union_of_2_arrays.cpp b/Operations on Datastructures/Union_of_2_arrays.cpp deleted file mode 100644 index 4046e1ae8..000000000 --- a/Operations on Datastructures/Union_of_2_arrays.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include -int main() -{ - int m,n,i=0,j=0; - cout << "Enter size of both arrays:"; - cin >> m >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for(i=0;i>a[i]; - cout << "Enter elements of array 2:"; - for(i=0;i> b[i]; - i=0;j=0; - while((ib[j]) - cout << b[j++] <<" "; - else - { - cout << a[i++]; - j++; - } - } - while(i -using namespace std; - - -//node defined -class node -{ -public: - int data; - node* link; - node(int d) - { - data = d; - link = NULL; - } - -}; - -//printing the linked list -void print(node* head) -{ - node* current = head; - while (current != NULL) - { - cout << current->data << " "; - current = current-> link; - } - cout << endl; -} - -//creating the linked list with 'n' nodes -node* createlist(int n) -{ - node* head = NULL; - node* t = NULL; - for (int i = 0; i < n; i++) - { - node* temp = NULL; - int num; - cin >> num; - temp = new node(num); - if (head == NULL) - { - head = temp; - t = temp; - continue; - } - if (t->link == NULL) t->link = temp; - t = temp; - } - return head; -} - - -//performing selection sort on the linked list in an iterative manner -void my_selection_sort_linked_list(node* &head) -{ - node* min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning - //while scanning if we find a node 'X' with value lesser than min, - //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' - node* current = min->link; // 'current' refers to the current node we are scanning - node* previous = min; //'previous' refers to the node that is previous to the current node - node* temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. - //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL - //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' - //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. - //Eg. Let suppose initially we have 5->4->1->3->2->NULL - //After 1st iteration : 1->4->5->3->2->NULL and so on - - while (min->link != NULL) //so that all the nodes are scanned or until there exists a node - { - //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node - - while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X - { - if (current->data < min->data) //if the current node is smaller than the presumed node 'min' - { - if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time - { - if (previous == min) //if the 'previous' is pointing to the 'min' node - { - //Update the pointers - head = current; //update the head pointer with the current node - min->link = current->link; - current->link = previous; - min = current; - current = previous->link; - } - else //if the 'previous' is not pointing to the 'min' node - { - //Update the pointers - head = current; //update the head pointer with the current node - previous->link = current->link; - current->link = min; - min = current; - current = previous->link; - } - } - else //if 'temp' is not NULL, i.e., its not the 1st iteration - { - temp->link = current; - previous->link = current->link; - current->link = min; - min = current; - current = previous->link; - } - } - else //if the current node is greater than min, just move the previous and the current pointer a step further - { - previous = previous->link; - current = current->link; - } - } - - //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part - //start the iteration again - temp = min; - min = min->link; - previous = min; - current = min->link; - } -} - -// Test cases: - -// enter the no. of nodes : 5 -// 8 9 3 1 4 -// original list is : 8 9 3 1 4 -// sorted list is : 1 3 4 8 9 - -// enter the no. of nodes : 3 -// -1 -2 -3 -// original list is : -1 -2 -3 -// sorted list is : -3 -2 -1 - - -// enter the no. of nodes : 8 -// 8 7 6 5 4 3 2 1 -// original list is : 8 7 6 5 4 3 2 1 -// sorted list is : 1 2 3 4 5 6 7 8 - -// enter the no. of nodes : 6 -// 5 3 4 1 -2 -4 -// original list is : 5 3 4 1 -2 -4 -// sorted list is : -4 -2 1 3 4 5 - - -int main() -{ - node* head = NULL; - int n; - cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list - cin >> n; - if (n == 0) return 0; - head = createlist(n); //creating the list - cout << "original list is : "; - print(head); //printing the original linked list - my_selection_sort_linked_list(head); //applying selection sort - cout << "sorted list is : "; - print(head); //printing the sorted linked list - return 0; -} \ No newline at end of file diff --git a/Others/Buzz_number.cpp b/Others/Buzz_number.cpp deleted file mode 100644 index 3d39c50f6..000000000 --- a/Others/Buzz_number.cpp +++ /dev/null @@ -1,17 +0,0 @@ -//A buzz number is a number that is either divisble by 7 or has last digit as 7. -#include -using namespace std; -int main() -{ - int n,t; - cin >> t; - while(t--) - { - cin >> n; - if((n%7==0)||(n%10==7)) - cout << n << " is a buzz number" << endl; - else - cout << n << " is not a buzz number" << endl; - } - return 0; -} diff --git a/Others/Decimal To Hexadecimal .cpp b/Others/Decimal To Hexadecimal .cpp deleted file mode 100644 index 39333ca00..000000000 --- a/Others/Decimal To Hexadecimal .cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include - -using namespace std; - -int main(void){ - int valueToConvert = 0; //Holds user input - int hexArray[8]; //Contains hex values backwards - int i = 0; //counter - char HexValues[] = "0123456789ABCDEF"; - - cout << "Enter a Decimal Value" << endl; //Displays request to stdout - cin >> valueToConvert; //Stores value into valueToConvert via user input - - while (valueToConvert > 15){ //Dec to Hex Algorithm - hexArray[i++] = valueToConvert % 16; //Gets remainder - valueToConvert /= 16; - } - hexArray[i] = valueToConvert; //Gets last value - - cout << "Hex Value: "; - while (i >= 0) - cout< -#include -#include -#include -using namespace std; - -//This functions fills a string with character c, n times and returns it -string fill( char c, int n ) -{ - string s = ""; - while( n-- ) s += c; - return s; -} - -//to convert to lowercase Roman Numeral -// the function works recursively -string tolowerRoman( int n ) -{ - if( n < 4 ) return fill( 'i', n ); - if( n < 6 ) return fill( 'i', 5 - n ) + "v"; - if( n < 9 ) return string( "v" ) + fill( 'i', n - 5 ); - if( n < 11 ) return fill( 'i', 10 - n ) + "x"; - if( n < 40 ) return fill( 'x', n / 10 ) + tolowerRoman( n % 10 ); - if( n < 60 ) return fill( 'x', 5 - n / 10 ) + 'l' + tolowerRoman( n % 10 ); - if( n < 90 ) return string( "l" ) + fill( 'x', n / 10 - 5 ) + tolowerRoman( n % 10 ); - if( n < 110 ) return fill( 'x', 10 - n / 10 ) + "c" + tolowerRoman( n % 10 ); - if( n < 400 ) return fill( 'c', n / 100 ) + tolowerRoman( n % 100 ); - if( n < 600 ) return fill( 'c', 5 - n / 100 ) + 'd' + tolowerRoman( n % 100 ); - if( n < 900 ) return string( "d" ) + fill( 'c', n / 100 - 5 ) + tolowerRoman( n % 100 ); - if( n < 1100 ) return fill( 'c', 10 - n / 100 ) + "m" + tolowerRoman( n % 100 ); - if( n < 4000 ) return fill( 'm', n / 1000 ) + tolowerRoman( n % 1000 ); - return "?"; -} - -//to convert to uppercase Roman Numeral -// the function works recursively -string toupperRoman( int n ) -{ - if( n < 4 ) return fill( 'I', n ); - if( n < 6 ) return fill( 'I', 5 - n ) + "V"; - if( n < 9 ) return string( "V" ) + fill( 'I', n - 5 ); - if( n < 11 ) return fill( 'I', 10 - n ) + "X"; - if( n < 40 ) return fill( 'X', n / 10 ) + toupperRoman( n % 10 ); - if( n < 60 ) return fill( 'X', 5 - n / 10 ) + 'L' + toupperRoman( n % 10 ); - if( n < 90 ) return string( "L" ) + fill( 'X', n / 10 - 5 ) + toupperRoman( n % 10 ); - if( n < 110 ) return fill( 'X', 10 - n / 10 ) + "C" + toupperRoman( n % 10 ); - if( n < 400 ) return fill( 'C', n / 100 ) + toupperRoman( n % 100 ); - if( n < 600 ) return fill( 'C', 5 - n / 100 ) + 'D' + toupperRoman( n % 100 ); - if( n < 900 ) return string( "D" ) + fill( 'C', n / 100 - 5 ) + toupperRoman( n % 100 ); - if( n < 1100 ) return fill( 'C', 10 - n / 100 ) + "M" + toupperRoman( n % 100 ); - if( n < 4000 ) return fill( 'M', n / 1000 ) + toupperRoman( n % 1000 ); - return "?"; -} - -//main function - -int main() -{ - -int n; -cout << "\t\tRoman numbers converter\n\n"; -cout << "Type in decimal number between 0 up to 4000 (exclusive): "; -cin >> n; -cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; -cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; -return 0; -} diff --git a/Others/GCD_of_n_numbers.cpp b/Others/GCD_of_n_numbers.cpp deleted file mode 100644 index 3e9e9ce17..000000000 --- a/Others/GCD_of_n_numbers.cpp +++ /dev/null @@ -1,23 +0,0 @@ -//This program aims at calculating the GCD of n numbers by division method -#include -using namepsace std; -int main() -{ - cout <<"Enter value of n:"<> n; - int a[n]; - int i,j,gcd; - cout << "Enter the n numbers:" << endl; - for(i=0;i> a[i]; - j=1; //to access all elements of the array starting from 1 - gcd=a[0]; - while(j -using namespace std; - -int main() -{ - int n,k,s=0,d; - cout << "Enter a number:"; - cin >> n; - s=0;k=n; - while(k>9) - { - while(k!=0) - { - d=k%10; - s+=d; - k/=10; - } - k=s; - s=0; - } - if(k==1) - cout << n << " is a happy number" << endl; - else - cout << n << " is not a happy number" << endl; - return 0; -} diff --git a/Others/Paranthesis Matching.cpp b/Others/Paranthesis Matching.cpp deleted file mode 100644 index 25ee7287b..000000000 --- a/Others/Paranthesis Matching.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include -#include - -using namespace std; - -#define MAX 100 - -// -------------- stack -------------- - -char stack[MAX]; -int top = -1; - -void push(char ch){ - stack[ ++top ] = ch; -} - -char pop(){ - return stack[ top-- ]; -} - -// -------------- end stack ----------- - -char opening(char ch){ - switch(ch){ - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; - } -} - -int main(){ - - string exp; - int valid = 1, i = 0; - cout<<"Enter The Expression : "; - cin >> exp; - - while (valid == 1 && i < exp.length()){ - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<'){ - push(exp[i]); - } - else if (top >= 0 && stack[top] == opening(exp[i])){ - pop(); - } - else{ - valid = 0; - } - i++; - } - - // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1){ - cout<<"\nCorrect Expression"; - } - else{ - cout<<"\nWrong Expression"; - } - - return 0; -} diff --git a/Others/Primality Test.cpp b/Others/Primality Test.cpp deleted file mode 100644 index 0b4bb67de..000000000 --- a/Others/Primality Test.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include -using namespace std; - - - //A simple and efficient implementation of a function to test if a number is prime, based on the fact that - //Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k. - - bool IsPrime( int number ) - { - if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) ) - return false; - - for( int k = 1; 36*k*k-12*k < number;++k) - { - if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) ) - return false; - } - return true; - } - - int main() - { - //Main Function - cout <<"Enter the value of n to check if Prime\n"; - int n; - cin >> n; - if(IsPrime(n)) - cout << n << " is Prime" < -using namespace std; - -Multiply(int A[][], int B[][], int n) -{ - if (n==2) - { - int p1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]); - int p2= (a[1][0]+a[1][1])*b[0][0]; - int p3= a[0][0]*(b[0][1]-b[1][1]); - int p4= a[1][1]*(b[1][0]-b[0][0]); - int p5= (a[0][0]+a[0][1])*b[1][1]; - int p6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]); - int p7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]); - - - int c[n][n]; - c[0][0]=p1+p4-p5+p7; - c[0][1]=p3+p5; - c[1][0]=p2+p4; - c[1][1]=p1-p2+p3+p6; - - return c[][]; - } - else - { - - } - -} - -int main() -{ - int p,q,r,s; - cout<<"Enter the dimensions of Matrices"; - cin>>n; - int A[n][n],; - int B[n][n],; - cout<<"Enter the elements of Matrix A"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j >A[i][j]; - } - } - - - cout<<"Enter the elements of Matrix B"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j >B[i][j]; - } - } - - Multiply(A, B, n); - return 0; -} \ No newline at end of file diff --git a/Others/Tower of Hanoi.cpp b/Others/Tower of Hanoi.cpp deleted file mode 100644 index f9b363784..000000000 --- a/Others/Tower of Hanoi.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include -using namespace std; - -struct tower -{ - int values[10]; - int top; -}F, U, T; - - - -void show() -{ - cout<<"\n\n\tF : "; - for(int i=0; i> no; - - for (int i = no; i >0; i--) - { - F.values[F.top++]=i; - }; - - - - - - show(); - TH(no, F, U, T); - - - - - - return 0; -} diff --git a/Others/spiral_print.cpp b/Others/spiral_print.cpp deleted file mode 100644 index 03ea074e9..000000000 --- a/Others/spiral_print.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include -using namespace std; - -void genArray(int a[][10],int r,int c){ - - int value=1; - for(int i=0;i=startCol;i--,cnt++){ - cout<=startRow;i--,cnt++){ - cout<>r>>c; - genArray(a,r,c); - spiralPrint(a,r,c); - - -return 0; -} diff --git a/README.md b/README.md index 81367fcb4..a3077cdc5 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,10 @@ -# C++ +# The Algorithms - C++ +[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md)  +![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) +![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) -This repository contains some useful algorithms and data structures. +### All algorithms implemented in C++ (for education) +The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. -### Contribute - -How you can contribute? See this small guide. - -* Use the directory structure of the repository. -* Please describe your pull requests. -* Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compiler process. -* Put comments in your code. -* Avoid **struct**. Instead use the **class** keyword. -* Add some test cases in the main-function. -* Can suggest any change in present algorithms(if needed). \ No newline at end of file +### Contribute Guidelines +Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. diff --git a/Range queries/MO.cpp b/Range queries/MO.cpp deleted file mode 100644 index 2a2cbfffd..000000000 --- a/Range queries/MO.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "bits/stdc++.h" -using namespace std; -const int N = 1e6+5; -int a[N],bucket[N],cnt[N]; -int bucket_size; -struct query{ - int l,r,i; -}q[N]; -int ans=0; - -void add(int index) -{ - cnt[a[index]]++; - if(cnt[a[index]] == 1) - ans++; -} -void remove(int index) -{ - cnt[a[index]]--; - if(cnt[a[index]] == 0) - ans--; -} - - -bool mycmp(query x, query y) -{ - if(x.l/bucket_size != y.l/bucket_size) - return x.l/bucket_size < y.l/bucket_size; - return x.rL) - { - add(left-1); - left--; - } - while(right<=R) - { - add(right); - right++; - } - while(right>R+1) - { - remove(right-1); - right--; - } - bucket[q[i].i] = ans; - } - for(i=0;i -#define MAX 4000000 -using namespace std; -typedef long long ll; -void ConsTree(ll arr[],ll segtree[],ll low,ll high,ll pos) -{ - if(low == high) - { - segtree[pos] = arr[low]; - return; - } - ll mid = (low+high)/2; - ConsTree(arr,segtree,low,mid,2*pos+1); - ConsTree(arr,segtree,mid+1,high,2*pos+2); - segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2]; -} -ll query(ll segtree[],ll lazy[],ll qlow,ll qhigh,ll low,ll high,ll pos) -{ - if(low > high) - return 0; - if(qlow>high || qhigh=high) - return segtree[pos]; - ll mid = (low+high)/2; - return query(segtree,lazy,qlow,qhigh,low,mid,2*pos+1) + query(segtree,lazy,qlow,qhigh,mid+1,high,2*pos+2); -} -void update(ll segtree[],ll lazy[],ll start,ll end,ll delta,ll low,ll high,ll pos) -{ - if(low>high) - return; - if(lazy[pos] != 0) - { - segtree[pos] += lazy[pos]*(high-low+1); - if(low!=high) - { - lazy[2*pos+1] += lazy[pos]; - lazy[2*pos+2] += lazy[pos]; - } - lazy[pos] = 0; - } - if(start > high || end < low) - return; - if(start <= low && end >= high) - { - segtree[pos] += delta*(high-low+1); - if(low != high) - { - lazy[2*pos+1] += delta; - lazy[2*pos+2] += delta; - } - return; - } - ll mid = (low+high)/2; - update(segtree,lazy,start,end,delta,low,mid,2*pos+1); - update(segtree,lazy,start,end,delta,mid+1,high,2*pos+2); - segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2]; -} -int main() { - ll n,c; - scanf("%lld %lld",&n,&c); - ll arr[n]={0},p,q,v,choice; - ll segtree[MAX],lazy[MAX]={0}; - ConsTree(arr,segtree,0,n-1,0); - while(c--) - { - scanf("%lld",&choice); - if(choice == 0) - { - scanf("%lld %lld %lld",&p,&q,&v); - update(segtree,lazy,p-1,q-1,v,0,n-1,0); - } - else - { - scanf("%lld %lld",&p,&q); - printf("%lld\n",query(segtree,lazy,p-1,q-1,0,n-1,0)); - } - } - return 0; -} diff --git a/Search/Binary Search.cpp b/Search/Binary Search.cpp deleted file mode 100644 index cb67e3a07..000000000 --- a/Search/Binary Search.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -using namespace std; -int binary_search(int a[],int l,int r,int key){ - while(l<=r){ - int m = l+(r-l)/2; - if(key==a[m]) - return m; - else if(key>n; - cout<<"Enter array elements: "; - int a[n]; - for (int i = 0; i < n; ++i) - { - cin>>a[i]; - } - cout<<"Enter search key: "; - cin>>key; - int res = binary_search(a,0,n-1,key); - if(res != -1) - cout< -using namespace std; - -int LinearSearch(int *array, int size, int key) -{ - for (int i = 0; i < size; ++i) - { - if (array[i]==key) - { - return i; - } - } - - return -1; -} - - -int main() -{ - int size; - cout<<"\nEnter the size of the Array : "; - cin >> size; - - int array[size]; - int key; - - //Input array - cout<<"\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) - { - cin>>array[i]; - } - - cout<<"\nEnter the number to be searched : "; - cin>>key; - - int index=LinearSearch(array, size, key); - if (index!=-1) - { - cout<<"\nNumber found at index : "< -#include -#include - -using namespace std; -char paragraph; - -int main() -{ - string paragraph; - cout << "Please enter your paragraph: \n"; - getline (cin,paragraph); - cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; - cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - - if (paragraph.empty()) - { - cout << "\nThe paragraph is empty" << endl; - } - else - { - while (true) { - string word; - cout << "Please enter the word you are searching for: "; - getline (cin,word); - cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == string::npos) - { - cout << word << " does not exist in the sentence" << endl; - } - else - { - cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl << endl; - } - system("pause"); - } - - } -} diff --git a/Search/ternary_search.cpp b/Search/ternary_search.cpp deleted file mode 100644 index 4d126f09d..000000000 --- a/Search/ternary_search.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This is a divide and conquer algorithm. - * It does this by dividing the search space by 3 parts and - * using its property (usually monotonic property) to find - * the desired index. - * - * Time Complexity : O(log3 n) - * Space Complexity : O(1) (without the array) - */ - -#include -using namespace std; - -/* - * The absolutePrecision can be modified to fit preference but - * it is recommended to not go lower than 10 due to errors that - * may occur. - * - * The value of _target should be decided or can be decided later - * by using the variable of the function. - */ - -#define _target 10 -#define absolutePrecision 10 -#define MAX 10000000 - -int N = 21; -int A[MAX] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,10}; - -/* - * get_input function is to receive input from standard IO - */ -void get_input() -{ - // TODO: Get input from STDIO or write input to memory as done above. -} - - -/* - * This is the iterative method of the ternary search which returns the index of the element. - */ -int it_ternary_search(int left, int right, int A[],int target) -{ - while (1) - { - if(left A[twoThird]) left = twoThird+1; - else if(target < A[oneThird]) right = oneThird-1; - - else left = oneThird+1, right = twoThird-1; - } - else return -1; - } -} - -/* - * This is the recursive method of the ternary search which returns the index of the element. - */ -int rec_ternary_search(int left, int right, int A[],int target) -{ - if(left A[twoThird]) return rec_ternary_search(twoThird+1, right, A, target); - - return rec_ternary_search(oneThird+1, twoThird-1, A, target); - } - else return -1; -} - -/* - * ternary_search is a template function - * You could either use it_ternary_search or rec_ternary_search according to preference. - */ -void ternary_search(int N,int A[],int target) -{ - cout << it_ternary_search(0,N-1,A,target) << '\t'; - cout << rec_ternary_search(0,N-1,A,target) << '\t'; - cout << '\n'; -} - -int main() -{ - get_input(); - ternary_search(N,A,_target); - return 0; -} diff --git a/Sorting/BitonicSort.cpp b/Sorting/BitonicSort.cpp deleted file mode 100644 index e03e4fc14..000000000 --- a/Sorting/BitonicSort.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Source : https://www.geeksforgeeks.org/bitonic-sort/ - -/* C++ Program for Bitonic Sort. Note that this program - works only when size of input is a power of 2. */ - -#include -#include -using namespace std; - -/*The parameter dir indicates the sorting direction, ASCENDING - or DESCENDING; if (a[i] > a[j]) agrees with the direction, - then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) -{ - if (dir==(a[i]>a[j])) - swap(a[i],a[j]); -} - -/*It recursively sorts a bitonic sequence in ascending order, - if dir = 1, and in descending order otherwise (means dir=0). - The sequence to be sorted starts at index position low, - the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) -{ - if (cnt>1) - { - int k = cnt/2; - for (int i=low; i1) - { - int k = cnt/2; - - // sort in ascending order since dir here is 1 - bitonicSort(a, low, k, 1); - - // sort in descending order since dir here is 0 - bitonicSort(a, low+k, k, 0); - - // Will merge wole sequence in ascending order - // since dir=1. - bitonicMerge(a,low, cnt, dir); - } -} - -/* Caller of bitonicSort for sorting the entire array of - length N in ASCENDING order */ -void sort(int a[], int N, int up) -{ - bitonicSort(a,0, N, up); -} - -// Driver code -int main() -{ - int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; - int N = sizeof(a)/sizeof(a[0]); - - int up = 1; // means sort in ascending order - sort(a, N, up); - - printf("Sorted array: \n"); - for (int i=0; i -using namespace std; - -//Iterative Version - -void CocktailSelectionSort(vector &vec,int low,int high) -{ - while(low<=high) - { - int minimum=vec[low]; - int minimumindex=low; - int maximum=vec[high]; - int maximumindex=high; - - for(int i=low;i<=high;i++) - { - if(vec[i]>=maximum) - { - maximum=vec[i]; - maximumindex=i; - } - if(vec[i]<=minimum) - { - minimum=vec[i]; - minimumindex=i; - } - } - if(low!=maximumindex||high!=minimumindex) - { - swap(vec[low],vec[minimumindex]); - swap(vec[high],vec[maximumindex]); - } - else - { - swap(vec[low],vec[high]); - } - - low++; - high--; -} - -} - - -//Recursive Version - -void CocktailSelectionSort(vector &vec,int low,int high) -{ - - if(low>=high) - return; - - int minimum=vec[low]; - int minimumindex=low; - int maximum=vec[high]; - int maximumindex=high; - - for(int i=low;i<=high;i++) - { - if(vec[i]>=maximum) - { - maximum=vec[i]; - maximumindex=i; - } - if(vec[i]<=minimum) - { - minimum=vec[i]; - minimumindex=i; - } - } - if(low!=maximumindex||high!=minimumindex) - { - swap(vec[low],vec[minimumindex]); - swap(vec[high],vec[maximumindex]); - } - else - { - swap(vec[low],vec[high]); - } - - CocktailSelectionSort(vec,low+1,high-1); - - -} - - -//main function, select any one of iterative or recursive version - -int main() -{ - - int n; - cout << "Enter number of elements\n"; - cin >> n; - std::vector v(n); - cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) - { - cin >> v[i]; - } - - CocktailSelectionSort(v,0,n-1); - cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) - { - cout << v[i] << " "; - } - - - return 0; -} diff --git a/Sorting/CountingSortString.cpp b/Sorting/CountingSortString.cpp deleted file mode 100644 index 2dbf499e7..000000000 --- a/Sorting/CountingSortString.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// C++ Program for counting sort -#include - -using namespace std; - -void countSort(string arr) -{ - - string output; - - int count[256], i; - for(int i=0;i<256;i++) - count[i]=0; - - - for(i = 0; arr[i]; ++i) - ++count[arr[i]]; - - - for (i = 1; i <= 256; ++i) - count[i] += count[i-1]; - - for (i = 0; arr[i]; ++i) - { - output[count[arr[i]]-1] = arr[i]; - --count[arr[i]]; - } - - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; - - cout<<"Sorted character array is "<>arr; - - countSort(arr); - - return 0; -} diff --git a/Sorting/Counting_Sort.cpp b/Sorting/Counting_Sort.cpp deleted file mode 100644 index bea604a98..000000000 --- a/Sorting/Counting_Sort.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include -using namespace std; - -int Max(int Arr[], int N){ - int max = Arr[0]; - for(int i=1; i max) - max = Arr[i]; - return max; -} - -int Min(int Arr[], int N){ - int min = Arr[0]; - for(int i=1; i=0; i--){ - Sorted_Arr[Count[Arr[i]-min]-1] = Arr[i]; - Count[Arr[i]-min]--; - } - - return Sorted_Arr; -} - -int main(){ - - int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; - int *Sorted_Arr; - - cout<<"\n\tOrignal Array = ";Print(Arr, N); - Sorted_Arr = Counting_Sort(Arr, N); - cout<<"\n\t Sorted Array = ";Print(Sorted_Arr, N); - cout< -#include -using namespace std; -void max_heapify(int *a, int i, int n) -{ - int j, temp; - temp = a[i]; - j = 2 * i; - while (j <= n) - { - if (j < n && a[j + 1] > a[j]) - j = j + 1; - if (temp > a[j]) - break; - else if (temp <= a[j]) - { - a[j / 2] = a[j]; - j = 2 * j; - } - } - a[j / 2] = temp; - return; -} -void heapsort(int *a, int n) -{ - int i, temp; - for (i = n; i >= 2; i--) - { - temp = a[i]; - a[i] = a[1]; - a[1] = temp; - max_heapify(a, 1, i - 1); - } -} -void build_maxheap(int *a, int n) -{ - int i; - for (i = n / 2; i >= 1; i--) - { - max_heapify(a, i, n); - } -} -int main() -{ - int n, i, x; - cout << "Enter number of elements of array\n"; - cin >> n; - int a[20]; - for (i = 1; i <= n; i++) - { - cout << "Enter Element " << (i) << endl; - cin >> a[i]; - } - build_maxheap(a, n); - heapsort(a, n); - cout << "Sorted Output\n"; - for (i = 1; i <= n; i++) - { - cout << a[i] << endl; - } - getch(); -} diff --git a/Sorting/Insertion Sort.cpp b/Sorting/Insertion Sort.cpp deleted file mode 100644 index af66550ec..000000000 --- a/Sorting/Insertion Sort.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//Insertion Sort - -#include -using namespace std; - -int main() -{ - int n; - cout<<"\nEnter the length of your array : "; - cin>>n; - int Array[n]; - cout<<"\nEnter any "<>Array[i]; - } - - //Sorting - for(int i=1; i=0 && temp -#include -#include -using namespace std; - -bool NumericSort(string a,string b) -{ - while(a[0]=='0') - { - a.erase(a.begin()); - } - while(b[0]=='0') - { - b.erase(b.begin()); - } - int n=a.length(); - int m=b.length(); - if(n==m) - return a> n; - -vector v(n); -cout << "Enter the string of Numbers\n"; -for(int i=0;i> v[i]; -} - -sort(v.begin(),v.end()); -cout << "Elements sorted normally \n"; -for(int i=0;i -using namespace std; - -int partition (int arr[], int low, int high) -{ - int pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element - - for (int j = low; j >size; - - int arr[size]; - - cout<<"\nEnter the unsorted elements : "; - - for (int i = 0; i < size; ++i) - { - cout<<"\n"; - cin>>arr[i]; - } - quickSort(arr, 0, size); - cout<<"Sorted array\n"; - show(arr, size); - return 0; -} diff --git a/Sorting/Radix Sort.cpp b/Sorting/Radix Sort.cpp deleted file mode 100644 index eb3f12a57..000000000 --- a/Sorting/Radix Sort.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include -#include -#include -#include -using namespace std; -void radixsort(int a[],int n){ - int count[10]; - int output[n]; - memset(output,0,sizeof(output)); - memset(count,0,sizeof(count)); - int max = 0; - for (int i = 0; i < n; ++i) - { - if (a[i]>max) - { - max = a[i]; - } - } - int maxdigits = 0; - while(max){ - maxdigits++; - max/=10; - } - for(int j=0;j -using namespace std; - -int main() -{ - int Array[6]; - cout<<"\nEnter any 6 Numbers for Unsorted Array : "; - - //Input - for(int i=0; i<6; i++) - { - cin>>Array[i]; - } - - //Selection Sorting - for(int i=0; i<6; i++) - { - int min=i; - for(int j=i+1; j<6; j++) - { - if(Array[j] -using namespace std; - -int main() -{ - int size=10; - int array[size]; - // Input - cout<<"\nHow many numbers do want to enter in unsorted array : "; - cin>>size; - cout<<"\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) - { - cin>>array[i]; - } - - // Sorting - for (int i = size/2; i>0 ; i=i/2) - { - for (int j = i; j =0; k=k-i) - { - if (array[k] -#include -#include -using namespace std; - -// Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) -{ - // 1) Create n empty buckets - vector b[n]; - - // 2) Put array elements in different buckets - for (int i=0; i - +#include + // Number of vertices in the graph #define V 4 - + void printSolution(int color[]); - + /* A utility function to check if the current color assignment is safe for vertex v */ -bool isSafe (int v, bool graph[V][V], int color[], int c) +bool isSafe(int v, bool graph[V][V], int color[], int c) { for (int i = 0; i < V; i++) if (graph[v][i] && c == color[i]) return false; return true; } - + /* A recursive utility function to solve m coloring problem */ void graphColoring(bool graph[V][V], int m, int color[], int v) { /* base case: If all vertices are assigned a color then return true */ - if (v == V){ - printSolution(color); + if (v == V) + { + printSolution(color); return; } - + /* Consider this vertex v and try different colors */ for (int c = 1; c <= m; c++) { /* Check if assignment of color c to v is fine*/ if (isSafe(v, graph, color, c)) { - color[v] = c; - - /* recur to assign colors to rest of the vertices */ - graphColoring (graph, m, color, v+1); - - + color[v] = c; + + /* recur to assign colors to rest of the vertices */ + graphColoring(graph, m, color, v + 1); + /* If assigning color c doesn't lead to a solution then remove it */ - color[v] = 0; + color[v] = 0; } } - } /* A utility function to print solution */ @@ -50,10 +49,10 @@ void printSolution(int color[]) { printf(" Following are the assigned colors \n"); for (int i = 0; i < V; i++) - printf(" %d ", color[i]); + printf(" %d ", color[i]); printf("\n"); } - + // driver program to test above function int main() { @@ -64,18 +63,19 @@ int main() | / | (0)---(1) */ - bool graph[V][V] = {{0, 1, 1, 1}, + bool graph[V][V] = { + {0, 1, 1, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 0, 1, 0}, }; int m = 3; // Number of colors - int color[V]; + int color[V]; - for (int i = 0; i < V; i++) + for (int i = 0; i < V; i++) color[i] = 0; - + graphColoring(graph, m, color, 0); return 0; } diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp new file mode 100644 index 000000000..fbb8a6f96 --- /dev/null +++ b/backtracking/knight_tour.cpp @@ -0,0 +1,68 @@ +#include +# define n 8 + +/** +A knight's tour is a sequence of moves of a knight on a chessboard +such that the knight visits every square only once. If the knight +ends on a square that is one knight's move from the beginning +square (so that it could tour the board again immediately, following +the same path), the tour is closed; otherwise, it is open. +**/ + +using namespace std; +bool issafe(int x,int y,int sol[n][n]) +{ + return (x=0 && y=0 && sol[x][y]==-1); + +} +bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) +{ + int k,xnext,ynext; + + if(mov == n*n) + return true; + + for(k=0;k<8;k++) + { + xnext=x+xmov[k]; + ynext=y+ymov[k]; + + if(issafe(xnext,ynext,sol)) + { + sol[xnext][ynext]=mov; + + if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true) + return true; + else + sol[xnext][ynext]=-1; + } + } + return false; +} +int main() +{ + //initialize(); + + int sol[n][n]; + int i,j; + for(i=0;i +#include +#include + +using std::cout; +using std::endl; +using std::max; +using std::min; +using std::vector; + +int minimax(int depth, int node_index, bool is_max, vector scores, + int height) { + if (depth == height) + return scores[node_index]; + + int v1 = minimax(depth + 1, node_index * 2, !is_max, scores, height); + int v2 = minimax(depth + 1, node_index * 2 + 1, !is_max, scores, height); + + return is_max ? max(v1, v2) : min(v1, v2); +} + +int main() { + vector scores = { 90, 23, 6, 33, 21, 65, 123, 34423 }; + int height = log2(scores.size()); + + cout << "Optimal value: " << minimax(0, 0, true, scores, height) << endl; +} diff --git a/Backtracking/N Queens.cpp b/backtracking/n_queens.cpp similarity index 68% rename from Backtracking/N Queens.cpp rename to backtracking/n_queens.cpp index f070c5803..472aaa2fe 100644 --- a/Backtracking/N Queens.cpp +++ b/backtracking/n_queens.cpp @@ -1,82 +1,77 @@ -#include +#include #define N 4 using namespace std; void printSolution(int board[N][N]) { - cout<<"\n"; + cout << "\n"; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) - cout<<""<=0 && j>=0; i--, j--) + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; - + /* Check lower diagonal on left side */ - for (i=row, j=col; j>=0 && i= 0 && i < N; i++, j--) if (board[i][j]) return false; - + return true; } - void solveNQ(int board[N][N], int col) { - - if (col >= N){ + + if (col >= N) + { printSolution(board); return; } - + /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ - if ( isSafe(board, i, col) ) + if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ -// cout<<"\n"< +#define n 4 + +void PrintSol(int Board[n][n]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + std::cout << Board[i][j] << " "; + } + std::cout << std::endl; + } + std::cout << std::endl; +} + +bool CanIMove(int Board[n][n], int row, int col) { + /// check in the row + for (int i = 0; i < col; i++) { + if (Board[row][i] == 1) + return false; + } + /// check the first diagonal + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + if (Board[i][j] == 1) + return false; + } + /// check the second diagonal + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + if (Board[i][j] == 1) + return false; + } + return true; +} + +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { + PrintSol(Board); + return; + } + for (int i = 0; i < n; i++) { + if (CanIMove(Board, i, col)) { + Board[i][col] = 1; + NQueenSol(Board, col + 1); + Board[i][col] = 0; + } + } +} + +int main() { + int Board[n][n] = {0}; + NQueenSol(Board, 0); +} diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp new file mode 100644 index 000000000..307b5c7b0 --- /dev/null +++ b/backtracking/rat_maze.cpp @@ -0,0 +1,73 @@ +/* + A Maze is given as N*N binary matrix of blocks where source block is the upper + left most block i.e., maze[0][0] and destination block is lower rightmost + block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. + The rat can move only in two directions: forward and down. In the maze matrix, + 0 means the block is dead end and 1 means the block can be used in the path + from source to destination. +*/ +#include +#define size 4 + +using namespace std; + +int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size]) +{ + if ((currposrow == size - 1) && (currposcol == size - 1)) + { + soln[currposrow][currposcol] = 1; + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + cout << soln[i][j]; + } + cout << endl; + } + return 1; + } + else + { + soln[currposrow][currposcol] = 1; + + // if there exist a solution by moving one step ahead in a collumn + if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln)) + { + return 1; + } + + // if there exists a solution by moving one step ahead in a row + if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln)) + { + return 1; + } + + // the backtracking part + soln[currposrow][currposcol] = 0; + return 0; + } +} + +int main(int argc, char const *argv[]) +{ + int maze[size][size] = { + {1, 0, 1, 0}, + {1, 0, 1, 1}, + {1, 0, 0, 1}, + {1, 1, 1, 1}}; + + int soln[size][size]; + + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + soln[i][j] = 0; + } + } + + int currposrow = 0; + int currposcol = 0; + solveMaze(currposrow, currposcol, maze, soln); + return 0; +} diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp new file mode 100644 index 000000000..6a01fd395 --- /dev/null +++ b/backtracking/sudoku_solve.cpp @@ -0,0 +1,117 @@ +#include +using namespace std; +///N=9; +int n = 9; + +bool isPossible(int mat[][9], int i, int j, int no) +{ + ///Row or col nahin hona chahiye + for (int x = 0; x < n; x++) + { + if (mat[x][j] == no || mat[i][x] == no) + { + return false; + } + } + + /// Subgrid mein nahi hona chahiye + int sx = (i / 3) * 3; + int sy = (j / 3) * 3; + + for (int x = sx; x < sx + 3; x++) + { + for (int y = sy; y < sy + 3; y++) + { + if (mat[x][y] == no) + { + return false; + } + } + } + + return true; +} +void printMat(int mat[][9]) +{ + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cout << mat[i][j] << " "; + if ((j + 1) % 3 == 0) + { + cout << '\t'; + } + } + if ((i + 1) % 3 == 0) + { + cout << endl; + } + cout << endl; + } +} + +bool solveSudoku(int mat[][9], int i, int j) +{ + ///Base Case + if (i == 9) + { + ///Solve kr chuke hain for 9 rows already + printMat(mat); + return true; + } + + ///Crossed the last Cell in the row + if (j == 9) + { + return solveSudoku(mat, i + 1, 0); + } + + ///Blue Cell - Skip + if (mat[i][j] != 0) + { + return solveSudoku(mat, i, j + 1); + } + ///White Cell + ///Try to place every possible no + for (int no = 1; no <= 9; no++) + { + if (isPossible(mat, i, j, no)) + { + ///Place the no - assuming solution aa jayega + mat[i][j] = no; + bool aageKiSolveHui = solveSudoku(mat, i, j + 1); + if (aageKiSolveHui) + { + return true; + } + ///Nahin solve hui + ///loop will place the next no. + } + } + ///Sare no try kr liey, kisi se bhi solve nahi hui + mat[i][j] = 0; + return false; +} + +int main() +{ + + int mat[9][9] = + {{5, 3, 0, 0, 7, 0, 0, 0, 0}, + {6, 0, 0, 1, 9, 5, 0, 0, 0}, + {0, 9, 8, 0, 0, 0, 0, 6, 0}, + {8, 0, 0, 0, 6, 0, 0, 0, 3}, + {4, 0, 0, 8, 0, 3, 0, 0, 1}, + {7, 0, 0, 0, 2, 0, 0, 0, 6}, + {0, 6, 0, 0, 0, 0, 2, 8, 0}, + {0, 0, 0, 4, 1, 9, 0, 0, 5}, + {0, 0, 0, 0, 8, 0, 0, 7, 9}}; + + printMat(mat); + cout << "Solution " << endl; + solveSudoku(mat, 0, 0); + + return 0; +} diff --git a/computer_oriented_statistical_methods/Bisection_method.CPP b/computer_oriented_statistical_methods/Bisection_method.CPP new file mode 100644 index 000000000..717987321 --- /dev/null +++ b/computer_oriented_statistical_methods/Bisection_method.CPP @@ -0,0 +1,53 @@ +#include +#include +#include + +float eq(float i) +{ + return (pow(i, 3) - (4 * i) - 9); // original equation +} + +void main() +{ + float a, b, x, z; + clrscr(); + for (int i = 0; i < 100; i++) + { + z = eq(i); + if (z >= 0) + { + b = i; + a = --i; + goto START; + } + } + +START: + + cout << "\nFirst initial: " << a; + cout << "\nSecond initial: " << b; + for (i = 0; i < 100; i++) + { + x = (a + b) / 2; + z = eq(x); + cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]"; + + if (z < 0) + { + a = x; + } + else + { + b = x; + } + + if (z > 0 && z < 0.0009) // stoping criteria + { + goto END; + } + } + +END: + cout << "\n\nRoot: " << x; + getch(); +} diff --git a/computer_oriented_statistical_methods/Gaussian_elimination.cpp b/computer_oriented_statistical_methods/Gaussian_elimination.cpp new file mode 100644 index 000000000..58e634505 --- /dev/null +++ b/computer_oriented_statistical_methods/Gaussian_elimination.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + +int main() +{ + int mat_size, i, j, step; + + cout << "Matrix size: "; + cin >> mat_size; + + double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1]; + + cout << endl + << "Enter value of the matrix: " << endl; + for (i = 0; i < mat_size; i++) + { + for (j = 0; j <= mat_size; j++) + { + cin >> mat[i][j]; //Enter (mat_size*mat_size) value of the matrix. + } + } + + for (step = 0; step < mat_size - 1; step++) + { + for (i = step; i < mat_size - 1; i++) + { + double a = (mat[i + 1][step] / mat[step][step]); + + for (j = step; j <= mat_size; j++) + mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]); + } + } + + cout << endl + << "Matrix using Gaussian Elimination method: " << endl; + for (i = 0; i < mat_size; i++) + { + for (j = 0; j <= mat_size; j++) + { + x[i][j] = mat[i][j]; + cout << mat[i][j] << " "; + } + cout << endl; + } + cout << endl + << "Value of the Gaussian Elimination method: " << endl; + for (i = mat_size - 1; i >= 0; i--) + { + double sum = 0; + for (j = mat_size - 1; j > i; j--) + { + x[i][j] = x[j][j] * x[i][j]; + sum = x[i][j] + sum; + } + if (x[i][i] == 0) + x[i][i] = 0; + else + x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); + + cout << "x" << i << "= " << x[i][i] << endl; + } + return 0; +} diff --git a/computer_oriented_statistical_methods/Newton_Raphson.CPP b/computer_oriented_statistical_methods/Newton_Raphson.CPP new file mode 100644 index 000000000..183a78daf --- /dev/null +++ b/computer_oriented_statistical_methods/Newton_Raphson.CPP @@ -0,0 +1,53 @@ +#include +#include +#include + +float eq(float i) +{ + return (pow(i, 3) - (4 * i) - 9); // original equation +} +float eq_der(float i) +{ + return ((3 * pow(i, 2)) - 4); // derivative of equation +} + +void main() +{ + float a, b, z, c, m, n; + clrscr(); + for (int i = 0; i < 100; i++) + { + z = eq(i); + if (z >= 0) + { + b = i; + a = --i; + goto START; + } + } + +START: + + cout << "\nFirst initial: " << a; + cout << "\nSecond initial: " << b; + c = (a + b) / 2; + + for (i = 0; i < 100; i++) + { + float h; + m = eq(c); + n = eq_der(c); + + z = c - (m / n); + c = z; + + if (m > 0 && m < 0.009) // stoping criteria + { + goto END; + } + } + +END: + cout << "\n\nRoot: " << z; + getch(); +} diff --git a/computer_oriented_statistical_methods/Secant_method.CPP b/computer_oriented_statistical_methods/Secant_method.CPP new file mode 100644 index 000000000..b897e9184 --- /dev/null +++ b/computer_oriented_statistical_methods/Secant_method.CPP @@ -0,0 +1,49 @@ +#include +#include +#include + +float eq(float i) +{ + return (pow(i, 3) - (4 * i) - 9); // original equation +} + +void main() +{ + float a, b, z, c, m, n; + clrscr(); + for (int i = 0; i < 100; i++) + { + z = eq(i); + if (z >= 0) + { + b = i; + a = --i; + goto START; + } + } + +START: + + cout << "\nFirst initial: " << a; + cout << "\nSecond initial: " << b; + for (i = 0; i < 100; i++) + { + float h, d; + m = eq(a); + n = eq(b); + + c = ((a * n) - (b * m)) / (n - m); + a = b; + b = c; + + z = eq(c); + if (z > 0 && z < 0.09) // stoping criteria + { + goto END; + } + } + +END: + cout << "\n\nRoot: " << c; + getch(); +} diff --git a/computer_oriented_statistical_methods/false-position.cpp b/computer_oriented_statistical_methods/false-position.cpp new file mode 100644 index 000000000..5e15e92cc --- /dev/null +++ b/computer_oriented_statistical_methods/false-position.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +float eq(float i) { + return (pow(i, 3) - (4 * i) - 9); // origial equation +} +int main() { + float a, b, z, c, m, n; + system("clear"); + for (int i = 0; i < 100; i++) { + z = eq(i); + if (z >= 0) { + b = i; + a = --i; + goto START; + } + } + START: + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + for (int i = 0; i < 100; i++) { + float h, d; + m = eq(a); + n = eq(b); + c = ((a * n) - (b * m)) / (n - m); + a = c; + z = eq(c); + if (z > 0 && z < 0.09) { // stoping criteria + goto END; + } + } + END: + std::cout << "\n\nRoot: " << c; + system("pause"); +} diff --git a/computer_oriented_statistical_methods/successive_approximation.CPP b/computer_oriented_statistical_methods/successive_approximation.CPP new file mode 100644 index 000000000..b42ab8f8c --- /dev/null +++ b/computer_oriented_statistical_methods/successive_approximation.CPP @@ -0,0 +1,37 @@ +#include +#include +#include +float eq(float y) +{ + return ((3 * y) - (cos(y)) - 2); +} +float eqd(float y) +{ + return ((0.5) * ((cos(y)) + 2)); +} + +void main() +{ + float y, x1, x2, x3, sum, s, a, f1, f2, gd; + int i, n; + + clrscr(); + for (i = 0; i < 10; i++) + { + sum = eq(y); + cout << "value of equation at " << i << " " << sum << "\n"; + y++; + } + cout << "enter the x1->"; + cin >> x1; + cout << "enter the no iteration to perform->\n"; + cin >> n; + + for (i = 0; i <= n; i++) + { + x2 = eqd(x1); + cout << "\nenter the x2->" << x2; + x1 = x2; + } + getch(); +} \ No newline at end of file diff --git a/Data Structure/AVLtree.cpp b/data_structure/AVLtree.cpp similarity index 58% rename from Data Structure/AVLtree.cpp rename to data_structure/AVLtree.cpp index a3cd52919..db6b9e0d4 100644 --- a/Data Structure/AVLtree.cpp +++ b/data_structure/AVLtree.cpp @@ -3,20 +3,23 @@ using namespace std; -typedef struct node { +typedef struct node +{ int data; int height; - struct node* left; - struct node* right; -}node; + struct node *left; + struct node *right; +} node; -int max(int a, int b) { +int max(int a, int b) +{ return a > b ? a : b; } // Returns a new Node -node* createNode(int data) { +node *createNode(int data) +{ node *nn = new node(); nn->data = data; nn->height = 0; @@ -27,21 +30,24 @@ node* createNode(int data) { // Returns height of tree -int height(node *root) { - if(root==NULL) +int height(node *root) +{ + if (root == NULL) return 0; return 1 + max(height(root->left), height(root->right)); } // Returns difference between height of left and right subtree -int getBalance(node *root) { +int getBalance(node *root) +{ return height(root->left) - height(root->right); } // Returns Node after Right Rotation -node* rightRotate(node *root) { +node *rightRotate(node *root) +{ node *t = root->left; node *u = t->right; t->right = root; @@ -51,7 +57,8 @@ node* rightRotate(node *root) { // Returns Node after Left Rotation -node* leftRotate(node *root) { +node *leftRotate(node *root) +{ node *t = root->right; node *u = t->left; t->left = root; @@ -61,57 +68,65 @@ node* leftRotate(node *root) { // Returns node with minimum value in the tree -node* minValue(node* root) { - if(root->left==NULL) +node *minValue(node *root) +{ + if (root->left == NULL) return root; return minValue(root->left); } // Balanced Insertion -node* insert(node* root, int item) { +node *insert(node *root, int item) +{ node *nn = createNode(item); - if(root == NULL) + if (root == NULL) return nn; - if(itemdata) + if (item < root->data) root->left = insert(root->left, item); else root->right = insert(root->right, item); int b = getBalance(root); - if(b>1) { - if(getBalance(root->left)<0) - root->left = leftRotate(root->left); // Left-Right Case - return rightRotate(root); // Left-Left Case + if (b > 1) + { + if (getBalance(root->left) < 0) + root->left = leftRotate(root->left); // Left-Right Case + return rightRotate(root); // Left-Left Case } - else if(b<-1) { - if(getBalance(root->right)>0) - root->right = rightRotate(root->right); // Right-Left Case - return leftRotate(root); // Right-Right Case + else if (b < -1) + { + if (getBalance(root->right) > 0) + root->right = rightRotate(root->right); // Right-Left Case + return leftRotate(root); // Right-Right Case } return root; } // Balanced Deletion -node* deleteNode(node *root, int key) { - if(root == NULL) +node *deleteNode(node *root, int key) +{ + if (root == NULL) return root; - if(key < root->data) + if (key < root->data) root->left = deleteNode(root->left, key); - else if(key > root->data) + else if (key > root->data) root->right = deleteNode(root->right, key); - else { + else + { // Node to be deleted is leaf node or have only one Child - if(!root->right) { - node* temp = root->left; - delete(root); + if (!root->right) + { + node *temp = root->left; + delete (root); root = NULL; return temp; } - else if(!root->left) { - node* temp = root->right; - delete(root); + else if (!root->left) + { + node *temp = root->right; + delete (root); root = NULL; return temp; } @@ -124,36 +139,38 @@ node* deleteNode(node *root, int key) { return root; } - // LevelOrder (Breadth First Search) -void levelOrder(node* root) { - queue q; +void levelOrder(node *root) +{ + queue q; q.push(root); - while(!q.empty()) { + while (!q.empty()) + { root = q.front(); - cout<data<<" "; + cout << root->data << " "; q.pop(); - if(root->left) + if (root->left) q.push(root->left); - if(root->right) + if (root->right) q.push(root->right); } } -int main() { +int main() +{ // Testing AVL Tree node *root = NULL; int i; - for(i = 1 ; i <= 7 ; i++) + for (i = 1; i <= 7; i++) root = insert(root, i); - cout<<"LevelOrder: "; + cout << "LevelOrder: "; levelOrder(root); root = deleteNode(root, 1); // Deleting key with value 1 - cout<<"\nLevelOrder: "; + cout << "\nLevelOrder: "; levelOrder(root); - root = deleteNode(root, 4); // Deletin key with value 4 - cout<<"\nLevelOrder: "; + root = deleteNode(root, 4); // Deletin key with value 4 + cout << "\nLevelOrder: "; levelOrder(root); return 0; } diff --git a/data_structure/Binary Search Tree.cpp b/data_structure/Binary Search Tree.cpp new file mode 100644 index 000000000..32a65517c --- /dev/null +++ b/data_structure/Binary Search Tree.cpp @@ -0,0 +1,218 @@ +#include +using namespace std; + +struct node +{ + int val; + node *left; + node *right; +}; + +struct queue +{ + node *t[100]; + int front; + int rear; +}; + +queue q; + +void enqueue(node *n) +{ + q.t[q.rear++] = n; +} + +node *dequeue() +{ + return (q.t[q.front++]); +} + +void Insert(node *n, int x) +{ + if (x < n->val) + { + if (n->left == NULL) + { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } + else + { + Insert(n->left, x); + } + } + else + { + if (n->right == NULL) + { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } + else + { + Insert(n->right, x); + } + } +} + +int findMaxInLeftST(node *n) +{ + while (n->right != NULL) + { + n = n->right; + } + return n->val; +} + +void Remove(node *p, node *n, int x) +{ + if (n->val == x) + { + if (n->right == NULL && n->left == NULL) + { + if (x < p->val) + { + p->right = NULL; + } + else + { + p->left = NULL; + } + } + else if (n->right == NULL) + { + if (x < p->val) + { + p->right = n->left; + } + else + { + p->left = n->left; + } + } + else if (n->left == NULL) + { + if (x < p->val) + { + p->right = n->right; + } + else + { + p->left = n->right; + } + } + else + { + int y = findMaxInLeftST(n->left); + n->val = y; + Remove(n, n->right, y); + } + } + else if (x < n->val) + { + Remove(n, n->left, x); + } + else + { + Remove(n, n->right, x); + } +} + +void BFT(node *n) +{ + if (n != NULL) + { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } +} + +void Pre(node *n) +{ + if (n != NULL) + { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } +} + +void In(node *n) +{ + if (n != NULL) + { + In(n->left); + cout << n->val << " "; + In(n->right); + } +} + +void Post(node *n) +{ + if (n != NULL) + { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } +} + +int main() +{ + q.front = 0; + q.rear = 0; + int value; + int ch; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Breadth First"; + cout << "\n4. Preorder Depth First"; + cout << "\n5. Inorder Depth First"; + cout << "\n6. Postorder Depth First"; + + cout << "\nEnter Your Choice : "; + cin >> ch; + int x; + switch (ch) + { + case 1: + cout << "\nEnter the value to be Inserted : "; + cin >> x; + Insert(root, x); + break; + case 2: + cout << "\nEnter the value to be Deleted : "; + cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; + } + } while (ch != 0); +} diff --git a/data_structure/Binaryheap.cpp b/data_structure/Binaryheap.cpp new file mode 100644 index 000000000..31129a823 --- /dev/null +++ b/data_structure/Binaryheap.cpp @@ -0,0 +1,158 @@ +// A C++ program to demonstrate common Binary Heap Operations +#include +#include +using namespace std; + +// Prototype of a utility function to swap two integers +void swap(int *x, int *y); + +// A class for Min Heap +class MinHeap +{ + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap +public: + // Constructor + MinHeap(int capacity); + + // to heapify a subtree with the root at given index + void MinHeapify(int); + + int parent(int i) { return (i - 1) / 2; } + + // to get index of left child of node at index i + int left(int i) { return (2 * i + 1); } + + // to get index of right child of node at index i + int right(int i) { return (2 * i + 2); } + + // to extract the root which is the minimum element + int extractMin(); + + // Decreases key value of key at index i to new_val + void decreaseKey(int i, int new_val); + + // Returns the minimum key (key at root) from min heap + int getMin() { return harr[0]; } + + // Deletes a key stored at index i + void deleteKey(int i); + + // Inserts a new key 'k' + void insertKey(int k); +}; + +// Constructor: Builds a heap from a given array a[] of given size +MinHeap::MinHeap(int cap) +{ + heap_size = 0; + capacity = cap; + harr = new int[cap]; +} + +// Inserts a new key 'k' +void MinHeap::insertKey(int k) +{ + if (heap_size == capacity) + { + cout << "\nOverflow: Could not insertKey\n"; + return; + } + + // First insert the new key at the end + heap_size++; + int i = heap_size - 1; + harr[i] = k; + + // Fix the min heap property if it is violated + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Decreases value of key at index 'i' to new_val. It is assumed that +// new_val is smaller than harr[i]. +void MinHeap::decreaseKey(int i, int new_val) +{ + harr[i] = new_val; + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Method to remove minimum element (or root) from min heap +int MinHeap::extractMin() +{ + if (heap_size <= 0) + return INT_MAX; + if (heap_size == 1) + { + heap_size--; + return harr[0]; + } + + // Store the minimum value, and remove it from heap + int root = harr[0]; + harr[0] = harr[heap_size - 1]; + heap_size--; + MinHeapify(0); + + return root; +} + +// This function deletes key at index i. It first reduced value to minus +// infinite, then calls extractMin() +void MinHeap::deleteKey(int i) +{ + decreaseKey(i, INT_MIN); + extractMin(); +} + +// A recursive method to heapify a subtree with the root at given index +// This method assumes that the subtrees are already heapified +void MinHeap::MinHeapify(int i) +{ + int l = left(i); + int r = right(i); + int smallest = i; + if (l < heap_size && harr[l] < harr[i]) + smallest = l; + if (r < heap_size && harr[r] < harr[smallest]) + smallest = r; + if (smallest != i) + { + swap(&harr[i], &harr[smallest]); + MinHeapify(smallest); + } +} + +// A utility function to swap two elements +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} + +// Driver program to test above functions +int main() +{ + MinHeap h(11); + h.insertKey(3); + h.insertKey(2); + h.deleteKey(1); + h.insertKey(15); + h.insertKey(5); + h.insertKey(4); + h.insertKey(45); + cout << h.extractMin() << " "; + cout << h.getMin() << " "; + h.decreaseKey(2, 1); + cout << h.getMin(); + return 0; +} diff --git a/data_structure/Doubly Linked List.cpp b/data_structure/Doubly Linked List.cpp new file mode 100644 index 000000000..84a239d3f --- /dev/null +++ b/data_structure/Doubly Linked List.cpp @@ -0,0 +1,134 @@ +#include +using namespace std; + +struct node +{ + int val; + node *prev; + node *next; +}; + +node *start; + +void insert(int x) +{ + node *t = start; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->prev = t; + n->val = x; + n->next = NULL; + } + else + { + node *n = new node; + n->val = x; + n->prev = NULL; + n->next = NULL; + start = n; + } +} + +void remove(int x) +{ + node *t = start; + while (t->val != x) + { + t = t->next; + } + t->prev->next = t->next; + t->next->prev = t->prev; + delete t; +} + +void search(int x) +{ + node *t = start; + int found = 0; + while (t != NULL) + { + if (t->val == x) + { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + cout << "\nNot Found"; + } +} + +void show() +{ + node *t = start; + while (t != NULL) + { + cout << t->val << "\t"; + t = t->next; + } +} + +void reverseShow() +{ + node *t = start; + while (t->next != NULL) + { + t = t->next; + } + while (t != NULL) + { + cout << t->val << "\t"; + t = t->prev; + } +} + +int main() +{ + int choice, x; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Forward print"; + cout << "\n5. Reverse print"; + cout << "\n\nEnter you choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + ; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; + case 5: + reverseShow(); + break; + } + } while (choice != 0); + + return 0; +} diff --git a/data_structure/List Array.cpp b/data_structure/List Array.cpp new file mode 100644 index 000000000..de984876b --- /dev/null +++ b/data_structure/List Array.cpp @@ -0,0 +1,188 @@ +#include +using namespace std; + +struct list +{ + int data[50]; + int top = 0; + bool isSorted = false; + + int BinarySearch(int *array, int first, int last, int x) + { + if (last < first) + { + return -1; + } + int mid = (first + last) / 2; + if (array[mid] == x) + return mid; + else if (x < array[mid]) + return (BinarySearch(array, first, mid - 1, x)); + else if (x > array[mid]) + return (BinarySearch(array, mid + 1, last, x)); + } + + int LinarSearch(int *array, int x) + { + for (int i = 0; i < top; i++) + { + if (array[i] == x) + { + return i; + } + } + + return -1; + } + + int Search(int x) + { + int pos = -1; + + if (isSorted) + { + pos = BinarySearch(data, 0, top - 1, x); + } + + else + { + pos = LinarSearch(data, x); + } + + if (pos != -1) + { + cout << "\nElement found at position : " << pos; + } + else + { + cout << "\nElement not found"; + } + return pos; + } + + void Sort() + { + int i, j, pos; + for (i = 0; i < top; i++) + { + int min = data[i]; + for (j = i + 1; j < top; j++) + { + if (data[j] < min) + { + pos = j; + min = data[pos]; + } + } + + int temp = data[i]; + data[i] = data[pos]; + data[pos] = temp; + } + isSorted = true; + } + + void insert(int x) + { + if (!isSorted) + { + + if (top == 49) + { + cout << "\nOverflow"; + } + else + { + data[top] = x; + top++; + } + } + + else + { + int pos = 0; + + for (int i = 0; i < top - 1; i++) + { + if (data[i] <= x && x <= data[i + 1]) + { + pos = i + 1; + break; + } + } + if (pos == 0) + { + pos = top - 1; + } + + for (int i = top; i > pos; i--) + { + data[i] = data[i - 1]; + } + top++; + data[pos] = x; + } + } + + void Remove(int x) + { + int pos = Search(x); + cout << "\n" + << data[pos] << " deleted"; + for (int i = pos; i < top; i++) + { + data[i] = data[i + 1]; + } + top--; + } + + void Show() + { + for (int i = 0; i < top; i++) + { + cout << data[i] << "\t"; + } + } +}; + +int main() +{ + list L; + int choice; + int x; + do + { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + L.insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + L.Remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; + } + } while (choice != 0); + return 0; +} diff --git a/Data Structure/MorrisInorder.cpp b/data_structure/MorrisInorder.cpp similarity index 68% rename from Data Structure/MorrisInorder.cpp rename to data_structure/MorrisInorder.cpp index 5ea630fac..d3a2e9fd7 100644 --- a/Data Structure/MorrisInorder.cpp +++ b/data_structure/MorrisInorder.cpp @@ -7,73 +7,86 @@ using namespace std; -struct Btree { +struct Btree +{ int data; - struct Btree* left; //Pointer to left subtree - struct Btree* right; //Pointer to right subtree + struct Btree *left; //Pointer to left subtree + struct Btree *right; //Pointer to right subtree }; -void insert(Btree **root, int d) { - Btree *nn = new Btree(); //Creating new node +void insert(Btree **root, int d) +{ + Btree *nn = new Btree(); //Creating new node nn->data = d; nn->left = NULL; nn->right = NULL; - if(*root == NULL) { + if (*root == NULL) + { *root = nn; return; } - else { - queue q; + else + { + queue q; // Adding root node to queue q.push(*root); - while(!q.empty()) { + while (!q.empty()) + { Btree *node = q.front(); // Removing parent node from queue q.pop(); - if(node->left) + if (node->left) // Adding left child of removed node to queue q.push(node->left); - else { + else + { // Adding new node if no left child is present node->left = nn; return; } - if(node->right) + if (node->right) // Adding right child of removed node to queue q.push(node->right); - else { + else + { // Adding new node if no right child is present node->right = nn; return; - } + } } } } -void morrisInorder(Btree *root) { +void morrisInorder(Btree *root) +{ Btree *curr = root; Btree *temp; - while(curr) { - if(curr->left==NULL) { - cout<data<<" "; + while (curr) + { + if (curr->left == NULL) + { + cout << curr->data << " "; // If left of current node is NULL then curr is shifted to right curr = curr->right; } - else { + else + { // Left of current node is stored in temp temp = curr->left; // Moving to extreme right of temp - while(temp->right&&temp->right!=curr) + while (temp->right && temp->right != curr) temp = temp->right; // If extreme right is null it is made to point to currrent node (will be used for backtracking) - if(temp->right == NULL) { + if (temp->right == NULL) + { temp->right = curr; // current node is made to point its left subtree curr = curr->left; } // If extreme right already points to currrent node it it set to null - else if(temp->right == curr) { - cout<data<<" "; + else if (temp->right == curr) + { + cout << curr->data << " "; temp->right = NULL; // current node is made to point its right subtree curr = curr->right; @@ -82,13 +95,14 @@ void morrisInorder(Btree *root) { } } -int main() { +int main() +{ // Testing morrisInorder funtion Btree *root = NULL; int i; - for(i = 1 ; i <= 7 ; i++) + for (i = 1; i <= 7; i++) insert(&root, i); - cout<<"Morris Inorder: "; + cout << "Morris Inorder: "; morrisInorder(root); return 0; } diff --git a/data_structure/Queue Using Array.cpp b/data_structure/Queue Using Array.cpp new file mode 100644 index 000000000..3b79d06fc --- /dev/null +++ b/data_structure/Queue Using Array.cpp @@ -0,0 +1,75 @@ +#include +using namespace std; + +int queue[10]; +int front = 0; +int rear = 0; + +void Enque(int x) +{ + if (rear == 10) + { + cout << "\nOverflow"; + } + else + { + queue[rear++] = x; + } +} + +void Deque() +{ + if (front == rear) + { + cout << "\nUnderflow"; + } + + else + { + cout << "\n" + << queue[front++] << " deleted"; + for (int i = front; i < rear; i++) + { + queue[i - front] = queue[i]; + } + rear = rear - front; + front = 0; + } +} + +void show() +{ + for (int i = front; i < rear; i++) + { + cout << queue[i] << "\t"; + } +} + +int main() +{ + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/Queue Using Linked List.cpp b/data_structure/Queue Using Linked List.cpp new file mode 100644 index 000000000..39d7a9ae3 --- /dev/null +++ b/data_structure/Queue Using Linked List.cpp @@ -0,0 +1,89 @@ +#include +using namespace std; + +struct node +{ + int val; + node *next; +}; + +node *front, *rear; + +void Enque(int x) +{ + if (rear == NULL) + { + node *n = new node; + n->val = x; + n->next = NULL; + rear = n; + front = n; + } + + else + { + + node *n = new node; + n->val = x; + n->next = NULL; + rear->next = n; + rear = n; + } +} + +void Deque() +{ + if (rear == NULL && front == NULL) + { + cout << "\nUnderflow"; + } + else + { + node *t = front; + cout << "\n" + << t->val << " deleted"; + front = front->next; + delete t; + if (front == NULL) + rear = NULL; + } +} + +void show() +{ + node *t = front; + while (t != NULL) + { + cout << t->val << "\t"; + t = t->next; + } +} + +int main() +{ + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/Stack Using Array.cpp b/data_structure/Stack Using Array.cpp new file mode 100644 index 000000000..af1d57c46 --- /dev/null +++ b/data_structure/Stack Using Array.cpp @@ -0,0 +1,79 @@ +#include +using namespace std; + +int *stack; +int top = 0, size; + +void push(int x) +{ + if (top == size) + { + cout << "\nOverflow"; + } + else + { + stack[top++] = x; + } +} + +void pop() +{ + if (top == 0) + { + cout << "\nUnderflow"; + } + else + { + cout << "\n" + << stack[--top] << " deleted"; + } +} + +void show() +{ + for (int i = 0; i < top; i++) + { + cout << stack[i] << "\n"; + } +} + +void topmost() +{ + cout << "\nTopmost element: " << stack[top - 1]; +} +int main() +{ + cout << "\nEnter Size of stack : "; + cin >> size; + stack = new int[size]; + int ch, x; + do + { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\n4. Print topmost element:"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + push(x); + } + else if (ch == 2) + { + pop(); + } + else if (ch == 3) + { + show(); + } + else if (ch == 4) + { + topmost(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/Stack Using Linked List.cpp b/data_structure/Stack Using Linked List.cpp new file mode 100644 index 000000000..6925cf10c --- /dev/null +++ b/data_structure/Stack Using Linked List.cpp @@ -0,0 +1,73 @@ +#include +using namespace std; + +struct node +{ + int val; + node *next; +}; + +node *top; + +void push(int x) +{ + node *n = new node; + n->val = x; + n->next = top; + top = n; +} + +void pop() +{ + if (top == NULL) + { + cout << "\nUnderflow"; + } + else + { + node *t = top; + cout << "\n" + << t->val << " deleted"; + top = top->next; + delete t; + } +} + +void show() +{ + node *t = top; + while (t != NULL) + { + cout << t->val << "\n"; + t = t->next; + } +} + +int main() +{ + int ch, x; + do + { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + push(x); + } + else if (ch == 2) + { + pop(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/Tree.cpp b/data_structure/Tree.cpp new file mode 100644 index 000000000..9ccc7069b --- /dev/null +++ b/data_structure/Tree.cpp @@ -0,0 +1,138 @@ +#include +#include +using namespace std; + +struct node +{ + int val; + node *left; + node *right; +}; + +void CreateTree(node *curr, node *n, int x, char pos) +{ + if (n != NULL) + { + char ch; + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') + CreateTree(n, n->left, x, ch); + else if (ch == 'r') + CreateTree(n, n->right, x, ch); + } + else + { + node *t = new node; + t->val = x; + t->left = NULL; + t->right = NULL; + if (pos == 'l') + { + curr->left = t; + } + else if (pos == 'r') + { + curr->right = t; + } + } +} + +void BFT(node *n) +{ + list queue; + + queue.push_back(n); + + while(!queue.empty()) + { + n = queue.front(); + cout << n->val << " "; + queue.pop_front(); + + if(n->left != NULL) + queue.push_back(n->left); + if(n->right != NULL) + queue.push_back(n->right); + } +} + +void Pre(node *n) +{ + if (n != NULL) + { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } +} + +void In(node *n) +{ + if (n != NULL) + { + In(n->left); + cout << n->val << " "; + In(n->right); + } +} + +void Post(node *n) +{ + if (n != NULL) + { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } +} + +int main() +{ + int value; + int ch; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; + do + { + cout << "\n1. Insert"; + cout << "\n2. Breadth First"; + cout << "\n3. Preorder Depth First"; + cout << "\n4. Inorder Depth First"; + cout << "\n5. Postorder Depth First"; + + cout << "\nEnter Your Choice : "; + cin >> ch; + switch (ch) + { + case 1: + int x; + char pos; + cout << "\nEnter the value to be Inserted : "; + cin >> x; + cout << "\nLeft or Right of Root : "; + cin >> pos; + if (pos == 'l') + CreateTree(root, root->left, x, pos); + else if (pos == 'r') + CreateTree(root, root->right, x, pos); + break; + case 2: + BFT(root); + break; + case 3: + Pre(root); + break; + case 4: + In(root); + break; + case 5: + Post(root); + break; + } + } while (ch != 0); +} diff --git a/Data Structure/circular_Queue_using_Linked_List.cpp b/data_structure/circular_Queue_using_Linked_List.cpp similarity index 59% rename from Data Structure/circular_Queue_using_Linked_List.cpp rename to data_structure/circular_Queue_using_Linked_List.cpp index bf700ae8b..4b1ec476c 100644 --- a/Data Structure/circular_Queue_using_Linked_List.cpp +++ b/data_structure/circular_Queue_using_Linked_List.cpp @@ -1,36 +1,44 @@ -#include +#include using namespace std; -struct node{ +struct node +{ int data; struct node *next; }; -class Queue{ +class Queue +{ node *front; node *rear; + public: - Queue(){ + Queue() + { front = NULL; rear = NULL; } - void createNode(int val){ + void createNode(int val) + { node *ptr; node *nn; nn = new node; ptr = front; nn->data = val; nn->next = NULL; - front=nn; - rear=nn; + front = nn; + rear = nn; } - void enqueue(int val){ - if(front==NULL || rear==NULL){ + void enqueue(int val) + { + if (front == NULL || rear == NULL) + { createNode(val); } - else{ + else + { node *ptr; node *nn; - ptr=front; + ptr = front; nn = new node; nn->data = val; rear->next = nn; @@ -38,24 +46,28 @@ public: rear = nn; } } - void dequeue(){ + void dequeue() + { node *n; n = front; front = front->next; - delete(n); + delete (n); } - void traverse(){ + void traverse() + { node *ptr; - ptr=front; - do{ - cout<data<<" "; - ptr=ptr->next; - }while(ptr!=rear->next); - cout<data; - cout<data << " "; + ptr = ptr->next; + } while (ptr != rear->next); + cout << front->data; + cout << endl; } }; -int main(void){ +int main(void) +{ Queue q; q.enqueue(10); q.enqueue(20); diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp new file mode 100644 index 000000000..efc068f3c --- /dev/null +++ b/data_structure/cll/cll.cpp @@ -0,0 +1,127 @@ +/* + A simple class for Cicular Linear Linked List +*/ +#include "cll.h" +using namespace std; + +/* Constructor */ +cll::cll() +{ + head = NULL; + total = 0; +} + +cll::~cll() +{ + /* Desstructure, no need to fill */ +} + +/* Display a list. and total element */ +void cll::display() +{ + if (head == NULL) + cout << "List is empty !" << endl; + else + { + cout << "CLL list: "; + node *current = head; + for (int i = 0; i < total; i++) + { + cout << current->data << " -> "; + current = current ->next; + } + cout << head->data << endl; + cout << "Total element: "<< total <data = new_data; + newNode->next = NULL; + if(head==NULL) { + head = newNode; + head -> next = head; + } else { + node *current = head; + while (current -> next != head) { + current = current->next; + } + newNode->next = head; + current->next = newNode; + head = newNode; + } + total++; +} + +/* List insert a new value at head in list */ +void cll::insert_tail(int new_data) +{ + node *newNode; + newNode = new node; + newNode->data = new_data; + newNode->next = NULL; + if(head==NULL) { + head = newNode; + head -> next = head; + } else { + node *current = head; + while (current -> next != head) { + current = current->next; + } + current->next = newNode; + newNode->next = head; + } + total++; +} + +/* Get total element in list */ +int cll::get_size() +{ + return total; +} + + +/* Return true if the requested item (sent in as an argument) +is in the list, otherwise return false */ +bool cll::find_item(int item_to_find) +{ + if (head == NULL) { + cout << "List is empty !" << endl; + return false; + } else { + node *current = head; + while (current -> next != head) { + if (current->data == item_to_find) + return true; + current = current->next; + } + return false; + } +} + +/* Overloading method*/ +int cll::operator*() +{ + return head->data; +} + +/* Overload the pre-increment operator. + The iterator is advanced to the next node. */ +void cll::operator++() +{ + if (head == NULL) { + cout << "List is empty !" << endl; + } else { + node *current = head; + while (current -> next != head) { + current = current -> next; + } + current->next = head -> next; + head = head -> next; + } + total--; +} diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h new file mode 100644 index 000000000..ae71dcd01 --- /dev/null +++ b/data_structure/cll/cll.h @@ -0,0 +1,45 @@ +/* + * Simple data structure CLL (Cicular Linear Linked List) + * */ +#include +#include +#include +#include + +#ifndef CLL_H +#define CLL_H +/*The data structure is a linear linked list of integers */ +struct node +{ + int data; + node * next; +}; + +class cll +{ + public: + cll(); /* Construct without parameter */ + ~cll(); + void display(); /* Show the list */ + + /****************************************************** + * Useful method for list + *******************************************************/ + void insert_front(int new_data); /* Insert a new value at head */ + void insert_tail(int new_data); /* Insert a new value at tail */ + int get_size(); /* Get total element in list */ + bool find_item(int item_to_find); /* Find an item in list */ + + /****************************************************** + * Overloading method for list + *******************************************************/ + int operator*(); /* Returns the info contained in head */ + /* Overload the pre-increment operator. + The iterator is advanced to the next node. */ + void operator++(); + + protected: + node * head; + int total; /* Total element in a list */ +}; +#endif diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp new file mode 100644 index 000000000..15388b822 --- /dev/null +++ b/data_structure/cll/main_cll.cpp @@ -0,0 +1,44 @@ +#include "cll.h" +using namespace std; + +int main() +{ + /* Test CLL */ + cout << "----------- Test construct -----------" << endl; + cll list1; + list1.display(); + cout << "----------- Test insert front -----------" << endl; + list1.insert_front(5); + cout << "After insert 5 at front: "< +#include + +using std::cout; +using std::endl; +using std::vector; + +vector root, rnk; + +void CreateSet(int n) { + root = vector (n+1); + rnk = vector (n+1, 1); + for (int i = 1; i <= n; ++i) { + root[i] = i; + } +} + +int Find(int x) { + if (root[x] == x) { + return x; + } + return root[x] = Find(root[x]); +} + +bool InSameUnion(int x, int y) { + return Find(x) == Find(y); +} + +void Union(int x, int y) { + int a = Find(x), b = Find(y); + if (a != b) { + if (rnk[a] < rnk[b]) { + root[a] = b; + } else if (rnk[a] > rnk[b]) { + root[b] = a; + } else { + root[a] = b; + ++rnk[b]; + } + } +} + +int main() { + // tests CreateSet & Find + int n = 100; + CreateSet(n); + for (int i = 1; i <= 100; ++i) { + if (root[i] != i) { + cout << "Fail" << endl; + break; + } + } + // tests InSameUnion & Union + cout << "1 and 2 are initially not in the same subset" << endl; + if (InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + Union(1, 2); + cout << "1 and 2 are now in the same subset" << endl; + if (!InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + return 0; +} diff --git a/data_structure/linkedList_implentation_usingArray.cpp b/data_structure/linkedList_implentation_usingArray.cpp new file mode 100644 index 000000000..6f8205f27 --- /dev/null +++ b/data_structure/linkedList_implentation_usingArray.cpp @@ -0,0 +1,106 @@ +/* The difference between the pointer implementation of linked list and array implementation of linked list: + 1. The NULL is represented by -1; + 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. +*/ + +#include +using namespace std; +struct Node +{ + int data; + int next; +}; +Node AvailArray[100]; //array that will act as nodes of a linked list. +int head = -1; +int avail = 0; +void initialise_list() +{ + for (int i = 0; i <= 98; i++) + { + AvailArray[i].next = i + 1; + } + AvailArray[99].next = -1; //indicating the end of the linked list. +} + +int getnode() //This will return the index of the first free node present in the avail list +{ + int NodeIndexToBeReturned = avail; + avail = AvailArray[avail].next; + return NodeIndexToBeReturned; +} + +void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. +{ + AvailArray[nodeToBeDeleted].next = avail; + avail = nodeToBeDeleted; +} + +void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. +{ + int newNode = getnode(); + AvailArray[newNode].data = data; + AvailArray[newNode].next = head; + head = newNode; +} + +void insertAtTheEnd(int data) +{ + int newNode = getnode(); + int temp = head; + while (AvailArray[temp].next != -1) + { + temp = AvailArray[temp].next; + } + //temp is now pointing to the end node. + AvailArray[newNode].data = data; + AvailArray[newNode].next = -1; + AvailArray[temp].next = newNode; +} + +void display() +{ + int temp = head; + while (temp != -1) + { + cout << AvailArray[temp].data << "->"; + temp = AvailArray[temp].next; + } + cout << "-1" << endl; + ; +} + +int main() +{ + initialise_list(); + int x, y, z; + for (;;) + { + cout << "1. Insert At The Beginning" << endl; + cout << "2. Insert At The End" << endl; + cout << "3. Display" << endl; + cout << "4.Exit" << endl; + cout << "Enter Your choice" << endl; + cin >> z; + switch (z) + { + case 1: + cout << "Enter the number you want to enter" << endl; + cin >> x; + insertAtTheBeginning(x); + break; + case 2: + cout << "Enter the number you want to enter" << endl; + cin >> y; + insertAtTheEnd(y); + break; + case 3: + cout << "The linked list contains the following element in order" << endl; + display(); + break; + case 4: + exit(0); + default: + cout << "The entered choice is not correct" << endl; + } + } +} diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp new file mode 100644 index 000000000..64cad14f9 --- /dev/null +++ b/data_structure/linked_list.cpp @@ -0,0 +1,135 @@ +#include + +struct node { + int val; + node *next; +}; + +node *start; + +void insert(int x) { + node *t = start; + node *n = new node; + n->val = x; + n->next = NULL; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + t->next = n; + } else { + start = n; + } + +} + +void remove(int x) { + if (start == NULL) { + std::cout << "\nLinked List is empty\n"; + return; + } else if (start->val == x) { + node *temp = start; + start = start->next; + delete temp; + return; + } + + node *temp = start, *parent = start; + + while (temp != NULL && temp->val != x) { + parent = temp; + temp = temp->next; + } + + if (temp == NULL) { + std::cout << std::endl << x << " not found in list\n"; + return; + } + + parent->next = temp->next; + delete temp; +} + +void search(int x) { + node *t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + std::cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + std::cout << "\nNot Found"; + } +} + +void show() { + node *t = start; + while (t != NULL) { + std::cout << t->val << "\t"; + t = t->next; + } +} + +void reverse() { + node *first = start; + if (first != NULL) { + node *second = first->next; + while (second != NULL) { + node *tem = second->next; + second->next = first; + first = second; + second = tem; + } + start->next = NULL; + start = first; + } else { + std::cout << "\nEmpty list"; + } +} + +int main() { + int choice, x; + do { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Print"; + std::cout << "\n5. Reverse"; + std::cout << "\n0. Exit"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + search(x); + break; + case 4: + show(); + std::cout << "\n"; + break; + case 5: + std::cout << "The reversed list: \n"; + reverse(); + show(); + std::cout << "\n"; + break; + } + } while (choice != 0); + + return 0; +} diff --git a/data_structure/queue/makefile b/data_structure/queue/makefile new file mode 100644 index 000000000..420909804 --- /dev/null +++ b/data_structure/queue/makefile @@ -0,0 +1,11 @@ +CC= g++ +CFLAGS = -c -Wall + +all: test_queue +queue.o: queue.cpp + $(CC) $(CFLAGS) queue.cpp +test_queue: queue.o + $(CC) test_queue.cpp queue.o -o queue + +clean: + rm *o queue diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp new file mode 100644 index 000000000..728adfc18 --- /dev/null +++ b/data_structure/queue/queue.cpp @@ -0,0 +1,90 @@ +#include +#include +#include "queue.h" + +using namespace std; + +/* Default constructor*/ +template +queue::queue() +{ + queueFront = NULL; + queueRear = NULL; + size = 0; +} + +/* Destructor */ +template +queue::~queue() +{ +} + +/* Display for testing */ +template +void queue::display() +{ + node *current = queueFront; + cout << "Front --> "; + while(current != NULL) { + cout<data<< " "; + current = current -> next; + } + cout < +bool queue::isEmptyQueue() +{ + return (queueFront == NULL); +} + +/* Clear queue */ +template +void queue::clear() +{ + queueFront = NULL; +} + +/* Add new item to the queue */ +template +void queue::enQueue(Kind item) +{ + node *newNode; + newNode = new node; + newNode->data = item; + newNode->next = NULL; + if (queueFront == NULL) { + queueFront = newNode; + queueRear = newNode; + } else { + queueRear->next = newNode; + queueRear = queueRear->next; + } + size++; +} + +/* Return the top element of the queue */ +template +Kind queue::front() +{ + assert(queueFront != NULL); + return queueFront->data; +} + +/* Remove the element of the queue */ +template +void queue::deQueue() +{ + node *temp; + if(!isEmptyQueue()) { + temp = queueFront; + queueFront = queueFront->next; + delete temp; + size--; + } else { + cout << "Queue is empty !" << endl; + } +} + diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h new file mode 100644 index 000000000..715def1ef --- /dev/null +++ b/data_structure/queue/queue.h @@ -0,0 +1,34 @@ +/* This class specifies the basic operation on a queue as a linked list */ +#ifndef QUEUE_H +#define QUEUE_H + +/* Definition of the node */ +template +struct node +{ + Kind data; + node *next; +}; + +/* Definition of the queue class */ +template +class queue +{ + public: + void display(); /* Show queue */ + queue(); /* Default constructor*/ + ~queue(); /* Destructor */ + bool isEmptyQueue(); /* Determine whether the queue is empty */ + void enQueue (Kind item); /* Add new item to the queue */ + Kind front(); /* Return the first element of the queue */ + void deQueue(); /* Remove the top element of the queue */ + void clear(); + + private: + node *queueFront; /* Pointer to the front of the queue */ + node *queueRear; /* Pointer to the rear of the queue */ + int size; +}; + +#endif + diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp new file mode 100644 index 000000000..caf80318c --- /dev/null +++ b/data_structure/queue/test_queue.cpp @@ -0,0 +1,38 @@ +#include +#include +#include "queue.h" +#include "queue.cpp" + +using namespace std; + +int main() +{ + queue q; + cout << "---------------------- Test construct ----------------------" << endl; + q.display(); + cout << "---------------------- Test isEmptyQueue ----------------------" << endl; + if(q.isEmptyQueue()) + cout << "PASS" < + +#define MAXSIZE 10 + +class Queue_Array { + int front; + int rear; + int size; + + public: + Queue_Array() { + front = -1; + rear = -1; + size = MAXSIZE; + } + int *arr = new int[size]; + void enqueue(int); + int dequeue(); + void display(); +}; + +void Queue_Array::enqueue(int ele) { + if (rear == size - 1) { + std::cout << "\nStack is full"; + } else if (front == -1 && rear == -1) { + front = rear = 0; + arr[rear] = ele; + } else if (rear < size) { + rear++; + arr[rear] = ele; + } +} + +int Queue_Array::dequeue() { + int d; + if (front == -1) { + std::cout << "\nstack is empty "; + return 0; + } else if (front == rear) { + d = arr[front]; + front = rear = -1; + } else { + d = arr[front++]; + } + + return d; +} + +void Queue_Array::display() { + if (front == -1) { + std::cout << "\nStack is empty"; + } else { + for (int i = front; i <= rear; i++) + std::cout << arr[i] << " "; + } +} + +int main() { + int op, data; + + Queue_Array ob; + + std::cout << "\n1. enqueue(Insertion) "; + std::cout << "\n2. dequeue(Deletion)"; + std::cout << "\n3. Display"; + std::cout << "\n4. Exit"; + while (1) { + std::cout << "\nEnter your choice "; + std::cin >> op; + if (op == 1) { + std::cout << "Enter data "; + std::cin >> data; + ob.enqueue(data); + } else if (op == 2) { + data = ob.dequeue(); + std::cout << "\ndequeue element is:\t" << data; + } else if (op == 3) { + ob.display(); + } else if (op == 4) { + exit(0); + } else { + std::cout << "\nWrong choice "; + } + } +} diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp new file mode 100644 index 000000000..8bc130c27 --- /dev/null +++ b/data_structure/queue_using_linkedlist.cpp @@ -0,0 +1,98 @@ +/* + Write a program to implement Queue using linkedlist. +*/ +#include + + +struct linkedlist{ + int data; + linkedlist *next; + +}; +class stack_linkedList{ + public: + linkedlist *front; + linkedlist *rear; + + stack_linkedList(){ + front=rear=NULL; + } + void enqueue(int); + int dequeue(); + void display(); + +}; +void stack_linkedList::enqueue(int ele){ + + linkedlist *temp=new linkedlist(); + temp->data=ele; + temp->next=NULL; + + if(front==NULL) + front=rear=temp; + else{ + rear->next=temp; + rear=temp; + } +} +int stack_linkedList::dequeue(){ + linkedlist *temp; + int ele; + if(front==NULL) + std::cout<<"\nStack is empty"; + else{ + temp=front; + ele=temp->data; + if(front==rear) //if length of queue is 1; + rear=rear->next; + front=front->next; + delete(temp); + } + return ele; +} +void stack_linkedList::display(){ + + if(front==NULL) + std::cout<<"\nStack is empty"; + + else { + + linkedlist *temp; + temp=front; + while(temp!=NULL){ + std::cout<data<<" "; + temp=temp->next; + } + } +} + +int main(){ + + int op,data; + stack_linkedList ob; + std::cout<<"\n1. enqueue(Insertion) "; + std::cout<<"\n2. dequeue(Deletion)"; + std::cout<<"\n3. Display"; + std::cout<<"\n4. Exit"; + + while(1){ + std::cout<<"\nEnter your choice "; + std::cin>>op; + if(op==1) + { + std::cout<<"Enter data "; + std::cin>>data; + ob.enqueue(data); + } + else if(op==2) + data=ob.dequeue(); + else if(op==3) + ob.display(); + else if(op==4) + exit(0); + else + std::cout<<"\nWrong choice "; + + } + return 0; +} diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp new file mode 100644 index 000000000..2d6bbec56 --- /dev/null +++ b/data_structure/stk/main.cpp @@ -0,0 +1,55 @@ +/* + * This program reads a data file consisting of students' GPAs + * followed by their names. The program then prints the highest + * GPA and the names of the students with the highest GPA. + * It uses stack to store the names of the students + * Run: + * make all + * ./main student.txt + ************************************************************ + * */ +#include +#include +#include +#include +#include + +#include "stack.h" +#include "stack.cpp" + +using namespace std; + +int main(int argc, char * argv[]) { + double GPA; + double highestGPA; + string name; + + assert(argc == 2); + ifstream infile; + stack stk; + + infile.open(argv[1]); + cout << fixed << showpoint; + cout << setprecision(2); + infile >> GPA >> name; + highestGPA = GPA; + + while (infile) { + if (GPA > highestGPA) { + stk.clear(); + stk.push(name); + highestGPA = GPA; + } else if (GPA == highestGPA) { + stk.push(name); + } + infile >> GPA >> name; + } + cout << "Highest GPA: " << highestGPA < +#include +#include "stack.h" + +using namespace std; + +/* Default constructor*/ +template +stack::stack() +{ + stackTop = NULL; + size = 0; +} + +/* Destructor */ +template +stack::~stack() +{ +} + +/* Display for testing */ +template +void stack::display() +{ + node *current = stackTop; + cout << "Top --> "; + while(current != NULL) { + cout<data<< " "; + current = current -> next; + } + cout < +bool stack::isEmptyStack() +{ + return (stackTop == NULL); +} + +/* Clear stack */ +template +void stack::clear() +{ + stackTop = NULL; +} + +/* Add new item to the stack */ +template +void stack::push(Type item) +{ + node *newNode; + newNode = new node; + newNode->data = item; + newNode->next = stackTop; + stackTop = newNode; + size++; +} + +/* Return the top element of the stack */ +template +Type stack::top() +{ + assert(stackTop != NULL); + return stackTop->data; +} + +/* Remove the top element of the stack */ +template +void stack::pop() +{ + node *temp; + if(!isEmptyStack()) { + temp = stackTop; + stackTop = stackTop->next; + delete temp; + size--; + } else { + cout << "Stack is empty !" << endl; + } +} + +/* Operator "=" */ +template +stack stack::operator=(stack & otherStack) +{ + node *newNode, *current, *last; + + if (stackTop != NULL) /* If stack is no empty, make it empty */ + stackTop = NULL; + if (otherStack.stackTop == NULL) + stackTop = NULL; + else { + current = otherStack.stackTop; + stackTop = new node; + stackTop->data = current->data; + stackTop->next = NULL; + last = stackTop; + current = current ->next; + /* Copy the remaining stack */ + while (current != NULL) + { + newNode = new node; + newNode->data = current->data; + newNode->next = NULL; + last->next = newNode; + last = newNode; + current = current->next; + } + } + size = otherStack.size; + return *this; +} diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h new file mode 100644 index 000000000..a93669482 --- /dev/null +++ b/data_structure/stk/stack.h @@ -0,0 +1,35 @@ +/* This class specifies the basic operation on a stack as a linked list */ +#ifndef STACK_H +#define STACK_H + +/* Definition of the node */ +template +struct node +{ + Type data; + node *next; +}; + +/* Definition of the stack class */ +template +class stack +{ + public: + void display(); /* Show stack */ + stack(); /* Default constructor*/ + ~stack(); /* Destructor */ + bool isEmptyStack(); /* Determine whether the stack is empty */ + void push (Type item); /* Add new item to the stack */ + Type top(); /* Return the top element of the stack */ + void pop(); /* Remove the top element of the stack */ + void clear(); + + stack operator=(stack & otherStack); + // Overload "=" the assignment operator. + private: + node *stackTop; /* Pointer to the stack */ + int size; +}; + +#endif + diff --git a/data_structure/stk/student.txt b/data_structure/stk/student.txt new file mode 100644 index 000000000..b7e3b9e79 --- /dev/null +++ b/data_structure/stk/student.txt @@ -0,0 +1,17 @@ +3.4 Tom +3.2 Kathy +2.5 Hoang +3.4 Tom +3.8 Randy +3.9 Kingston +3.8 Mickey +3.6 Peter +3.5 Donald +3.8 Cindy +3.7 Dome +3.9 Andy +3.8 Hai +3.9 Minnie +2.7 Gilda +3.9 Vinay +3.4 Hiral diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp new file mode 100644 index 000000000..4703fc906 --- /dev/null +++ b/data_structure/stk/test_stack.cpp @@ -0,0 +1,54 @@ +#include +#include "stack.h" +#include "stack.cpp" + +using namespace std; + +int main() +{ + stack stk; + cout << "---------------------- Test construct ----------------------" << endl; + stk.display(); + cout << "---------------------- Test isEmptyStack ----------------------" << endl; + if(stk.isEmptyStack()) + cout << "PASS" < stk1; + cout << "stk current: "<< endl; + stk.display(); + cout << endl << "Assign stk1 = stk "<< endl; + stk1 = stk; + stk1.display(); + cout << endl<< "After pushing 8 9 10 into stk1:" < +#include + +#include +#include + +// structure definition +typedef struct trie { + struct trie * arr[26]; + bool isEndofWord; +} trie; + +// create a new node for trie +trie * createNode() { + trie * nn = new trie(); + for (int i = 0; i < 26; i++) + nn -> arr[i] = NULL; + nn -> isEndofWord = false; + return nn; +} + +// insert string into the trie +void insert(trie * root, std::string str) { + for (int i = 0; i < str.length(); i++) { + int j = str[i] - 'a'; + if (root -> arr[j]) { + root = root -> arr[j]; + } else { + root -> arr[j] = createNode(); + root = root -> arr[j]; + } + } + root -> isEndofWord = true; +} + +// search a string exists inside the trie +bool search(trie * root, std::string str, int index) { + if (index == str.length()) { + if (!root -> isEndofWord) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root -> arr[j]) + return false; + return search(root -> arr[j], str, index + 1); +} + +/* +removes the string if it is not a prefix of any other +string, if it is then just sets the endofword to false, else +removes the given string +*/ +bool deleteString(trie * root, std::string str, int index) { + if (index == str.length()) { + if (!root -> isEndofWord) + return false; + root -> isEndofWord = false; + for (int i = 0; i < 26; i++) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root -> arr[j]) + return false; + bool + var = deleteString(root, str, index + 1); + if (var) { + root -> arr[j] = NULL; + if (root -> isEndofWord) { + return false; + } else { + int i; + for (i = 0; i < 26; i++) + if (root -> arr[i]) + return false; + return true; + } + } +} + +int main() { + trie * root = createNode(); + insert(root, "hello"); + insert(root, "world"); + int a = search(root, "hello", 0); + int b = search(root, "word", 0); + printf("%d %d ", a, b); + return 0; +} diff --git a/Dynamic Programming/0-1 Knapsack.cpp b/dynamic_programming/0-1 Knapsack.cpp similarity index 55% rename from Dynamic Programming/0-1 Knapsack.cpp rename to dynamic_programming/0-1 Knapsack.cpp index 4bed36fb2..9348372b2 100644 --- a/Dynamic Programming/0-1 Knapsack.cpp +++ b/dynamic_programming/0-1 Knapsack.cpp @@ -1,6 +1,6 @@ //0-1 Knapsack problem - Dynamic programming //#include -#include +#include using namespace std; //void Print(int res[20][20], int i, int j, int capacity) @@ -15,7 +15,7 @@ using namespace std; // { // cout<res[i][j-1]) @@ -28,43 +28,44 @@ using namespace std; // } //} -int Knapsack(int capacity,int n,int weight[],int value[]){ +int Knapsack(int capacity, int n, int weight[], int value[]) +{ int res[20][20]; - for (int i = 0; i < n+1; ++i) + for (int i = 0; i < n + 1; ++i) { - for (int j = 0; j < capacity+1; ++j) + for (int j = 0; j < capacity + 1; ++j) { - if(i==0||j==0) + if (i == 0 || j == 0) res[i][j] = 0; - else if(weight[i-1]<=j) - res[i][j] = max(value[i-1]+res[i-1][j-weight[i-1]], res[i-1][j]); + else if (weight[i - 1] <= j) + res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]); else - res[i][j] = res[i-1][j]; + res[i][j] = res[i - 1][j]; } } -// Print(res, n, capacity, capacity); -// cout<<"\n"; + // Print(res, n, capacity, capacity); + // cout<<"\n"; return res[n][capacity]; } int main() { int n; - cout<<"Enter number of items: "; - cin>>n; + cout << "Enter number of items: "; + cin >> n; int weight[n], value[n]; - cout<<"Enter weights: "; + cout << "Enter weights: "; for (int i = 0; i < n; ++i) { - cin>>weight[i]; + cin >> weight[i]; } - cout<<"Enter values: "; + cout << "Enter values: "; for (int i = 0; i < n; ++i) { - cin>>value[i]; + cin >> value[i]; } int capacity; - cout<<"Enter capacity: "; - cin>>capacity; - cout<> capacity; + cout << Knapsack(capacity, n, weight, value); return 0; } diff --git a/dynamic_programming/Bellman-Ford.cpp b/dynamic_programming/Bellman-Ford.cpp new file mode 100644 index 000000000..7c36d96df --- /dev/null +++ b/dynamic_programming/Bellman-Ford.cpp @@ -0,0 +1,128 @@ +#include +#include + +using namespace std; + +//Wrapper class for storing an edge +class Edge +{ +public: + int src, dst, weight; +}; + +//Wrapper class for storing a graph +class Graph +{ +public: + int vertexNum, edgeNum; + Edge *edges; + + //Constructs a graph with V vertices and E edges + Graph(int V, int E) + { + this->vertexNum = V; + this->edgeNum = E; + this->edges = (Edge *)malloc(E * sizeof(Edge)); + } + + //Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + static int edgeInd = 0; + if (edgeInd < this->edgeNum) + { + Edge newEdge; + newEdge.src = src; + newEdge.dst = dst; + newEdge.weight = weight; + this->edges[edgeInd++] = newEdge; + } + } +}; + +//Utility function to print distances +void print(int dist[], int V) +{ + cout << "\nVertex Distance" << endl; + for (int i = 0; i < V; i++) + { + if (dist[i] != INT_MAX) + cout << i << "\t" << dist[i] << endl; + else + cout << i << "\tINF" << endl; + } +} + +//The main function that finds the shortest path from given source +//to all other vertices using Bellman-Ford.It also detects negative +//weight cycle +void BellmanFord(Graph graph, int src) +{ + int V = graph.vertexNum; + int E = graph.edgeNum; + int dist[V]; + + //Initialize distances array as INF for all except source + //Intialize source as zero + for (int i = 0; i < V; i++) + dist[i] = INT_MAX; + dist[src] = 0; + + //Calculate shortest path distance from source to all edges + //A path can contain maximum (|V|-1) edges + for (int i = 0; i <= V - 1; i++) + for (int j = 0; j < E; j++) + { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + dist[v] = dist[u] + w; + } + + //Iterate inner loop once more to check for negative cycle + for (int j = 0; j < E; j++) + { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + { + cout << "Graph contains negative weight cycle. Hence, shortest distance not guaranteed." << endl; + return; + } + } + + print(dist, V); + + return; +} + +//Driver Function +int main() +{ + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V, E); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + cout << "\nEnter source: "; + cin >> gsrc; + BellmanFord(G, gsrc); + + return 0; +} diff --git a/Dynamic Programming/Catalan-Numbers.cpp b/dynamic_programming/Catalan-Numbers.cpp similarity index 71% rename from Dynamic Programming/Catalan-Numbers.cpp rename to dynamic_programming/Catalan-Numbers.cpp index a086ae6c1..4d73cd51a 100644 --- a/Dynamic Programming/Catalan-Numbers.cpp +++ b/dynamic_programming/Catalan-Numbers.cpp @@ -13,7 +13,7 @@ int *cat; // global array to hold catalan numbers unsigned long int catalan_dp(int n) { - /** Using the tabulation technique in dynamic programming, + /** Using the tabulation technique in dynamic programming, this function computes the first `n+1` Catalan numbers Parameter @@ -26,39 +26,39 @@ unsigned long int catalan_dp(int n) */ // By definition, the first two Catalan numbers are 1 - cat[0] = cat[1] = 1; + cat[0] = cat[1] = 1; // Compute the remaining numbers from index 2 to index n, using tabulation - for (int i = 2; i <= n; i++) - { - cat[i] = 0; - for (int j = 0; j < i; j++) - cat[i] += cat[j] * cat[i-j-1]; // applying the definition here - } + for (int i = 2; i <= n; i++) + { + cat[i] = 0; + for (int j = 0; j < i; j++) + cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here + } // Return the result - return cat[n]; + return cat[n]; } int main(int argc, char *argv[]) { - int n; - cout << "Enter n: "; - cin >> n; + int n; + cout << "Enter n: "; + cin >> n; - cat = new int[n+1]; + cat = new int[n + 1]; - cout << "Catalan numbers from 0 to " << n << " are:\n"; - for (int i = 0; i <= n; i++) + cout << "Catalan numbers from 0 to " << n << " are:\n"; + for (int i = 0; i <= n; i++) { - cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; - // NOTE: Since `cat` is a global array, calling `catalan_dp` + cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; + // NOTE: Since `cat` is a global array, calling `catalan_dp` // repeatedly will not recompute the the values already computed - // as in case of pre-computed values, the array will simply return them, + // as in case of pre-computed values, the array will simply return them, // instead of recomputing them. } - return 0; + return 0; } /** Sample Test Case: diff --git a/dynamic_programming/Coin-Change.cpp b/dynamic_programming/Coin-Change.cpp new file mode 100644 index 000000000..c8acad48e --- /dev/null +++ b/dynamic_programming/Coin-Change.cpp @@ -0,0 +1,50 @@ +#include +#include +using namespace std; + +// Function to find the Minimum number of coins required to get Sum S +int findMinCoins(int arr[], int n, int N) +{ + // dp[i] = no of coins required to get a total of i + int dp[N + 1]; + + // 0 coins are needed for 0 sum + + dp[0] = 0; + + for (int i = 1; i <= N; i++) + { + // initialize minimum number of coins needed to infinity + dp[i] = INT_MAX; + int res = INT_MAX; + + // do for each coin + for (int c = 0; c < n; c++) + { + if (i - arr[c] >= 0) // check if coins doesn't become negative by including it + res = dp[i - arr[c]]; + + // if total can be reached by including current coin c, + // update minimum number of coins needed dp[i] + if (res != INT_MAX) + dp[i] = min(dp[i], res + 1); + } + } + + // The Minimum No of Coins Required for N = dp[N] + return dp[N]; +} + +int main() +{ + // No of Coins We Have + int arr[] = {1, 2, 3, 4}; + int n = sizeof(arr) / sizeof(arr[0]); + + // Total Change Required + int N = 15; + + cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n"; + + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/Cut Rod.cpp b/dynamic_programming/Cut Rod.cpp new file mode 100644 index 000000000..afca3dced --- /dev/null +++ b/dynamic_programming/Cut Rod.cpp @@ -0,0 +1,28 @@ +/*Given a rod of length n inches and an array of prices that +contains prices of all pieces of size smaller than n. Determine +the maximum value obtainable by cutting up the rod and selling +the pieces.*/ + +#include +using namespace std; +int cutrod(int p[], int n) +{ + int r[n + 1]; + r[0] = 0; + for (int j = 0; j < n; j++) + { + int q = INT_MIN; + for (int i = 0; i <= j; i++) + { + q = max(q, p[i] + r[j - i]); + } + r[j + 1] = q; + } + return r[n]; +} +int main() +{ + int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; + cout << cutrod(price, 30); + return 0; +} diff --git a/dynamic_programming/Edit Distance.cpp b/dynamic_programming/Edit Distance.cpp new file mode 100644 index 000000000..996d3272c --- /dev/null +++ b/dynamic_programming/Edit Distance.cpp @@ -0,0 +1,94 @@ +/* Given two strings str1 & str2 + * and below operations that can + * be performed on str1. Find + * minimum number of edits + * (operations) required to convert + * 'str1' into 'str2'/ + * a. Insert + * b. Remove + * c. Replace + * All of the above operations are + * of equal cost + */ + +#include +#include +using namespace std; + +int min(int x, int y, int z) +{ + return min(min(x, y), z); +} + +/* A Naive recursive C++ program to find + * minimum number of operations to convert + * str1 to str2. + * O(3^m) + */ +int editDist(string str1, string str2, int m, int n) +{ + if (m == 0) + return n; + if (n == 0) + return m; + + //If last characters are same then continue + //for the rest of them. + if (str1[m - 1] == str2[n - 1]) + return editDist(str1, str2, m - 1, n - 1); + + //If last not same, then 3 possibilities + //a.Insert b.Remove c. Replace + //Get min of three and continue for rest. + return 1 + min(editDist(str1, str2, m, n - 1), + editDist(str1, str2, m - 1, n), + editDist(str1, str2, m - 1, n - 1)); +} + +/* A DP based program + * O(m x n) + */ +int editDistDP(string str1, string str2, int m, int n) +{ + + //Create Table for SubProblems + int dp[m + 1][n + 1]; + + //Fill d[][] in bottom up manner + for (int i = 0; i <= m; i++) + { + for (int j = 0; j <= n; j++) + { + //If str1 empty. Then add all of str2 + if (i == 0) + dp[i][j] = j; + + //If str2 empty. Then add all of str1 + else if (j == 0) + dp[i][j] = i; + + //If character same. Recur for remaining + else if (str1[i - 1] == str2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + + else + dp[i][j] = 1 + min(dp[i][j - 1], //Insert + dp[i - 1][j], //Remove + dp[i - 1][j - 1] //Replace + ); + } + } + + return dp[m][n]; +} + +int main() +{ + string str1 = "sunday"; + string str2 = "saturday"; + + cout << editDist(str1, str2, str1.length(), str2.length()) << endl; + cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl; + + return 0; +} diff --git a/Dynamic Programming/Egg-Dropping-Puzzle.cpp b/dynamic_programming/Egg-Dropping-Puzzle.cpp similarity index 64% rename from Dynamic Programming/Egg-Dropping-Puzzle.cpp rename to dynamic_programming/Egg-Dropping-Puzzle.cpp index 5b277be26..a441f29cb 100644 --- a/Dynamic Programming/Egg-Dropping-Puzzle.cpp +++ b/dynamic_programming/Egg-Dropping-Puzzle.cpp @@ -6,40 +6,47 @@ #include using namespace std; -int eggDrop(int n, int k) { - int eggFloor[n+1][k+1]; +int eggDrop(int n, int k) +{ + int eggFloor[n + 1][k + 1]; int result; - for(int i=1; i<=n; i++) { + for (int i = 1; i <= n; i++) + { eggFloor[i][1] = 1; //n eggs..1 Floor eggFloor[i][0] = 0; //n eggs..0 Floor } - + // Only one egg available - for(int j=1; j<=k ; j++) { + for (int j = 1; j <= k; j++) + { eggFloor[1][j] = j; } - for(int i=2; i<=n; i++) { - for(int j=2; j<=k; j++) { + for (int i = 2; i <= n; i++) + { + for (int j = 2; j <= k; j++) + { eggFloor[i][j] = INT_MAX; - for(int x=1; x<=j; x++) { + for (int x = 1; x <= j; x++) + { // 1+max(eggBreak[one less egg, lower floors], // eggDoesntBreak[same # of eggs, upper floors]); - result = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]); - if(result < eggFloor[i][j]) + result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + if (result < eggFloor[i][j]) eggFloor[i][j] = result; } } } - + return eggFloor[n][k]; } -int main() { +int main() +{ int n, k; cout << "Enter number of eggs and floors: "; - cin>>n>>k; + cin >> n >> k; cout << "Minimum number of trials in worst case: " << eggDrop(n, k) << endl; return 0; } diff --git a/dynamic_programming/Fibonacci_Bottom_Up.cpp b/dynamic_programming/Fibonacci_Bottom_Up.cpp new file mode 100644 index 000000000..ab5b5b41f --- /dev/null +++ b/dynamic_programming/Fibonacci_Bottom_Up.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; +int fib(int n) +{ + int res[3]; + res[0] = 0; + res[1] = 1; + for (int i = 2; i <= n; i++) + { + res[2] = res[1] + res[0]; + res[0] = res[1]; + res[1] = res[2]; + } + return res[1]; +} +int main(int argc, char const *argv[]) +{ + int n; + cout << "Enter n: "; + cin >> n; + cout << "Fibonacci number is "; + cout << fib(n) << endl; + return 0; +} diff --git a/dynamic_programming/Fibonacci_Top_Down.cpp b/dynamic_programming/Fibonacci_Top_Down.cpp new file mode 100644 index 000000000..9d76366f7 --- /dev/null +++ b/dynamic_programming/Fibonacci_Top_Down.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int arr[1000000]; +int fib(int n) +{ + if (arr[n] == -1) + { + if (n <= 1) + arr[n] = n; + else + arr[n] = fib(n - 1) + fib(n - 2); + } + return arr[n]; +} +int main(int argc, char const *argv[]) +{ + int n; + cout << "Enter n: "; + cin >> n; + for (int i = 0; i < n + 1; ++i) + { + arr[i] = -1; + } + cout << "Fibonacci number is " << fib(n) << endl; + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/Floyd-Warshall.cpp b/dynamic_programming/Floyd-Warshall.cpp new file mode 100644 index 000000000..93ccff62f --- /dev/null +++ b/dynamic_programming/Floyd-Warshall.cpp @@ -0,0 +1,112 @@ +#include +#include +#include + +using namespace std; + +//Wrapper class for storing a graph +class Graph +{ +public: + int vertexNum; + int **edges; + + //Constructs a graph with V vertices and E edges + Graph(int V) + { + this->vertexNum = V; + this->edges = (int **)malloc(V * sizeof(int *)); + for (int i = 0; i < V; i++) + { + this->edges[i] = (int *)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) + this->edges[i][j] = INT_MAX; + this->edges[i][i] = 0; + } + } + + //Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + this->edges[src][dst] = weight; + } +}; + +//Utility function to print distances +void print(int dist[], int V) +{ + cout << "\nThe Distance matrix for Floyd - Warshall" << endl; + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { + + if (dist[i * V + j] != INT_MAX) + cout << dist[i * V + j] << "\t"; + else + cout << "INF" + << "\t"; + } + cout << endl; + } +} + +//The main function that finds the shortest path from a vertex +//to all other vertices using Floyd-Warshall Algorithm. +void FloydWarshall(Graph graph) +{ + int V = graph.vertexNum; + int dist[V][V]; + + //Initialise distance array + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) + dist[i][j] = graph.edges[i][j]; + + //Calculate distances + for (int k = 0; k < V; k++) + //Choose an intermediate vertex + + for (int i = 0; i < V; i++) + //Choose a source vertex for given intermediate + + for (int j = 0; j < V; j++) + //Choose a destination vertex for above source vertex + + if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) + //If the distance through intermediate vertex is less than direct edge then update value in distance array + dist[i][j] = dist[i][k] + dist[k][j]; + + //Convert 2d array to 1d array for print + int dist1d[V * V]; + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) + dist1d[i * V + j] = dist[i][j]; + + print(dist1d, V); +} + +//Driver Function +int main() +{ + int V, E; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + FloydWarshall(G); + + return 0; +} diff --git a/dynamic_programming/Longest Common Subsequence.cpp b/dynamic_programming/Longest Common Subsequence.cpp new file mode 100644 index 000000000..af50720b4 --- /dev/null +++ b/dynamic_programming/Longest Common Subsequence.cpp @@ -0,0 +1,82 @@ +//Longest common subsequence - Dynamic Programming +#include +using namespace std; + +void Print(int trace[20][20], int m, int n, string a) +{ + if (m == 0 || n == 0) + { + return; + } + if (trace[m][n] == 1) + { + Print(trace, m - 1, n - 1, a); + cout << a[m - 1]; + } + else if (trace[m][n] == 2) + { + Print(trace, m - 1, n, a); + } + else if (trace[m][n] == 3) + { + Print(trace, m, n - 1, a); + } +} + +int lcs(string a, string b) +{ + int m = a.length(), n = b.length(); + int res[m + 1][n + 1]; + int trace[20][20]; + + // fills up the arrays with zeros. + for (int i = 0; i < m + 1; i++) + { + for (int j = 0; j < n + 1; j++) + { + res[i][j] = 0; + trace[i][j] = 0; + } + } + + for (int i = 0; i < m + 1; ++i) + { + for (int j = 0; j < n + 1; ++j) + { + if (i == 0 || j == 0) + { + res[i][j] = 0; + trace[i][j] = 0; + } + + else if (a[i - 1] == b[j - 1]) + { + res[i][j] = 1 + res[i - 1][j - 1]; + trace[i][j] = 1; // 1 means trace the matrix in upper left diagonal direction. + } + else + { + if (res[i - 1][j] > res[i][j - 1]) + { + res[i][j] = res[i - 1][j]; + trace[i][j] = 2; // 2 means trace the matrix in upwards direction. + } + else + { + res[i][j] = res[i][j - 1]; + trace[i][j] = 3; // means trace the matrix in left direction. + } + } + } + } + Print(trace, m, n, a); + return res[m][n]; +} + +int main() +{ + string a, b; + cin >> a >> b; + cout << lcs(a, b); + return 0; +} diff --git a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp new file mode 100644 index 000000000..5ee24e6a7 --- /dev/null +++ b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp @@ -0,0 +1,46 @@ +//Program to calculate length of longest increasing subsequence in an array +// in O(n log n) +// tested on : https://cses.fi/problemset/task/1145/ + +#include + +using namespace std; +int LIS(int arr[], int n) +{ + set < int > active; // The current built LIS. + active.insert(arr[0]); + // Loop through every element. + for (int i = 1; i < n; ++i) + { + auto get = active.lower_bound(arr[i]); + if (get == active.end()) + { + active.insert(arr[i]); + } // current element is the greatest so LIS increases by 1. + else + { + int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing + if (val > arr[i]) + { + // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; + active.erase(get); + active.insert(arr[i]); + } + } + } + return active.size(); // size of the LIS. +} +int main(int argc, char const * argv[]) +{ + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; +} diff --git a/Dynamic Programming/Longest Increasing Subsequence.cpp b/dynamic_programming/Longest Increasing Subsequence.cpp similarity index 67% rename from Dynamic Programming/Longest Increasing Subsequence.cpp rename to dynamic_programming/Longest Increasing Subsequence.cpp index e2d6111c8..49c54a941 100644 --- a/Dynamic Programming/Longest Increasing Subsequence.cpp +++ b/dynamic_programming/Longest Increasing Subsequence.cpp @@ -1,7 +1,8 @@ //Program to calculate length of longest increasing subsequence in an array #include using namespace std; -int LIS(int a[],int n){ +int LIS(int a[], int n) +{ int lis[n]; for (int i = 0; i < n; ++i) { @@ -11,28 +12,28 @@ int LIS(int a[],int n){ { for (int j = 0; j < i; ++j) { - if(a[i]>a[j] && lis[i] a[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } } int res = 0; for (int i = 0; i < n; ++i) { - res = max(res,lis[i]); + res = max(res, lis[i]); } return res; } int main(int argc, char const *argv[]) { int n; - cout<<"Enter size of array: "; - cin>>n; + cout << "Enter size of array: "; + cin >> n; int a[n]; - cout<<"Enter array elements: "; + cout << "Enter array elements: "; for (int i = 0; i < n; ++i) { - cin>>a[i]; + cin >> a[i]; } - cout< +#include +using namespace std; + +#define MAX 10 + +// dp table to store the solution for already computed sub problems +int dp[MAX][MAX]; + +// Function to find the most efficient way to multiply the given sequence of matrices +int MatrixChainMultiplication(int dim[], int i, int j) +{ + // base case: one matrix + if (j <= i + 1) + return 0; + + // stores minimum number of scalar multiplications (i.e., cost) + // needed to compute the matrix M[i+1]...M[j] = M[i..j] + int min = INT_MAX; + + // if dp[i][j] is not calculated (calculate it!!) + + if (dp[i][j] == 0) + { + // take the minimum over each possible position at which the + // sequence of matrices can be split + + for (int k = i + 1; k <= j - 1; k++) + { + // recur for M[i+1]..M[k] to get a i x k matrix + int cost = MatrixChainMultiplication(dim, i, k); + + // recur for M[k+1]..M[j] to get a k x j matrix + cost += MatrixChainMultiplication(dim, k, j); + + // cost to multiply two (i x k) and (k x j) matrix + cost += dim[i] * dim[k] * dim[j]; + + if (cost < min) + min = cost; // store the minimum cost + } + dp[i][j] = min; + } + + // return min cost to multiply M[j+1]..M[j] + return dp[i][j]; +} + +// main function +int main() +{ + // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n + // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix + int dim[] = {10, 30, 5, 60}; + int n = sizeof(dim) / sizeof(dim[0]); + + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending); + + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) << "\n"; + + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp new file mode 100644 index 000000000..4dba89a27 --- /dev/null +++ b/dynamic_programming/armstrong_number.cpp @@ -0,0 +1,21 @@ +// Program to check whether a number is an armstrong number or not +#include + +using std::cout; +using std::cin; + +int main() { + int n, k, d, s = 0; + cout << "Enter a number:"; + cin >> n; + k = n; + while (k != 0) { + d = k % 10; + s += d * d * d; + k /= 10; + } + if (s == n) + cout << n << "is an armstrong number"; + else + cout << n << "is not an armstrong number"; +} diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp new file mode 100644 index 000000000..bf2aa76ac --- /dev/null +++ b/dynamic_programming/kadane.cpp @@ -0,0 +1,30 @@ +#include +#include + +int maxSubArraySum(int a[], int size) { + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + + +int main() { + int n, i; + std::cout << "Enter the number of elements \n"; + std::cin >> n; + int a[n]; // NOLINT + for (i = 0; i < n; i++) { + std::cin >> a[i]; + } + int max_sum = maxSubArraySum(a, n); + std::cout << "Maximum contiguous sum is " << max_sum; + return 0; +} diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp new file mode 100644 index 000000000..c1e89d6db --- /dev/null +++ b/dynamic_programming/longest_common_string.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +int max(int a,int b) +{ + return (a > b) ? a : b; +} + +int main() +{ + char str1[]="DEFBCD"; + char str2[]="ABDEFJ"; + int i,j,k; + int n=strlen(str1)+1; + int m=strlen(str2)+1; + //cout<ma) + { + ma=a[i][j]; + indi=i; + indj=j; + } + } + } + + cout< + +// this is main fuction +// *** +int main() { + int64_t r, mr = 0, x, q, i, z; + std::cout << "Enter Number of array you want to Store :"; + std::cin >> x; + std::cout << "Enter Number of "; + std::cout << "Question or Quary you "; + std::cout << "want to do Related to Array :"; + std::cin >> q; + // create a Array in run time because use can + // change the size of each array which he/she is going to store + // create a 2D array + int** ar = new int* [x](); + // this for loop is use for entering different variable size array + // *** + for (r = 0; r < x; r++) { + std::cout << "Enter number of element in " << r + 1 << " rows :"; + std::cin >> mr; + // creating a 1D array + int* ac = new int[mr](); + std::cout << "Enter the element of Array "; + // this for loop is use for storing values in array + // *** + for (i = 0; i < mr; i++) { + // entering the value of rows in array in Horizontal + std::cin >> ac[i]; + } + // Change the position of Array so that new arrays entery will be done + ar[r] = ac; + } + // this for loop is use for display result of querry + // *** + for (z = 0; z < q; z++) { + int64_t r1 = 0, q1 = 0; + std::cout << "enter the number of row which element you want to find :"; + std::cin >> r1; + r1 = r1 - 1; + std::cout << "enter the position of element which you want to find :"; + std::cin >> q1; + q1 = q1 - 1; + // use this to find desire position of element in desire array + std::cout <<"The element is "<< ar[r1][q1] < +#include + +// global declarations +// no of nodes max limit. +const int MAX = 1e5; +// adjacency list +std::vector adj[MAX]; +std::vector visited; +std::vector dp; + +void depth_first_search(int u) { + visited[u] = true; + int child_height = 1; + for (int v : adj[u]) { + if (!visited[v]) { + depth_first_search(v); + + // select maximum sub-tree height from all children. + child_height = std::max(child_height, dp[v]+1); + } + } + // assigned the max child height to current visited node. + dp[u] = child_height; +} + +int main() { + // number of nodes + int number_of_nodes; + std::cout << "Enter number of nodes of the tree : " << std::endl; + std::cin >> number_of_nodes; + + // u, v denotes an undirected edge of tree. + int u, v; + // Tree contains exactly n-1 edges where n denotes the number of nodes. + std::cout << "Enter edges of the tree : " << std::endl; + for (int i = 0; i < number_of_nodes - 1; i++) { + std::cin >> u >> v; + // undirected tree u -> v and v -> u. + adj[u].push_back(v); + adj[v].push_back(u); + } + // initialize all nodes as unvisited. + visited.assign(number_of_nodes+1, false); + // initialize depth of all nodes to 0. + dp.assign(number_of_nodes+1, 0); + // function call which will initialize the height of all nodes. + depth_first_search(1); + std::cout << "Height of the Tree : " << dp[1] << std::endl; +} diff --git a/graph/BFS.cpp b/graph/BFS.cpp new file mode 100644 index 000000000..e4e12886b --- /dev/null +++ b/graph/BFS.cpp @@ -0,0 +1,73 @@ +#include +using namespace std; +class graph +{ + int v; + list *adj; + +public: + graph(int v); + void addedge(int src, int dest); + void printgraph(); + void bfs(int s); +}; +graph::graph(int v) +{ + this->v = v; + this->adj = new list[v]; +} +void graph::addedge(int src, int dest) +{ + src--; + dest--; + adj[src].push_back(dest); + //adj[dest].push_back(src); +} +void graph::printgraph() +{ + for (int i = 0; i < this->v; i++) + { + cout << "Adjacency list of vertex " << i + 1 << " is \n"; + list::iterator it; + for (it = adj[i].begin(); it != adj[i].end(); ++it) + { + cout << *it + 1 << " "; + } + cout << endl; + } +} +void graph::bfs(int s) +{ + bool *visited = new bool[this->v + 1]; + memset(visited, false, sizeof(bool) * (this->v + 1)); + visited[s] = true; + list q; + q.push_back(s); + list::iterator it; + while (!q.empty()) + { + int u = q.front(); + cout << u << " "; + q.pop_front(); + for (it = adj[u].begin(); it != adj[u].end(); ++it) + { + if (visited[*it] == false) + { + visited[*it] = true; + q.push_back(*it); + } + } + } +} +int main() +{ + graph g(4); + g.addedge(1, 2); + g.addedge(2, 3); + g.addedge(3, 4); + g.addedge(1, 4); + g.addedge(1, 3); + //g.printgraph(); + g.bfs(2); + return 0; +} diff --git a/graph/DFS.cpp b/graph/DFS.cpp new file mode 100644 index 000000000..656711ac8 --- /dev/null +++ b/graph/DFS.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +int v = 4; +void DFSUtil_(int graph[4][4], bool visited[], int s) +{ + visited[s] = true; + cout << s << " "; + for (int i = 0; i < v; i++) + { + if (graph[s][i] == 1 && visited[i] == false) + { + DFSUtil_(graph, visited, i); + } + } +} + +void DFS_(int graph[4][4], int s) +{ + bool visited[v]; + memset(visited, 0, sizeof(visited)); + DFSUtil_(graph, visited, s); +} + +int main() +{ + int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; + cout << "DFS: "; + DFS_(graph, 2); + cout << endl; + return 0; +} \ No newline at end of file diff --git a/Graph/DFS_with_stack.cc b/graph/DFS_with_stack.cc similarity index 52% rename from Graph/DFS_with_stack.cc rename to graph/DFS_with_stack.cc index 37ee50a5f..cc67c7509 100644 --- a/Graph/DFS_with_stack.cc +++ b/graph/DFS_with_stack.cc @@ -2,7 +2,6 @@ #include #include - #define WHITE 0 #define GREY 1 #define BLACK 2 @@ -12,23 +11,27 @@ using namespace std; int checked[999] = {WHITE}; -void dfs(const list lista[], int start) { +void dfs(const list lista[], int start) +{ stack stack; int checked[999] = {WHITE}; - + stack.push(start); - + checked[start] = GREY; - while(!stack.empty()) { + while (!stack.empty()) + { int act = stack.top(); stack.pop(); - if(checked[act] == GREY) { + if (checked[act] == GREY) + { cout << act << ' '; - for(auto it = lista[act].begin(); it != lista[act].end(); ++it) { + for (auto it = lista[act].begin(); it != lista[act].end(); ++it) + { stack.push(*it); - if(checked[*it] != BLACK) + if (checked[*it] != BLACK) checked[*it] = GREY; } checked[act] = BLACK; //nodo controllato @@ -36,18 +39,19 @@ void dfs(const list lista[], int start) { } } -int main() { - int u, w; - int n; - cin >> n; - list lista[INF]; - for(int i = 0; i < n; ++i) { - cin >> u >> w; - lista[u].push_back(w); - } +int main() +{ + int u, w; + int n; + cin >> n; + list lista[INF]; + for (int i = 0; i < n; ++i) + { + cin >> u >> w; + lista[u].push_back(w); + } - dfs(lista, 0); - + dfs(lista, 0); - return 0; + return 0; } diff --git a/graph/Dijkstra.cpp b/graph/Dijkstra.cpp new file mode 100644 index 000000000..b3ee44c41 --- /dev/null +++ b/graph/Dijkstra.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +using namespace std; +#define INF 10000010 +vector> graph[5 * 100001]; +int dis[5 * 100001]; +int dij(vector> *v, int s, int *dis) +{ + priority_queue, vector>, greater>> pq; + // source distance to zero. + pq.push(make_pair(0, s)); + dis[s] = 0; + int u; + while (!pq.empty()) + { + u = (pq.top()).second; + pq.pop(); + for (vector>::iterator it = v[u].begin(); it != v[u].end(); it++) + { + if (dis[u] + it->first < dis[it->second]) + { + dis[it->second] = dis[u] + it->first; + pq.push(make_pair(dis[it->second], it->second)); + } + } + } +} +int main() +{ + int m, n, l, x, y, s; + // n--> number of nodes , m --> number of edges + cin >> n >> m; + for (int i = 0; i < m; i++) + { + // input edges. + scanf("%d%d%d", &x, &y, &l); + graph[x].push_back(make_pair(l, y)); + graph[y].push_back(make_pair(l, x)); // comment this line for directed graph + } + // start node. + scanf("%d", &s); + // intialise all distances to infinity. + for (int i = 1; i <= n; i++) + dis[i] = INF; + dij(graph, s, dis); + + for (int i = 1; i <= n; i++) + if (dis[i] == INF) + cout << "-1 "; + else + cout << dis[i] << " "; + return 0; +} diff --git a/graph/Kruskal.cpp b/graph/Kruskal.cpp new file mode 100644 index 000000000..21b04ce49 --- /dev/null +++ b/graph/Kruskal.cpp @@ -0,0 +1,135 @@ +#include +//#include +//using namespace boost::multiprecision; +const int mx = 1e6 + 5; +const long int inf = 2e9; +typedef long long ll; +#define rep(i, n) for (i = 0; i < n; i++) +#define repp(i, a, b) for (i = a; i <= b; i++) +#define pii pair +#define vpii vector +#define vi vector +#define vll vector +#define r(x) scanf("%d", &x) +#define rs(s) scanf("%s", s) +#define gc getchar_unlocked +#define pc putchar_unlocked +#define mp make_pair +#define pb push_back +#define lb lower_bound +#define ub upper_bound +#define endl "\n" +#define fast \ + ios_base::sync_with_stdio(false); \ + cin.tie(NULL); \ + cout.tie(NULL); +using namespace std; +void in(int &x) +{ + register int c = gc(); + x = 0; + int neg = 0; + for (; ((c < 48 || c > 57) && c != '-'); c = gc()) + ; + if (c == '-') + { + neg = 1; + c = gc(); + } + for (; c > 47 && c < 58; c = gc()) + { + x = (x << 1) + (x << 3) + c - 48; + } + if (neg) + x = -x; +} +void out(int n) +{ + int N = n, rev, count = 0; + rev = N; + if (N == 0) + { + pc('0'); + return; + } + while ((rev % 10) == 0) + { + count++; + rev /= 10; + } + rev = 0; + while (N != 0) + { + rev = (rev << 3) + (rev << 1) + N % 10; + N /= 10; + } + while (rev != 0) + { + pc(rev % 10 + '0'); + rev /= 10; + } + while (count--) + pc('0'); +} +ll parent[mx], arr[mx], node, edge; +vector>> v; +void initial() +{ + int i; + rep(i, node + edge) + parent[i] = i; +} +int root(int i) +{ + while (parent[i] != i) + { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + return i; +} +void join(int x, int y) +{ + int root_x = root(x); //Disjoint set union by rank + int root_y = root(y); + parent[root_x] = root_y; +} +ll kruskal() +{ + ll mincost = 0, i, x, y; + rep(i, edge) + { + x = v[i].second.first; + y = v[i].second.second; + if (root(x) != root(y)) + { + mincost += v[i].first; + join(x, y); + } + } + return mincost; +} +int main() +{ + fast; + while (1) + { + int i, j, from, to, cost, totalcost = 0; + cin >> node >> edge; //Enter the nodes and edges + if (node == 0 && edge == 0) + break; //Enter 0 0 to break out + initial(); //Initialise the parent array + rep(i, edge) + { + cin >> from >> to >> cost; + v.pb(mp(cost, mp(from, to))); + totalcost += cost; + } + sort(v.begin(), v.end()); + // rep(i,v.size()) + // cout< #include #include - using namespace std; +using namespace std; -int n , m; // For number of Vertices (V) and number of edges (E) -vector< vector > G; +int n, m; // For number of Vertices (V) and number of edges (E) +vector> G; vector visited; vector ans; -void dfs(int v) { +void dfs(int v) +{ visited[v] = true; - for (int u : G[v]) { + for (int u : G[v]) + { if (!visited[u]) dfs(u); } ans.push_back(v); } - -void topological_sort() { + +void topological_sort() +{ visited.assign(n, false); ans.clear(); - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { if (!visited[i]) dfs(i); } reverse(ans.begin(), ans.end()); } -int main(){ +int main() +{ cout << "Enter the number of vertices and the number of directed edges\n"; cin >> n >> m; - int x , y; - G.resize(n , vector()); - for(int i = 0 ; i < n ; ++i) { + int x, y; + G.resize(n, vector()); + for (int i = 0; i < n; ++i) + { cin >> x >> y; - x-- , y--; // to convert 1-indexed to 0-indexed + x--, y--; // to convert 1-indexed to 0-indexed G[x].push_back(y); } topological_sort(); cout << "Topological Order : \n"; - for(int v : ans) { + for (int v : ans) + { cout << v + 1 << ' '; // converting zero based indexing back to one based. } cout << '\n'; diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp new file mode 100644 index 000000000..2e66f131f --- /dev/null +++ b/graph/kosaraju.cpp @@ -0,0 +1,134 @@ +/* Implementation of Kosaraju's Algorithm to find out the strongly connected components (SCCs) in a graph. + Author:Anirban166 +*/ + +#include +#include + +using namespace std; + +/** +* Iterative function/method to print graph: +* @param a[] : array of vectors (2D) +* @param V : vertices +* @return void +**/ +void print(vector a[],int V) +{ + for(int i=0;i"; + for(int j=0;j &st,bool vis[],vector adj[]) +{ + vis[v]=true; + for(auto i=adj[v].begin();i!=adj[v].end();i++) + { + if(vis[*i]==false) + push_vertex(*i,st,vis,adj); + } + st.push(v); +} + + +/** +* //Recursive function/method to implement depth first traversal(dfs): +* @param v : vertices +* @param vis[] : array to keep track of visited nodes (boolean type) +* @param grev[] : graph with reversed edges +* @return void +**/ +void dfs(int v,bool vis[],vector grev[]) +{ + vis[v]=true; + // cout<0)) + i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) +**/ +int kosaraju(int V, vector adj[]) +{ + bool vis[V]={}; + stack st; + for(int v=0;v grev[V]; + for(int i=0;i level[u]) + { + swap(u, v); + } + // u is at the bottom. + int dist = level[u] - level[v]; + // Go up this much distance + for (int i = LG - 1; i >= 0; --i) + { + if (dist & (1 << i)) + { + u = up[i][u]; + } + } + if (u == v) + { + return u; + } + assert(level[u] == level[v]); + for (int i = LG - 1; i >= 0; --i) + { + if (up[i][u] != up[i][v]) + { + u = up[i][u]; + v = up[i][v]; + } + } + assert(up[0][u] == up[0][v]); + return up[0][u]; + } +}; + +int main() +{ + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given + // n-1 edges of the form + // a b + // Use verify function to see. +} diff --git a/Greedy Algorithms/Dijkstra.cpp b/greedy_algorithms/Dijkstra.cpp similarity index 68% rename from Greedy Algorithms/Dijkstra.cpp rename to greedy_algorithms/Dijkstra.cpp index 05191a279..0c7fffc8c 100644 --- a/Greedy Algorithms/Dijkstra.cpp +++ b/greedy_algorithms/Dijkstra.cpp @@ -15,7 +15,7 @@ public: { // initializes the array edges. - this->edges = new int*[V]; + this->edges = new int *[V]; for (int i = 0; i < V; i++) { edges[i] = new int[V]; @@ -31,7 +31,6 @@ public: } this->vertexNum = V; - } //Adds the given edge to the graph @@ -39,36 +38,33 @@ public: { this->edges[src][dst] = weight; } - - }; //Utility function to find minimum distance vertex in mdist int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; - for(int i=0; i>V; - cout<<"Enter number of edges: "; - cin>>E; + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; Graph G(V); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; // makes sure source and destionation are in the proper bounds. if (src >= 0 && src < V && dst >= 0 && dst < V) @@ -144,9 +137,9 @@ int main() continue; } } - cout<<"\nEnter source:"; - cin>>gsrc; - Dijkstra(G,gsrc); + cout << "\nEnter source:"; + cin >> gsrc; + Dijkstra(G, gsrc); return 0; } diff --git a/greedy_algorithms/Knapsack.cpp b/greedy_algorithms/Knapsack.cpp new file mode 100644 index 000000000..2135bd1eb --- /dev/null +++ b/greedy_algorithms/Knapsack.cpp @@ -0,0 +1,92 @@ +#include +using namespace std; + +struct Item +{ + int weight; + int profit; +}; + +float profitPerUnit(Item x) +{ + return (float)x.profit / (float)x.weight; +} + +int partition(Item arr[], int low, int high) +{ + Item pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j < high; j++) + { + // If current element is smaller than or + // equal to pivot + if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) + { + i++; // increment index of smaller element + Item temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + Item temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); +} + +void quickSort(Item arr[], int low, int high) +{ + if (low < high) + { + + int p = partition(arr, low, high); + + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); + } +} + +int main() +{ + cout << "\nEnter the capacity of the knapsack : "; + float capacity; + cin >> capacity; + cout << "\n Enter the number of Items : "; + int n; + cin >> n; + Item itemArray[n]; + for (int i = 0; i < n; i++) + { + cout << "\nEnter the weight and profit of item " << i + 1 << " : "; + cin >> itemArray[i].weight; + cin >> itemArray[i].profit; + } + + quickSort(itemArray, 0, n - 1); + + // show(itemArray, n); + + float maxProfit = 0; + int i = n; + while (capacity > 0 && --i >= 0) + { + if (capacity >= itemArray[i].weight) + { + maxProfit += itemArray[i].profit; + capacity -= itemArray[i].weight; + cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; + } + else + { + maxProfit += profitPerUnit(itemArray[i]) * capacity; + cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity; + capacity = 0; + break; + } + } + + cout << "\nMax Profit : " << maxProfit; + + return 0; +} diff --git a/Greedy Algorithms/Kruskals Minimum Spanning Tree.cpp b/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp similarity index 59% rename from Greedy Algorithms/Kruskals Minimum Spanning Tree.cpp rename to greedy_algorithms/Kruskals Minimum Spanning Tree.cpp index 40c9d2d41..951d4a88a 100644 --- a/Greedy Algorithms/Kruskals Minimum Spanning Tree.cpp +++ b/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp @@ -4,35 +4,32 @@ using namespace std; #define V 6 #define INFINITY 99999 -int graph[V][V] ={ +int graph[V][V] = { {0, 4, 1, 4, INFINITY, INFINITY}, {4, 0, 3, 8, 3, INFINITY}, {1, 3, 0, INFINITY, 1, INFINITY}, {4, 8, INFINITY, 0, 5, 7}, {INFINITY, 3, 1, 5, 0, INFINITY}, - {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0} -}; - + {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; void findMinimumEdge() { for (int i = 0; i < V; i++) { - int min=INFINITY; - int minIndex=0; + int min = INFINITY; + int minIndex = 0; for (int j = 0; j < V; j++) { - if(graph[i][j]!=0 && graph[i][j] +using namespace std; + +#define V 4 +#define INFINITY 99999 + +int graph[V][V] = { + {0, 5, 1, 2}, + {5, 0, 3, 3}, + {1, 3, 0, 4}, + {2, 3, 4, 0}}; + +struct mst +{ + bool visited; + int key; + int near; +}; + +mst MST_Array[V]; + +void initilize() +{ + for (int i = 0; i < V; i++) + { + MST_Array[i].visited = false; + MST_Array[i].key = INFINITY; // considering INFINITY as inifinity + MST_Array[i].near = i; + } + + MST_Array[0].key = 0; +} + +void updateNear() +{ + for (int v = 0; v < V; v++) + { + int min = INFINITY; + int minIndex = 0; + for (int i = 0; i < V; i++) + { + if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY) + { + min = MST_Array[i].key; + minIndex = i; + } + } + + MST_Array[minIndex].visited = true; + + for (int i = 0; i < V; i++) + { + if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) + { + if (graph[minIndex][i] < MST_Array[i].key) + { + MST_Array[i].key = graph[minIndex][i]; + MST_Array[i].near = minIndex; + } + } + } + } +} + +void show() +{ + for (int i = 0; i < V; i++) + { + cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n"; + } +} + +int main() +{ + initilize(); + updateNear(); + show(); + return 0; +} diff --git a/greedy_algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp new file mode 100644 index 000000000..253d8d0b5 --- /dev/null +++ b/greedy_algorithms/huffman.cpp @@ -0,0 +1,109 @@ +// C++ program for Huffman Coding +#include +#include +using namespace std; + +// A Huffman tree node +struct MinHeapNode { + + // One of the input characters + char data; + + // Frequency of the character + unsigned freq; + + // Left and right child + MinHeapNode *left, *right; + + MinHeapNode(char data, unsigned freq) + + { + + left = right = NULL; + this->data = data; + this->freq = freq; + } +}; + +// For comparison of +// two heap nodes (needed in min heap) +struct compare { + + bool operator()(MinHeapNode* l, MinHeapNode* r) + + { + return (l->freq > r->freq); + } +}; + +// Prints huffman codes from +// the root of Huffman Tree. +void printCodes(struct MinHeapNode* root, string str) +{ + + if (!root) + return; + + if (root->data != '$') + cout << root->data << ": " << str << "\n"; + + printCodes(root->left, str + "0"); + printCodes(root->right, str + "1"); +} + +// The main function that builds a Huffman Tree and +// print codes by traversing the built Huffman Tree +void HuffmanCodes(char data[], int freq[], int size) +{ + struct MinHeapNode *left, *right, *top; + + // Create a min heap & inserts all characters of data[] + priority_queue, compare> minHeap; + + for (int i = 0; i < size; ++i) + minHeap.push(new MinHeapNode(data[i], freq[i])); + + // Iterate while size of heap doesn't become 1 + while (minHeap.size() != 1) { + + // Extract the two minimum + // freq items from min heap + left = minHeap.top(); + minHeap.pop(); + + right = minHeap.top(); + minHeap.pop(); + + // Create a new internal node with + // frequency equal to the sum of the + // two nodes frequencies. Make the + // two extracted node as left and right children + // of this new node. Add this node + // to the min heap '$' is a special value + // for internal nodes, not used + top = new MinHeapNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + minHeap.push(top); + } + + // Print Huffman codes using + // the Huffman tree built above + printCodes(minHeap.top(), ""); +} + +// Driver program to test above functions +int main() +{ + + char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int freq[] = { 5, 9, 12, 13, 16, 45 }; + + int size = sizeof(arr) / sizeof(arr[0]); + + HuffmanCodes(arr, freq, size); + + return 0; +} diff --git a/hashing/Chaining.cpp b/hashing/Chaining.cpp new file mode 100644 index 000000000..55aa8961c --- /dev/null +++ b/hashing/Chaining.cpp @@ -0,0 +1,140 @@ +#include +#include +using namespace std; + +struct Node +{ + int data; + struct Node *next; +} * head[100], *curr; + +void init() +{ + for (int i = 0; i < 100; i++) + head[i] = NULL; +} + +void add(int x, int h) +{ + struct Node *temp = new Node; + temp->data = x; + temp->next = NULL; + if (!head[h]) + { + head[h] = temp; + curr = head[h]; + } + else + { + curr = head[h]; + while (curr->next) + curr = curr->next; + curr->next = temp; + } +} + +void display(int mod) +{ + struct Node *temp; + int i; + for (i = 0; i < mod; i++) + { + if (!head[i]) + { + cout << "Key " << i << " is empty" << endl; + } + else + { + cout << "Key " << i << " has values = "; + temp = head[i]; + while (temp->next) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << temp->data; + cout << endl; + } + } +} + +int hash(int x, int mod) +{ + return x % mod; +} + +void find(int x, int h) +{ + struct Node *temp = head[h]; + if (!head[h]) + { + cout << "Element not found"; + return; + } + while (temp->data != x && temp->next) + temp = temp->next; + if (temp->next) + cout << "Element found"; + else + { + if (temp->data == x) + cout << "Element found"; + else + cout << "Element not found"; + } +} + +int main(void) +{ + init(); + int c, x, mod, h; + cout << "Enter the size of Hash Table. = "; + cin >> mod; + bool loop = true; + while (loop) + { + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add element." << endl; + cout << "2. Find element." << endl; + cout << "3. Generate Hash." << endl; + cout << "4. Display Hash table." << endl; + cout << "5. Exit." << endl; + cin >> c; + switch (c) + { + case 1: + cout << "Enter element to add = "; + cin >> x; + h = hash(x, mod); + h = fabs(h); + add(x, h); + break; + case 2: + cout << "Enter element to search = "; + cin >> x; + h = hash(x, mod); + find(x, h); + break; + case 3: + cout << "Enter element to generate hash = "; + cin >> x; + cout << "Hash of " << x << " is = " << hash(x, mod); + break; + case 4: + display(mod); + break; + default: + loop = false; + break; + } + cout << endl; + } + /*add(1,&head1); + add(2,&head1); + add(3,&head2); + add(5,&head1); + display(&head1); + display(&head2);*/ + return 0; +} \ No newline at end of file diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp new file mode 100644 index 000000000..6030b7ff3 --- /dev/null +++ b/hashing/double_hash_hash_table.cpp @@ -0,0 +1,235 @@ +// Copyright 2019 + +#include +#include +#include +#include + +using std::endl; +using std::cout; +using std::cin; +using std::string; + +// fwd declarations +struct Entry; +bool putProber(Entry entry, int key); +bool searchingProber(Entry entry, int key); +void add(int key); + +// globals +int notPresent; +struct Entry* table; +int totalSize; +int tomb = -1; +int size; +bool rehashing; + +// Node that holds key +struct Entry { + explicit Entry(int key = notPresent) : key(key) {} + int key; +}; + +// Hash a key +int hashFxn(int key) { + std::hash hash; + return hash(key); +} + +// Used for second hash function +int otherHashFxn(int key) { + std::hash hash; + return 1 + (7 - (hash(key) % 7)); +} + +// Performs double hashing to resolve collisions +int doubleHash(int key, bool searching) { + int hash = static_cast(fabs(hashFxn(key))); + int i = 0; + Entry entry; + do { + int index = static_cast(fabs((hash + + (i * otherHashFxn(key))))) % totalSize; + entry = table[index]; + if (searching) { + if (entry.key == notPresent) { + return notPresent; + } + if (searchingProber(entry, key)) { + cout << "Found key!" << endl; + return index; + } + cout << "Found tombstone or equal hash, checking next" << endl; + i++; + } else { + if (putProber(entry, key)) { + if (!rehashing) cout << "Spot found!" << endl; + return index; + } + if (!rehashing) cout << "Spot taken, looking at next (next index:" + << " " << static_cast(fabs((hash + + (i * otherHashFxn(key))))) % totalSize << ")" << endl; + i++; + } + if (i == totalSize * 100) { + cout << "DoubleHash probe failed" << endl; + return notPresent; + } + } while (entry.key != notPresent); + return notPresent; +} + +// Finds empty spot +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { + return true; + } + return false; +} + +// Looks for a matching key +bool searchingProber(Entry entry, int key) { + if (entry.key == key) return true; + return false; +} + +// Displays the table +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { + cout << " Empty "; + } else if (table[i].key == tomb) { + cout << " Tomb "; + } else { + cout << " "; + cout << table[i].key; + cout << " "; + } + } + cout << endl; +} + +// Rehashes the table into a bigger table +void rehash() { + // Necessary so wall of add info isn't printed all at once + rehashing = true; + int oldSize = totalSize; + Entry* oldTable = table; + // Really this should use the next prime number greater than totalSize * 2 + table = new Entry[totalSize * 2]; + totalSize *= 2; + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + size--; // Size stays the same (add increments size) + add(oldTable[i].key); + } + } + delete[] oldTable; + rehashing = false; + cout << "Table was rehashed, new size is: " << totalSize << endl; +} + +// Checks for load factor here +void add(int key) { + Entry * entry = new Entry(); + entry->key = key; + int index = doubleHash(key, false); + table[index] = *entry; + // Load factor greater than 0.5 causes resizing + if (++size/ static_cast(totalSize) >= 0.5) { + rehash(); + } +} + +// Removes key. Leaves tombstone upon removal. +void remove(int key) { + int index = doubleHash(key, true); + if (index == notPresent) { + cout << "key not found" << endl; + } + table[index].key = tomb; + cout << "Removal successful, leaving tombstone" << endl; + size--; +} + +// Information about the adding process +void addInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << endl; + add(key); + cout << "New table: "; + display(); +} + +// Information about removal process +void removalInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << endl; + remove(key); + cout << "New table: "; + display(); +} + +// I/O +int main(void) { + int cmd, hash, key; + cout << "Enter the initial size of Hash Table. = "; + cin >> totalSize; + table = new Entry[totalSize]; + bool loop = true; + while (loop) { + system("pause"); + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add key. (Numeric only)" << endl; + cout << "2. Remove key." << endl; + cout << "3. Find key." << endl; + cout << "4. Generate Hash. (Numeric only)" << endl; + cout << "5. Display Hash table." << endl; + cout << "6. Exit." << endl; + cin >> cmd; + switch (cmd) { + case 1: + cout << "Enter key to add = "; + cin >> key; + addInfo(key); + break; + case 2: + cout << "Enter key to remove = "; + cin >> key; + removalInfo(key); + break; + case 3: { + cout << "Enter key to search = "; + cin >> key; + Entry entry = table[doubleHash(key, true)]; + if (entry.key == notPresent) { + cout << "Key not present"; + } + break; + } + case 4: + cout << "Enter element to generate hash = "; + cin >> key; + cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); + break; + case 5: + display(); + break; + default: + loop = false; + break; + delete[] table; + } + cout << endl; + } + return 0; +} diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp new file mode 100644 index 000000000..b00eb8641 --- /dev/null +++ b/hashing/linear_probing_hash_table.cpp @@ -0,0 +1,226 @@ +// Copyright 2019 + +#include +#include +#include +#include + +using std::endl; +using std::cout; +using std::cin; +using std::string; + +// fwd declarations +struct Entry; +bool putProber(Entry entry, int key); +bool searchingProber(Entry entry, int key); +void add(int key); + +// globals +int notPresent; +struct Entry* table; +int totalSize; +int tomb = -1; +int size; +bool rehashing; + +// Node that holds key +struct Entry { + explicit Entry(int key = notPresent) : key(key) {} + int key; +}; + +// Hash a key +int hashFxn(int key) { + std::hash hash; + return hash(key); +} + +// Performs linear probing to resolve collisions +int linearProbe(int key, bool searching) { + int hash = static_cast(fabs(hashFxn(key))); + int i = 0; + Entry entry; + do { + int index = static_cast(fabs((hash + i) % totalSize)); + entry = table[index]; + if (searching) { + if (entry.key == notPresent) { + return notPresent; + } + if (searchingProber(entry, key)) { + cout << "Found key!" << endl; + return index; + } + cout << "Found tombstone or equal hash, checking next" << endl; + i++; + } else { + if (putProber(entry, key)) { + if (!rehashing) cout << "Spot found!" << endl; + return index; + } + if (!rehashing) cout << "Spot taken, looking at next" << endl; + i++; + } + if (i == totalSize) { + cout << "Linear probe failed" << endl; + return notPresent; + } + } while (entry.key != notPresent); + return notPresent; +} + +// Finds empty spot +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { + return true; + } + return false; +} + +// Looks for a matching key +bool searchingProber(Entry entry, int key) { + if (entry.key == key) return true; + return false; +} + +// Displays the table +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { + cout << " Empty "; + } else if (table[i].key == tomb) { + cout << " Tomb "; + } else { + cout << " "; + cout << table[i].key; + cout << " "; + } + } + cout << endl; +} + +// Rehashes the table into a bigger table +void rehash() { + // Necessary so wall of add info isn't printed all at once + rehashing = true; + int oldSize = totalSize; + Entry* oldTable = table; + // Really this should use the next prime number greater than totalSize * 2 + table = new Entry[totalSize * 2]; + totalSize *= 2; + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + size--; // Size stays the same (add increments size) + add(oldTable[i].key); + } + } + delete[] oldTable; + rehashing = false; + cout << "Table was rehashed, new size is: " << totalSize << endl; +} + +// Adds entry using linear probing. Checks for load factor here +void add(int key) { + Entry * entry = new Entry(); + entry->key = key; + int index = linearProbe(key, false); + table[index] = *entry; + // Load factor greater than 0.5 causes resizing + if (++size/ static_cast(totalSize) >= 0.5) { + rehash(); + } +} + +// Removes key. Leaves tombstone upon removal. +void remove(int key) { + int index = linearProbe(key, true); + if (index == notPresent) { + cout << "key not found" << endl; + } + cout << "Removal Successful, leaving tomb" << endl; + table[index].key = tomb; + size--; +} + +// Information about the adding process +void addInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) << " % " + << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << endl; + add(key); + cout << "New table: "; + display(); +} + +// Information about removal process +void removalInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << endl; + remove(key); + cout << "New table: "; + display(); +} + +// I/O +int main(void) { + int cmd, hash, key; + cout << "Enter the initial size of Hash Table. = "; + cin >> totalSize; + table = new Entry[totalSize]; + bool loop = true; + while (loop) { + system("pause"); + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add key. (Numeric only)" << endl; + cout << "2. Remove key." << endl; + cout << "3. Find key." << endl; + cout << "4. Generate Hash. (Numeric only)" << endl; + cout << "5. Display Hash table." << endl; + cout << "6. Exit." << endl; + cin >> cmd; + switch (cmd) { + case 1: + cout << "Enter key to add = "; + cin >> key; + addInfo(key); + break; + case 2: + cout << "Enter key to remove = "; + cin >> key; + removalInfo(key); + break; + case 3: { + cout << "Enter key to search = "; + cin >> key; + Entry entry = table[linearProbe(key, true)]; + if (entry.key == notPresent) { + cout << "Key not present"; + } + break; + } + case 4: + cout << "Enter element to generate hash = "; + cin >> key; + cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); + break; + case 5: + display(); + break; + default: + loop = false; + break; + delete[] table; + } + cout << endl; + } + return 0; +} diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp new file mode 100644 index 000000000..44e2e3b9f --- /dev/null +++ b/hashing/quadratic_probing_hash_table.cpp @@ -0,0 +1,239 @@ +// Copyright 2019 + +#include +#include +#include +#include +#include + +using std::endl; +using std::cout; +using std::cin; +using std::string; + +// fwd declarations +struct Entry; +bool putProber(Entry entry, int key); +bool searchingProber(Entry entry, int key); +void add(int key); + +// globals +int notPresent; +struct Entry* table; +int totalSize; +int tomb = -1; +int size; +bool rehashing; + +// Node that holds key +struct Entry { + explicit Entry(int key = notPresent) : key(key) {} + int key; +}; + +// Hash a key +int hashFxn(int key) { + std::hash hash; + return hash(key); +} + +// Performs quadratic probing to resolve collisions +int quadraticProbe(int key, bool searching) { + int hash = static_cast(fabs(hashFxn(key))); + int i = 0; + Entry entry; + do { + int index = std::round(fabs((hash + + static_cast(std::round(std::pow(i, 2)))) % totalSize)); + entry = table[index]; + if (searching) { + if (entry.key == notPresent) { + return notPresent; + } + if (searchingProber(entry, key)) { + cout << "Found key!" << endl; + return index; + } + cout << "Found tombstone or equal hash, checking next" << endl; + i++; + } else { + if (putProber(entry, key)) { + if (!rehashing) cout << "Spot found!" << endl; + return index; + } + if (!rehashing) { + cout << "Spot taken, looking at next (next index = " << + std::round(fabs((hash + static_cast(std::round( + std::pow(i + 1, 2)))) % totalSize)) << endl; + } + i++; + } + if (i == totalSize * 100) { + cout << "Quadratic probe failed (infinite loop)" << endl; + return notPresent; + } + } while (entry.key != notPresent); + return notPresent; +} + +// Finds empty spot +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { + return true; + } + return false; +} + +// Looks for a matching key +bool searchingProber(Entry entry, int key) { + if (entry.key == key) return true; + return false; +} + +// Helper +Entry find(int key) { + int index = quadraticProbe(key, true); + if (index == notPresent) return Entry(); + return table[index]; +} + +// Displays the table +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { + cout << " Empty "; + } else if (table[i].key == tomb) { + cout << " Tomb "; + } else { + cout << " "; + cout << table[i].key; + cout << " "; + } + } + cout << endl; +} + +// Rehashes the table into a bigger table +void rehash() { + // Necessary so wall of add info isn't printed all at once + rehashing = true; + int oldSize = totalSize; + Entry* oldTable = table; + // Really this should use the next prime number greater than totalSize * 2 + table = new Entry[totalSize * 2]; + totalSize *= 2; + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + size--; // Size stays the same (add increments size) + add(oldTable[i].key); + } + } + delete[] oldTable; + rehashing = false; + cout << "Table was rehashed, new size is: " << totalSize << endl; +} + +// Checks for load factor here +void add(int key) { + Entry * entry = new Entry(); + entry->key = key; + int index = quadraticProbe(key, false); + table[index] = *entry; + // Load factor greater than 0.5 causes resizing + if (++size/ static_cast(totalSize) >= 0.5) { + rehash(); + } +} + +// Removes key. Leaves tombstone upon removal. +void remove(int key) { + int index = quadraticProbe(key, true); + if (index == notPresent) { + cout << "key not found" << endl; + } + table[index].key = tomb; + cout << "Removal successful, leaving tombstone" << endl; + size--; +} + +// Information about the adding process +void addInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) << " % " + << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << endl; + add(key); + cout << "New table: "; + display(); +} + +// Information about removal process +void removalInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << endl; + remove(key); + cout << "New table: "; + display(); +} + +// I/O +int main(void) { + int cmd, hash, key; + cout << "Enter the initial size of Hash Table. = "; + cin >> totalSize; + table = new Entry[totalSize]; + bool loop = true; + while (loop) { + system("pause"); + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add key. (Numeric only)" << endl; + cout << "2. Remove key." << endl; + cout << "3. Find key." << endl; + cout << "4. Generate Hash. (Numeric only)" << endl; + cout << "5. Display Hash table." << endl; + cout << "6. Exit." << endl; + cin >> cmd; + switch (cmd) { + case 1: + cout << "Enter key to add = "; + cin >> key; + addInfo(key); + break; + case 2: + cout << "Enter key to remove = "; + cin >> key; + removalInfo(key); + break; + case 3: { + cout << "Enter key to search = "; + cin >> key; + Entry entry = table[quadraticProbe(key, true)]; + if (entry.key == notPresent) { + cout << "Key not present"; + } + break; + } + case 4: + cout << "Enter element to generate hash = "; + cin >> key; + cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); + break; + case 5: + display(); + break; + default: + loop = false; + break; + delete[] table; + } + cout << endl; + } + return 0; +} diff --git a/Math/Prime_Factorization/README.md b/math/README.md similarity index 100% rename from Math/Prime_Factorization/README.md rename to math/README.md diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp new file mode 100644 index 000000000..b4551da25 --- /dev/null +++ b/math/binary_exponent.cpp @@ -0,0 +1,60 @@ +/// C++ Program to find Binary Exponent Iteratively and Recursively. + +#include +/* + * Calculate a^b in O(log(b)) by converting b to a binary number. + * Binary exponentiation is also known as exponentiation by squaring. + * NOTE : This is a far better approach compared to naive method which provide O(b) operations. + * Example: + * 10 in base 2 is 1010. + * 2^10 = 2^(1010) = 2^8 * 2^2 + * 2^1 = 2 + * 2^2 = (2^1)^2 = 2^2 = 4 + * 2^4 = (2^2)^2 = 4^2 = 16 + * 2^8 = (2^4)^2 = 16^2 = 256 + * Hence to calculate 2^10 we only need to multiply 2^8 and 2^2 skipping 2^1 and 2^4. +*/ + +/// Recursive function to calculate exponent in O(log(n)) using binary exponent. +int binExpo(int a, int b) { + if (b == 0) { + return 1; + } + int res = binExpo(a, b/2); + if (b%2) { + return res*res*a; + } else { + return res*res; + } +} + +/// Iterative function to calculate exponent in O(log(n)) using binary exponent. +int binExpo_alt(int a, int b) { + int res = 1; + while (b > 0) { + if (b%2) { + res = res*a; + } + a = a*a; + b /= 2; + } + return res; +} + +int main() { + int a, b; + /// Give two numbers a, b + std::cin >> a >> b; + if (a == 0 && b == 0) { + std::cout << "Math error" << std::endl; + } else if (b < 0) { + std::cout << "Exponent must be positive !!" << std::endl; + } else { + int resRecurse = binExpo(a, b); + /// int resIterate = binExpo_alt(a, b); + + /// Result of a^b (where '^' denotes exponentiation) + std::cout << resRecurse << std::endl; + /// std::cout << resIterate << std::endl; + } +} diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp new file mode 100644 index 000000000..31ced5a51 --- /dev/null +++ b/math/eulers_totient_function.cpp @@ -0,0 +1,41 @@ +/// C++ Program to find Euler Totient Function +#include + +/* + * Euler Totient Function is also known as phi function. + * phi(n) = phi(p1^a1).phi(p2^a2)... + * where p1, p2,... are prime factors of n. + * 3 Euler's properties: + * 1. phi(prime_no) = prime_no-1 + * 2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) + * 3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. + * Applying this 3 properties on the first equation. + * phi(n) = n. (1-1/p1). (1-1/p2). ... + * where p1,p2... are prime factors. + * Hence Implementation in O(sqrt(n)). + * phi(100) = 40 + * phi(1) = 1 + * phi(17501) = 15120 + * phi(1420) = 560 + */ + +// Function to caculate Euler's totient phi +int phiFunction(int n) { + int result = n; + for (int i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) { + n /= i; + } + result -= result / i; + } + } + if (n > 1) result -= result / n; + return result; +} + +int main() { + int n; + std::cin >> n; + std::cout << phiFunction(n); +} diff --git a/math/factorial.cpp b/math/factorial.cpp new file mode 100644 index 000000000..8b13eb52d --- /dev/null +++ b/math/factorial.cpp @@ -0,0 +1,17 @@ +// C++ program to find factorial of given number +#include + +// function to find factorial of given number +unsigned int factorial(unsigned int n) { + if (n == 0) + return 1; + return n * factorial(n - 1); +} + +// Driver code +int main() { + int num = 5; + std::cout << "Factorial of " << num << " is " << factorial(num) + << std::endl; + return 0; +} diff --git a/math/fast_power.cpp b/math/fast_power.cpp new file mode 100644 index 000000000..4f6e02081 --- /dev/null +++ b/math/fast_power.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include +#include +#include + +/* + Program that computes a^b in O(logN) time. + It is based on formula that: + case1) if b is even: a^b = a^(b/2) * a^(b/2) = (a^(b/2))ˆ2 + case2) if b is odd: a^b = a^((b-1)/2) * a^((b-1)/2) * a = (a^((b-1)/2))^2 * a + We can compute a^b recursively using above algorithm. +*/ + +double fast_power_recursive(int64_t a, int64_t b) { + // negative power. a^b = 1 / (a^-b) + if (b < 0) + return 1.0 / fast_power_recursive(a, -b); + + if (b == 0) return 1; + int64_t bottom = fast_power_recursive(a, b >> 1); + // Since it is integer division b/2 = (b-1)/2 where b is odd. + // Therefore, case2 is easily solved by integer division. + + int64_t result; + if ((b & 1) == 0) // case1 + result = bottom * bottom; + else // case2 + result = bottom * bottom * a; + return result; +} + +/* + Same algorithm with little different formula. + It still calculates in O(logN) +*/ +double fast_power_linear(int64_t a, int64_t b) { + // negative power. a^b = 1 / (a^-b) + if (b < 0) + return 1.0 / fast_power_linear(a, -b); + + double result = 1; + while (b) { + if (b & 1) result = result * a; + a = a * a; + b = b >> 1; + } + return result; +} + +int main() { + std::srand(time(NULL)); + std::ios_base::sync_with_stdio(false); + + std::cout << "Testing..." << std::endl; + for (int i = 0; i < 20; i++) { + unsigned int *rand1, *rand2; + int a = rand_r(rand1) % 20 - 10; + int b = rand_r(rand2) % 20 - 10; + std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; + assert(fast_power_recursive(a, b) == std::pow(a, b)); + assert(fast_power_linear(a, b) == std::pow(a, b)); + + std::cout << "------ " << a << "^" << b << " = "<< + fast_power_recursive(a, b) << std::endl; + } + + int64_t a, b; + std::cin >> a >> b; + + std::cout << a << "^" << b << " = "<< + fast_power_recursive(a, b) << std::endl; + + std::cout << a << "^" << b << " = "<< + fast_power_linear(a, b) << std::endl; + + return 0; +} diff --git a/math/greatest_common_divisor.cpp b/math/greatest_common_divisor.cpp new file mode 100644 index 000000000..5601c4be9 --- /dev/null +++ b/math/greatest_common_divisor.cpp @@ -0,0 +1,27 @@ +// C++ program to find GCD of two numbers +#include + +// Recursive function to return gcd of a and b +int gcd(int a, int b) { + // Everything divides 0 + if (a == 0) + return b; + if (b == 0) + return a; + + // base case + if (a == b) + return a; + + // a is greater + if (a > b) + return gcd(a-b, b); + return gcd(a, b-a); +} + +// Driver program to test above function +int main() { + int a = 98, b = 56; + std::cout << "GCD of " << a << " and " << b << " is " << gcd(a, b); + return 0; +} diff --git a/math/greatest_common_divisor_euclidean.cpp b/math/greatest_common_divisor_euclidean.cpp new file mode 100644 index 000000000..c4812e45b --- /dev/null +++ b/math/greatest_common_divisor_euclidean.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +// will find the greatest common denominator of two ints integers +// Euclidean algorithm can be found here +// https://en.wikipedia.org/wiki/Euclidean_algorithm +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { + throw std::domain_error("Euclidean algorithm domain is for ints > 0"); + } + + if (num1 == num2) { + return num1; + } + + int base_num = 0; + int previous_remainder = 1; + + if (num1 > num2) { + base_num = num1; + previous_remainder = num2; + } else { + base_num = num2; + previous_remainder = num1; + } + + while ((base_num % previous_remainder) != 0) { + int old_base = base_num; + base_num = previous_remainder; + previous_remainder = old_base % previous_remainder; + } + + return previous_remainder; +} + +int main() { + std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; + try { + std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; + } catch (const std::domain_error &e) { + std::cout << "Error handling was successful" << std::endl; + } + std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; + std::cout << "gcd of 289,204 is " << (gcd(289, 204)) << std::endl; + + return 0; +} diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp new file mode 100644 index 000000000..48ab63c36 --- /dev/null +++ b/math/number_of_positive_divisors.cpp @@ -0,0 +1,66 @@ +/// C++ Program to calculate number of divisors. + +#include +#include + +/** + * This algorithm use the prime factorization approach. + * Any number can be written in multiplication of its prime factors. + * Let N = P1^E1 * P2^E2 ... Pk^Ek + * Therefore. number-of-divisors(N) = (E1+1) * (E2+1) ... (Ek+1). + * Where P1, P2 ... Pk are prime factors and E1, E2 ... Ek are exponents respectively. + * + * Example:- + * N = 36 + * 36 = (3^2 * 2^2) + * number_of_positive_divisors(36) = (2+1) * (2+1) = 9. + * list of positive divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + * + * Similarly if N is -36 at that time number of positive divisors remain same. + * + * Example:- + * N = -36 + * -36 = -1 * (3^2 * 2^2) + * number_of_positive_divisors(-36) = (2+1) * (2+1) = 9. + * list of positive divisors of -36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + * +**/ + +int number_of_positive_divisors(int n) { + std::vector prime_exponent_count; + for (int i=2; i*i <= n; i++) { + int prime_count = 0; + while (n % i == 0) { + prime_count += 1; + n /= i; + } + if (prime_count != 0) { + prime_exponent_count.push_back(prime_count); + } + } + if (n > 1) { + prime_exponent_count.push_back(1); + } + + int divisors_count = 1; + + for (int i=0; i < prime_exponent_count.size(); i++) { + divisors_count = divisors_count * (prime_exponent_count[i]+1); + } + + return divisors_count; +} + +int main() { + int n; + std::cin >> n; + if (n < 0) { + n = -n; + } + if (n == 0) { + std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; + } else { + std::cout << "Number of positive divisors is : "; + std::cout << number_of_positive_divisors(n) << std::endl; + } +} diff --git a/Math/Power_For_Huge_Num/Power_Huge.cpp b/math/power_for_huge_numbers.cpp similarity index 89% rename from Math/Power_For_Huge_Num/Power_Huge.cpp rename to math/power_for_huge_numbers.cpp index 02f01dc50..bf9374228 100644 --- a/Math/Power_For_Huge_Num/Power_Huge.cpp +++ b/math/power_for_huge_numbers.cpp @@ -14,14 +14,16 @@ using namespace std; // for multiplication. // This function may value of res_size // and returns the new value of res_size -int multiply(int x, int res[], int res_size) { +int multiply(int x, int res[], int res_size) +{ // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] - for (int i = 0; i < res_size; i++) { + for (int i = 0; i < res_size; i++) + { int prod = res[i] * x + carry; // Store last digit of @@ -34,7 +36,8 @@ int multiply(int x, int res[], int res_size) { // Put carry in res and // increase result size - while (carry) { + while (carry) + { res[res_size] = carry % 10; carry = carry / 10; res_size++; @@ -48,18 +51,19 @@ void power(int x, int n) { //printing value "1" for power = 0 - if(n == 0 ){ - cout<<"1"; + if (n == 0) + { + cout << "1"; return; } - int res[MAX]; int res_size = 0; int temp = x; // Initialize result - while (temp != 0) { + while (temp != 0) + { res[res_size++] = temp % 10; temp = temp / 10; } @@ -75,7 +79,8 @@ void power(int x, int n) } // Driver program -int main() { +int main() +{ int exponent, base; printf("Enter base "); scanf("%id \n", &base); diff --git a/Math/Prime_Factorization/primefactorization.cpp b/math/prime_factorization.cpp similarity index 64% rename from Math/Prime_Factorization/primefactorization.cpp rename to math/prime_factorization.cpp index b903a166a..822cad332 100644 --- a/Math/Prime_Factorization/primefactorization.cpp +++ b/math/prime_factorization.cpp @@ -6,7 +6,7 @@ using namespace std; // Declaring variables for maintaing prime numbers and to check whether a number is prime or not bool isprime[1000006]; vector prime_numbers; -vector > factors; +vector> factors; // Calculating prime number upto a given range void SieveOfEratosthenes(int N) @@ -14,21 +14,20 @@ void SieveOfEratosthenes(int N) // initializes the array isprime memset(isprime, true, sizeof isprime); - for(int i=2; i<=N ; i++) + for (int i = 2; i <= N; i++) { - if(isprime[i]) + if (isprime[i]) { - for(int j=2*i; j<=N; j+=i) - isprime[j]=false; + for (int j = 2 * i; j <= N; j += i) + isprime[j] = false; } } - for(int i=2; i<=N; i++) + for (int i = 2; i <= N; i++) { - if(isprime[i]) + if (isprime[i]) prime_numbers.push_back(i); } - } // Prime factorization of a number @@ -37,9 +36,9 @@ void prime_factorization(int num) int number = num; - for(int i=0; prime_numbers[i]<=num; i++) + for (int i = 0; prime_numbers[i] <= num; i++) { - int count=0; + int count = 0; // termination condition if (number == 1) @@ -47,17 +46,15 @@ void prime_factorization(int num) break; } - while(number%prime_numbers[i] == 0) + while (number % prime_numbers[i] == 0) { count++; - number = number/prime_numbers[i]; + number = number / prime_numbers[i]; } - if(count) - factors.push_back(make_pair(prime_numbers[i],count)); + if (count) + factors.push_back(make_pair(prime_numbers[i], count)); } - - } /* @@ -68,16 +65,16 @@ int main() int num; cout << "\t\tComputes the prime factorization\n\n"; cout << "Type in a number: "; - cin>>num; + cin >> num; SieveOfEratosthenes(num); prime_factorization(num); // Prime factors with their powers in the given number in new line - for(auto it: factors) + for (auto it : factors) { - cout< +#include + +std::vector primes(int max) { + max++; + std::vector res; + std::vector numbers(max, false); + for (int i = 2; i < max; i++) { + if (!numbers[i]) { + for (int j = i; j < max; j += i) + numbers[j] = true; + res.push_back(i); + } + } + return res; +} + +int main() { + std::cout << "Calculate primes up to:\n>> "; + int n; + std::cin >> n; + std::vector ans = primes(n); + for (int i = 0; i < ans.size(); i++) + std::cout << ans[i] << ' '; + std::cout << std::endl; +} diff --git a/math/primes_up_to_10^8.cpp b/math/primes_up_to_10^8.cpp new file mode 100644 index 000000000..db9b56cab --- /dev/null +++ b/math/primes_up_to_10^8.cpp @@ -0,0 +1,27 @@ +#include +#include + +char prime[100000000]; + +void Sieve(int64_t n) { + memset(prime, '1', sizeof(prime)); // intitize '1' to every index + prime[0] = '0'; // 0 is not prime + prime[1] = '0'; // 1 is not prime + for (int p = 2; p * p <= n; p++) { + if (prime[p] == '1') { + for (int i = p * p; i <= n; i += p) + prime[i] = '0'; // set all multiples of p to false + } + } +} + + +int main() { + Sieve(100000000); + int64_t n; + std::cin >> n; // 10006187 + if (prime[n] == '1') + std::cout << "YES\n"; + else + std::cout << "NO\n"; +} diff --git a/Math/sieve_of_Eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp similarity index 70% rename from Math/sieve_of_Eratosthenes.cpp rename to math/sieve_of_eratosthenes.cpp index 30fd369ea..e600e480d 100644 --- a/Math/sieve_of_Eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -17,12 +17,16 @@ int isprime[MAX]; * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(int N) { +void sieve(int N) +{ isprime[0] = 0; isprime[1] = 0; - for (int i = 2; i <= N; i++) { - if (isprime[i]) { - for (int j = i * 2; j <= N; j += i) { + for (int i = 2; i <= N; i++) + { + if (isprime[i]) + { + for (int j = i * 2; j <= N; j += i) + { isprime[j] = 0; } } @@ -32,9 +36,12 @@ void sieve(int N) { /* * This function prints out the primes to STDOUT */ -void print(int N) { - for (int i = 1; i <= N; i++) { - if (isprime[i] == 1) { +void print(int N) +{ + for (int i = 1; i <= N; i++) + { + if (isprime[i] == 1) + { cout << i << ' '; } } @@ -45,13 +52,16 @@ void print(int N) { * NOTE: This function is important for the * initialization of the array. */ -void init() { - for (int i = 1; i < MAX; i++) { +void init() +{ + for (int i = 1; i < MAX; i++) + { isprime[i] = 1; } } -int main() { +int main() +{ int N = 100; init(); sieve(N); diff --git a/operations_on_datastructures/Array Left Rotation.cpp b/operations_on_datastructures/Array Left Rotation.cpp new file mode 100644 index 000000000..9eb5d4e50 --- /dev/null +++ b/operations_on_datastructures/Array Left Rotation.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; +int main() +{ + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + } + int temp = 0; + for (int i = 0; i < k; i++) + { + temp = a[0]; + for (int j = 0; j < n; j++) + { + if (j == n - 1) + { + a[n - 1] = temp; + } + else + { + a[j] = a[j + 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int j = 0; j < n; j++) + { + cout << a[j] << " "; + } + getchar(); + return 0; +} diff --git a/operations_on_datastructures/Array Right Rotation.cpp b/operations_on_datastructures/Array Right Rotation.cpp new file mode 100644 index 000000000..81875766c --- /dev/null +++ b/operations_on_datastructures/Array Right Rotation.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; +int main() +{ + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indices u want to rotate the array to right=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) + cin >> a[i]; + int temp = 0; + for (int i = 0; i < k; i++) + { + temp = a[n - 1]; + for (int j = n - 1; j >= 0; j--) + { + if (j == 0) + { + a[j] = temp; + } + else + { + a[j] = a[j - 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int i = 0; i < n; i++) + { + cout << a[i] << " "; + } +} diff --git a/operations_on_datastructures/Circular Linked List.cpp b/operations_on_datastructures/Circular Linked List.cpp new file mode 100644 index 000000000..d360f6cd7 --- /dev/null +++ b/operations_on_datastructures/Circular Linked List.cpp @@ -0,0 +1,114 @@ +#include +using namespace std; + +struct node +{ + int val; + node *next; +}; + +node *start; + +void insert(int x) +{ + node *t = start; + + if (start != NULL) + { + while (t->next != start) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = start; + } + else + { + node *n = new node; + n->val = x; + start = n; + n->next = start; + } +} + +void remove(int x) +{ + node *t = start; + node *p; + while (t->val != x) + { + p = t; + t = t->next; + } + p->next = t->next; + delete t; +} + +void search(int x) +{ + node *t = start; + int found = 0; + while (t->next != start) + { + if (t->val == x) + { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + cout << "\nNot Found"; + } +} + +void show() +{ + node *t = start; + do + { + cout << t->val << "\t"; + t = t->next; + } while (t != start); +} + +int main() +{ + int choice, x; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n\nEnter you choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; + } + } while (choice != 0); + + return 0; +} diff --git a/operations_on_datastructures/Circular Queue Using Array.cpp b/operations_on_datastructures/Circular Queue Using Array.cpp new file mode 100644 index 000000000..36d7e22c3 --- /dev/null +++ b/operations_on_datastructures/Circular Queue Using Array.cpp @@ -0,0 +1,74 @@ +#include +using namespace std; + +int queue[10]; +int front = 0; +int rear = 0; +int count = 0; + +void Enque(int x) +{ + if (count == 10) + { + cout << "\nOverflow"; + } + else + { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } +} + +void Deque() +{ + if (front == rear) + { + cout << "\nUnderflow"; + } + + else + { + cout << "\n" + << queue[front] << " deleted"; + front = (front + 1) % 10; + count--; + } +} + +void show() +{ + for (int i = 0; i < count; i++) + { + cout << queue[(i + front) % 10] << "\t"; + } +} + +int main() +{ + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); + + return 0; +} diff --git a/operations_on_datastructures/Intersection_of_2_arrays.cpp b/operations_on_datastructures/Intersection_of_2_arrays.cpp new file mode 100644 index 000000000..05652811f --- /dev/null +++ b/operations_on_datastructures/Intersection_of_2_arrays.cpp @@ -0,0 +1,31 @@ +#include +int main() +{ + int i, j, m, n; + cout << "Enter size of array 1:"; + cin >> m; + cout << "Enter size of array 2:"; + cin >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) + cin >> a[i]; + for (i = 0; i < n; i++) + cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) + { + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; + else + { + cout << a[i++] << " "; + j++; + } + } + return 0; +} diff --git a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp b/operations_on_datastructures/Reverse a Linked List using Recusion.cpp similarity index 50% rename from Operations on Datastructures/Reverse a Linked List using Recusion.cpp rename to operations_on_datastructures/Reverse a Linked List using Recusion.cpp index daefa18e8..0908080cc 100644 --- a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp +++ b/operations_on_datastructures/Reverse a Linked List using Recusion.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; struct node @@ -11,24 +11,24 @@ node *start; void insert(int x) { - node *t=start; - if (start!=NULL) + node *t = start; + if (start != NULL) { - while(t->next!=NULL) + while (t->next != NULL) { - t=t->next; + t = t->next; } - node *n= new node; - t->next=n; - n->val=x; - n->next=NULL; + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; } else { - node *n= new node; - n->val=x; - n->next=NULL; - start=n; + node *n = new node; + n->val = x; + n->next = NULL; + start = n; } } @@ -36,30 +36,27 @@ void reverse(node *p, node *q) { if (q->next == NULL) { - q->next=p; - p->next=NULL; - start=q; + q->next = p; + p->next = NULL; + start = q; return; } else { reverse(q, q->next); - q->next=p; - p->next=NULL; + q->next = p; + p->next = NULL; } - } - void show() { - node *t=start; - while(t!=NULL) + node *t = start; + while (t != NULL) { - cout<val<<"\t"; - t=t->next; + cout << t->val << "\t"; + t = t->next; } - } int main() @@ -75,6 +72,5 @@ int main() show(); - return 0; } diff --git a/operations_on_datastructures/Union_of_2_arrays.cpp b/operations_on_datastructures/Union_of_2_arrays.cpp new file mode 100644 index 000000000..aaaeb8378 --- /dev/null +++ b/operations_on_datastructures/Union_of_2_arrays.cpp @@ -0,0 +1,34 @@ +#include +int main() +{ + int m, n, i = 0, j = 0; + cout << "Enter size of both arrays:"; + cin >> m >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) + cin >> a[i]; + cout << "Enter elements of array 2:"; + for (i = 0; i < n; i++) + cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) + { + if (a[i] < b[j]) + cout << a[i++] << " "; + else if (a[i] > b[j]) + cout << b[j++] << " "; + else + { + cout << a[i++]; + j++; + } + } + while (i < m) + cout << a[i++] << " "; + while (j < n) + cout << b[j++] << " "; + return 0; +} diff --git a/operations_on_datastructures/selectionSortLinkedList.cpp b/operations_on_datastructures/selectionSortLinkedList.cpp new file mode 100644 index 000000000..52363ceff --- /dev/null +++ b/operations_on_datastructures/selectionSortLinkedList.cpp @@ -0,0 +1,159 @@ +#include +using namespace std; + +//node defined +class node +{ +public: + int data; + node *link; + node(int d) + { + data = d; + link = NULL; + } +}; + +//printing the linked list +void print(node *head) +{ + node *current = head; + while (current != NULL) + { + cout << current->data << " "; + current = current->link; + } + cout << endl; +} + +//creating the linked list with 'n' nodes +node *createlist(int n) +{ + node *head = NULL; + node *t = NULL; + for (int i = 0; i < n; i++) + { + node *temp = NULL; + int num; + cin >> num; + temp = new node(num); + if (head == NULL) + { + head = temp; + t = temp; + continue; + } + if (t->link == NULL) + t->link = temp; + t = temp; + } + return head; +} + +//performing selection sort on the linked list in an iterative manner +void my_selection_sort_linked_list(node *&head) +{ + node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning + //while scanning if we find a node 'X' with value lesser than min, + //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' + node *current = min->link; // 'current' refers to the current node we are scanning + node *previous = min; //'previous' refers to the node that is previous to the current node + node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. + //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL + //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' + //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. + //Eg. Let suppose initially we have 5->4->1->3->2->NULL + //After 1st iteration : 1->4->5->3->2->NULL and so on + + while (min->link != NULL) //so that all the nodes are scanned or until there exists a node + { + //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node + + while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X + { + if (current->data < min->data) //if the current node is smaller than the presumed node 'min' + { + if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time + { + if (previous == min) //if the 'previous' is pointing to the 'min' node + { + //Update the pointers + head = current; //update the head pointer with the current node + min->link = current->link; + current->link = previous; + min = current; + current = previous->link; + } + else //if the 'previous' is not pointing to the 'min' node + { + //Update the pointers + head = current; //update the head pointer with the current node + previous->link = current->link; + current->link = min; + min = current; + current = previous->link; + } + } + else //if 'temp' is not NULL, i.e., its not the 1st iteration + { + temp->link = current; + previous->link = current->link; + current->link = min; + min = current; + current = previous->link; + } + } + else //if the current node is greater than min, just move the previous and the current pointer a step further + { + previous = previous->link; + current = current->link; + } + } + + //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part + //start the iteration again + temp = min; + min = min->link; + previous = min; + current = min->link; + } +} + +// Test cases: + +// enter the no. of nodes : 5 +// 8 9 3 1 4 +// original list is : 8 9 3 1 4 +// sorted list is : 1 3 4 8 9 + +// enter the no. of nodes : 3 +// -1 -2 -3 +// original list is : -1 -2 -3 +// sorted list is : -3 -2 -1 + +// enter the no. of nodes : 8 +// 8 7 6 5 4 3 2 1 +// original list is : 8 7 6 5 4 3 2 1 +// sorted list is : 1 2 3 4 5 6 7 8 + +// enter the no. of nodes : 6 +// 5 3 4 1 -2 -4 +// original list is : 5 3 4 1 -2 -4 +// sorted list is : -4 -2 1 3 4 5 + +int main() +{ + node *head = NULL; + int n; + cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list + cin >> n; + if (n == 0) + return 0; + head = createlist(n); //creating the list + cout << "original list is : "; + print(head); //printing the original linked list + my_selection_sort_linked_list(head); //applying selection sort + cout << "sorted list is : "; + print(head); //printing the sorted linked list + return 0; +} \ No newline at end of file diff --git a/others/Buzz_number.cpp b/others/Buzz_number.cpp new file mode 100644 index 000000000..f31038aad --- /dev/null +++ b/others/Buzz_number.cpp @@ -0,0 +1,17 @@ +//A buzz number is a number that is either divisble by 7 or has last digit as 7. +#include +using namespace std; +int main() +{ + int n, t; + cin >> t; + while (t--) + { + cin >> n; + if ((n % 7 == 0) || (n % 10 == 7)) + cout << n << " is a buzz number" << endl; + else + cout << n << " is not a buzz number" << endl; + } + return 0; +} diff --git a/Others/Decimal To Binary.cpp b/others/Decimal To Binary.cpp similarity index 59% rename from Others/Decimal To Binary.cpp rename to others/Decimal To Binary.cpp index b8eaba1f1..4e2119ebc 100644 --- a/Others/Decimal To Binary.cpp +++ b/others/Decimal To Binary.cpp @@ -1,4 +1,4 @@ -// This function convert decimal to binary number +// This function convert decimal to binary number // #include using namespace std; @@ -10,13 +10,14 @@ int main() cin >> number; int remainder, binary = 0, var = 1; - do { - remainder = number % 2; - number = number / 2; - binary = binary + (remainder*var); + do + { + remainder = number % 2; + number = number / 2; + binary = binary + (remainder * var); var = var * 10; - } while (number>0); + } while (number > 0); cout << "the binary is :"; cout << binary; cout << endl; diff --git a/others/Decimal To Hexadecimal .cpp b/others/Decimal To Hexadecimal .cpp new file mode 100644 index 000000000..705f21ba4 --- /dev/null +++ b/others/Decimal To Hexadecimal .cpp @@ -0,0 +1,28 @@ +#include + +using namespace std; + +int main(void) +{ + int valueToConvert = 0; //Holds user input + int hexArray[8]; //Contains hex values backwards + int i = 0; //counter + char HexValues[] = "0123456789ABCDEF"; + + cout << "Enter a Decimal Value" << endl; //Displays request to stdout + cin >> valueToConvert; //Stores value into valueToConvert via user input + + while (valueToConvert > 15) + { //Dec to Hex Algorithm + hexArray[i++] = valueToConvert % 16; //Gets remainder + valueToConvert /= 16; + } + hexArray[i] = valueToConvert; //Gets last value + + cout << "Hex Value: "; + while (i >= 0) + cout << HexValues[hexArray[i--]]; + + cout << endl; + return 0; +} diff --git a/others/Decimal to Roman Numeral.cpp b/others/Decimal to Roman Numeral.cpp new file mode 100644 index 000000000..0372e8003 --- /dev/null +++ b/others/Decimal to Roman Numeral.cpp @@ -0,0 +1,97 @@ +//This Programme Converts a given decimal number in the range [0,4000) +//to both Lower case and Upper case Roman Numeral + +#include +#include +#include +#include +using namespace std; + +//This functions fills a string with character c, n times and returns it +string fill(char c, int n) +{ + string s = ""; + while (n--) + s += c; + return s; +} + +//to convert to lowercase Roman Numeral +// the function works recursively +string tolowerRoman(int n) +{ + if (n < 4) + return fill('i', n); + if (n < 6) + return fill('i', 5 - n) + "v"; + if (n < 9) + return string("v") + fill('i', n - 5); + if (n < 11) + return fill('i', 10 - n) + "x"; + if (n < 40) + return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) + return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); + if (n < 90) + return string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); + if (n < 110) + return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) + return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) + return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + if (n < 900) + return string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); + if (n < 1100) + return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) + return fill('m', n / 1000) + tolowerRoman(n % 1000); + return "?"; +} + +//to convert to uppercase Roman Numeral +// the function works recursively +string toupperRoman(int n) +{ + if (n < 4) + return fill('I', n); + if (n < 6) + return fill('I', 5 - n) + "V"; + if (n < 9) + return string("V") + fill('I', n - 5); + if (n < 11) + return fill('I', 10 - n) + "X"; + if (n < 40) + return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) + return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); + if (n < 90) + return string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); + if (n < 110) + return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) + return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) + return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + if (n < 900) + return string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); + if (n < 1100) + return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) + return fill('M', n / 1000) + toupperRoman(n % 1000); + return "?"; +} + +//main function + +int main() +{ + + int n; + cout << "\t\tRoman numbers converter\n\n"; + cout << "Type in decimal number between 0 up to 4000 (exclusive): "; + cin >> n; + cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; + cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; + return 0; +} diff --git a/others/GCD_of_n_numbers.cpp b/others/GCD_of_n_numbers.cpp new file mode 100644 index 000000000..8158052f8 --- /dev/null +++ b/others/GCD_of_n_numbers.cpp @@ -0,0 +1,23 @@ +//This program aims at calculating the GCD of n numbers by division method +#include +using namepsace std; +int main() +{ + cout << "Enter value of n:" << endl; + cin >> n; + int a[n]; + int i, j, gcd; + cout << "Enter the n numbers:" << endl; + for (i = 0; i < n; i++) + cin >> a[i]; + j = 1; //to access all elements of the array starting from 1 + gcd = a[0]; + while (j < n) + { + if (a[j] % gcd == 0) //value of gcd is as needed so far + j++; //so we check for next element + else + gcd = a[j] % gcd; //calculating GCD by division method + } + cout << "GCD of entered n numbers:" << gcd; +} diff --git a/Others/Palindromeofnumber.cpp b/others/Palindromeofnumber.cpp similarity index 70% rename from Others/Palindromeofnumber.cpp rename to others/Palindromeofnumber.cpp index 8bfdfb073..647803997 100644 --- a/Others/Palindromeofnumber.cpp +++ b/others/Palindromeofnumber.cpp @@ -12,12 +12,12 @@ int main() string s1 = to_string(num); string s2 = s1; - reverse(s1.begin(),s1.end()); + reverse(s1.begin(), s1.end()); - if(s1 == s2) - cout<<"true"; + if (s1 == s2) + cout << "true"; else - cout<<"false"; + cout << "false"; return 0; } diff --git a/others/Paranthesis Matching.cpp b/others/Paranthesis Matching.cpp new file mode 100644 index 000000000..d2bb4d39c --- /dev/null +++ b/others/Paranthesis Matching.cpp @@ -0,0 +1,76 @@ +#include +#include + +using namespace std; + +#define MAX 100 + +// -------------- stack -------------- + +char stack[MAX]; +int top = -1; + +void push(char ch) +{ + stack[++top] = ch; +} + +char pop() +{ + return stack[top--]; +} + +// -------------- end stack ----------- + +char opening(char ch) +{ + switch (ch) + { + case '}': + return '{'; + case ']': + return '['; + case ')': + return '('; + case '>': + return '<'; + } +} + +int main() +{ + + string exp; + int valid = 1, i = 0; + cout << "Enter The Expression : "; + cin >> exp; + + while (valid == 1 && i < exp.length()) + { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') + { + push(exp[i]); + } + else if (top >= 0 && stack[top] == opening(exp[i])) + { + pop(); + } + else + { + valid = 0; + } + i++; + } + + // makes sure the stack is empty after processsing (above) + if (valid == 1 && top == -1) + { + cout << "\nCorrect Expression"; + } + else + { + cout << "\nWrong Expression"; + } + + return 0; +} diff --git a/others/Primality Test.cpp b/others/Primality Test.cpp new file mode 100644 index 000000000..ce8fc1706 --- /dev/null +++ b/others/Primality Test.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +//A simple and efficient implementation of a function to test if a number is prime, based on the fact that +//Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k. + +bool IsPrime(int number) +{ + if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) + return false; + + for (int k = 1; 36 * k * k - 12 * k < number; ++k) + { + if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) + return false; + } + return true; +} + +int main() +{ + //Main Function + cout << "Enter the value of n to check if Prime\n"; + int n; + cin >> n; + if (IsPrime(n)) + cout << n << " is Prime" << endl; + else + cout << n << " is not Prime" << endl; + + return 0; +} diff --git a/Others/Sparse matrix.cpp b/others/Sparse matrix.cpp similarity index 54% rename from Others/Sparse matrix.cpp rename to others/Sparse matrix.cpp index 40073c345..1861163f1 100644 --- a/Others/Sparse matrix.cpp +++ b/others/Sparse matrix.cpp @@ -5,8 +5,8 @@ using namespace std; int main() { - int m,n; - int counterZeros=0; + int m, n; + int counterZeros = 0; cout << "Enter dimensions of matrix (seperated with space): "; cin >> m >> n; int a[m][n]; @@ -14,28 +14,28 @@ int main() cout << "\n"; // reads the matrix from stdin - for(int i=0;i> a[i][j]; + cout << "element? "; + cin >> a[i][j]; } } // counts the zero's - for(int i=0;i((m*n)/2)) //Checking for sparse matrix - cout << "Sparse matrix"; + if (counterZeros > ((m * n) / 2)) //Checking for sparse matrix + cout << "Sparse matrix"; else - cout << "Not a sparse matrix"; + cout << "Not a sparse matrix"; } diff --git a/others/Strassen Matrix Multiplication.cpp b/others/Strassen Matrix Multiplication.cpp new file mode 100644 index 000000000..85b627763 --- /dev/null +++ b/others/Strassen Matrix Multiplication.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +Multiply(int A[][], int B[][], int n) +{ + if (n == 2) + { + int p1 = (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]); + int p2 = (a[1][0] + a[1][1]) * b[0][0]; + int p3 = a[0][0] * (b[0][1] - b[1][1]); + int p4 = a[1][1] * (b[1][0] - b[0][0]); + int p5 = (a[0][0] + a[0][1]) * b[1][1]; + int p6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]); + int p7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]); + + int c[n][n]; + c[0][0] = p1 + p4 - p5 + p7; + c[0][1] = p3 + p5; + c[1][0] = p2 + p4; + c[1][1] = p1 - p2 + p3 + p6; + + return c[][]; + } + else + { + } +} + +int main() +{ + int p, q, r, s; + cout << "Enter the dimensions of Matrices"; + cin >> n; + int A[n][n], ; + int B[n][n], ; + cout << "Enter the elements of Matrix A"; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> A[i][j]; + } + } + + cout << "Enter the elements of Matrix B"; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> B[i][j]; + } + } + + Multiply(A, B, n); + return 0; +} \ No newline at end of file diff --git a/Others/String Fibonacci.cpp b/others/String Fibonacci.cpp similarity index 98% rename from Others/String Fibonacci.cpp rename to others/String Fibonacci.cpp index 8027b9668..e5475eec9 100644 --- a/Others/String Fibonacci.cpp +++ b/others/String Fibonacci.cpp @@ -2,7 +2,6 @@ //The method used is manual addition with carry and placing it in a string which is called string addition //This makes it have no bounds or limits - #include #include @@ -69,10 +68,9 @@ void fib_Accurate(long long n) fibMinus2 = fibMinus1; fibMinus1 = tmp; } - cout << fibMinus2; + cout << fibMinus2; } - int main() { int n; diff --git a/others/Tower of Hanoi.cpp b/others/Tower of Hanoi.cpp new file mode 100644 index 000000000..5783d6a98 --- /dev/null +++ b/others/Tower of Hanoi.cpp @@ -0,0 +1,73 @@ +#include +using namespace std; + +struct tower +{ + int values[10]; + int top; +} F, U, T; + +void show() +{ + cout << "\n\n\tF : "; + for (int i = 0; i < F.top; i++) + { + cout << F.values[i] << "\t"; + } + cout << "\n\tU : "; + for (int i = 0; i < U.top; i++) + { + cout << U.values[i] << "\t"; + } + cout << "\n\tT : "; + for (int i = 0; i < T.top; i++) + { + cout << T.values[i] << "\t"; + } +} + +void mov(tower &From, tower &To) +{ + --From.top; + To.values[To.top] = From.values[From.top]; + ++To.top; +} + +void TH(int n, tower &From, tower &Using, tower &To) +{ + + if (n == 1) + { + mov(From, To); + show(); + } + else + { + TH(n - 1, From, To, Using); + mov(From, To); + show(); + TH(n - 1, Using, From, To); + } +} + +int main() +{ + F.top = 0; + U.top = 0; + T.top = 0; + + int no; + + cout << "\nEnter number of discs : "; + cin >> no; + + for (int i = no; i > 0; i--) + { + F.values[F.top++] = i; + }; + + show(); + TH(no, F, U, T); + + return 0; +} diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp new file mode 100644 index 000000000..3358fc8bb --- /dev/null +++ b/others/fast_interger_input.cpp @@ -0,0 +1,36 @@ +// Read integers in the fastest way in c plus plus +#include +void fastinput(int *number) { +// variable to indicate sign of input integer + bool negative = false; + register int c; + *number = 0; + + // extract current character from buffer + c = std::getchar(); + if (c == '-') { + // number is negative + negative = true; + + // extract the next character from the buffer + c = std::getchar(); + } + + // Keep on extracting characters if they are integers + // i.e ASCII Value lies from '0'(48) to '9' (57) + for (; (c > 47 && c < 58); c = std::getchar()) + *number = *number *10 + c - 48; + + // if scanned input has a negative sign, negate the + // value of the input number + if (negative) + *(number) *= -1; +} + +// Function Call +int main() { + int number; + fastinput(&number); + std::cout << number << "\n"; + return 0; +} diff --git a/Others/fibonacci.cpp b/others/fibonacci.cpp similarity index 70% rename from Others/fibonacci.cpp rename to others/fibonacci.cpp index 82b1fd322..87ccda6d3 100644 --- a/Others/fibonacci.cpp +++ b/others/fibonacci.cpp @@ -6,14 +6,12 @@ //It is a property of fibonacci similar to matrix exponentiation. #include -#include +#include using namespace std; const long long MAX = 93; - long long f[MAX] = {0}; - long long fib(long long n) { @@ -22,26 +20,23 @@ long long fib(long long n) return 0; if (n == 1 || n == 2) return (f[n] = 1); - if (f[n]) return f[n]; - - long long k = (n%2!=0)? (n+1)/2 : n/2; - - f[n] = (n%2!=0)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) - : (2*fib(k-1) + fib(k))*fib(k); + + long long k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; + + f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) + : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } - int main() { - //Main Function - for(long long i=1;i<93;i++) - { - cout << i << " th fibonacci number is " << fib(i) << "\n"; - } - return 0; + //Main Function + for (long long i = 1; i < 93; i++) + { + cout << i << " th fibonacci number is " << fib(i) << "\n"; + } + return 0; } - diff --git a/others/happy_number.cpp b/others/happy_number.cpp new file mode 100644 index 000000000..7d25a1bbd --- /dev/null +++ b/others/happy_number.cpp @@ -0,0 +1,28 @@ +/* A happy number is a number whose sum of digits is calculated until the sum is a single digit, + and this sum turns out to be 1 */ + +// Copyright 2019 TheAlgorithms contributors + +#include + +int main() { + int n, k, s = 0, d; + std::cout << "Enter a number:"; + std::cin >> n; + s = 0; + k = n; + while (k > 9) { + while (k != 0) { + d = k % 10; + s += d; + k /= 10; + } + k = s; + s = 0; + } + if (k == 1) + std::cout << n << " is a happy number" << std::endl; + else + std::cout << n << " is not a happy number" << std::endl; + return 0; +} diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp new file mode 100644 index 000000000..25c411dda --- /dev/null +++ b/others/matrix_exponentiation.cpp @@ -0,0 +1,119 @@ +/* +Matrix Exponentiation. +The problem can be solved with DP but constraints are high. +ai = bi (for i <= k) +ai = c1*ai-1 + c2*ai-2 + ... + ck*ai-k (for i > k) +Taking the example of Fibonacci series, K=2 +b1 = 1, b2=1 +c1 = 1, c2=1 +a = 0 1 1 2 .... +This way you can find the 10^18 fibonacci number%MOD. +I have given a general way to use it. The program takes the input of B and C +matrix. +Steps for Matrix Expo +1. Create vector F1 : which is the copy of B. +2. Create transpose matrix (Learn more about it on the internet) +3. Perform T^(n-1) [transpose matrix to the power n-1] +4. Multiply with F to get the last matrix of size (1xk). +The first element of this matrix is the required result. +*/ + +#include +using std::cin; +using std::cout; +using std::vector; + +#define ll int64_t +#define endl '\n' +#define pb push_back +#define MOD 1000000007 +ll ab(ll x) { return x > 0LL ? x : -x; } +ll k; +vector a, b, c; + +// To multiply 2 matrix +vector> multiply(vector> A, vector> B) { + vector> C(k + 1, vector(k + 1)); + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + for (ll z = 1; z <= k; z++) { + C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; + } + } + } + return C; +} + +// computing power of a matrix +vector> power(vector> A, ll p) { + if (p == 1) + return A; + if (p % 2 == 1) { + return multiply(A, power(A, p - 1)); + } else { + vector> X = power(A, p / 2); + return multiply(X, X); + } +} + +// main function +ll ans(ll n) { + if (n == 0) + return 0; + if (n <= k) + return b[n - 1]; + // F1 + vector F1(k + 1); + for (ll i = 1; i <= k; i++) + F1[i] = b[i - 1]; + + // Transpose matrix + vector> T(k + 1, vector(k + 1)); + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + if (i < k) { + if (j == i + 1) + T[i][j] = 1; + else + T[i][j] = 0; + continue; + } + T[i][j] = c[k - j]; + } + } + // T^n-1 + T = power(T, n - 1); + + // T*F1 + ll res = 0; + for (ll i = 1; i <= k; i++) { + res = (res + (T[1][i] * F1[i]) % MOD) % MOD; + } + return res; +} + +// 1 1 2 3 5 + +int main() { + cin.tie(0); + cout.tie(0); + ll t; + cin >> t; + ll i, j, x; + while (t--) { + cin >> k; + for (i = 0; i < k; i++) { + cin >> x; + b.pb(x); + } + for (i = 0; i < k; i++) { + cin >> x; + c.pb(x); + } + cin >> x; + cout << ans(x) << endl; + b.clear(); + c.clear(); + } + return 0; +} diff --git a/others/measure_time_elapsed.cpp b/others/measure_time_elapsed.cpp new file mode 100644 index 000000000..d0830ab79 --- /dev/null +++ b/others/measure_time_elapsed.cpp @@ -0,0 +1,19 @@ +// To calculate the time taken by a code to execute +#include +#include + +__int64_t getTimeInMicroseconds() { + struct timeval start; + gettimeofday(&start, NULL); + return start.tv_sec * 1000000 + start.tv_usec; +} + +// write function sample(args) + +int main() { + // write code + __int64_t starttime = getTimeInMicroseconds(); + // sample(args) function run + // Any other functions (if present) run + std::cout << getTimeInMicroseconds() - starttime; +} diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp new file mode 100644 index 000000000..101100018 --- /dev/null +++ b/others/pascal_triangle.cpp @@ -0,0 +1,63 @@ +#include + +using namespace std; + +void show_pascal(int **arr, int n) +{ + //pint Pascal's Triangle + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n + i; ++j) + { + if (arr[i][j] == 0) + cout << " "; + else + cout << arr[i][j]; + } + cout << endl; + } +} + +int **pascal_triangle(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = n - i - 1; j < n + i; ++j) + { + if (j == n - i - 1 || j == n + i - 1) + arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 + else + arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; + } + } + + return arr; +} + +int main() +{ + int n = 0; + + cout << "Set Pascal's Triangle Height" << endl; + cin >> n; + + //memory allocation (Assign two-dimensional array to store Pascal triangle) + int **arr = new int*[n]; + for (int i = 0; i < n; ++i) + { + arr[i] = new int[2 * n - 1]; + memset(arr[i], 0, sizeof(int)*(2 * n - 1)); + } + + pascal_triangle(arr, n); + show_pascal(arr, n); + + //deallocation + for (int i = 0; i < n; ++i) + { + delete[] arr[i]; + } + delete[] arr; + + return 0; +} diff --git a/Others/sieve_of_Eratosthenes.cpp b/others/sieve_of_Eratosthenes.cpp similarity index 75% rename from Others/sieve_of_Eratosthenes.cpp rename to others/sieve_of_Eratosthenes.cpp index e20aec6ae..e87ad4983 100644 --- a/Others/sieve_of_Eratosthenes.cpp +++ b/others/sieve_of_Eratosthenes.cpp @@ -13,7 +13,6 @@ using namespace std; int primes[MAX]; - /* * This is the function that finds the primes and eliminates * the multiples. @@ -22,12 +21,13 @@ void sieve(int N) { primes[0] = 1; primes[1] = 1; - for(int i=2;i<=N;i++) - { - if(primes[i] == 1) continue; - for(int j=i+i;j<=N;j+=i) - primes[j] = 1; - } + for (int i = 2; i <= N; i++) + { + if (primes[i] == 1) + continue; + for (int j = i + i; j <= N; j += i) + primes[j] = 1; + } } /* @@ -35,8 +35,8 @@ void sieve(int N) */ void print(int N) { - for(int i=0;i<=N;i++) - if(primes[i] == 0) + for (int i = 0; i <= N; i++) + if (primes[i] == 0) cout << i << ' '; cout << '\n'; } @@ -47,7 +47,7 @@ void print(int N) */ void init() { - for(int i=0;i &P, Point Center, double R) @@ -44,12 +45,12 @@ double circle(vector P) Point C; Point minC; for (size_t i = 0; i < P.size() - 2; i++) - for (size_t j = i+1; j < P.size(); j++) - for (size_t k = j+1; k < P.size(); k++) + for (size_t j = i + 1; j < P.size(); j++) + for (size_t k = j + 1; k < P.size(); k++) { - C.x = -0.5 * ((P[i].y*(P[j].x*P[j].x + P[j].y*P[j].y - P[k].x*P[k].x - P[k].y*P[k].y) + P[j].y*(P[k].x*P[k].x + P[k].y*P[k].y - P[i].x*P[i].x - P[i].y*P[i].y) + P[k].y*(P[i].x*P[i].x + P[i].y*P[i].y - P[j].x*P[j].x - P[j].y*P[j].y)) / (P[i].x*(P[j].y - P[k].y) + P[j].x*(P[k].y - P[i].y) + P[k].x*(P[i].y - P[j].y) )); - C.y = 0.5 * ((P[i].x*(P[j].x*P[j].x + P[j].y*P[j].y - P[k].x*P[k].x - P[k].y*P[k].y) + P[j].x*(P[k].x*P[k].x + P[k].y*P[k].y - P[i].x*P[i].x - P[i].y*P[i].y) + P[k].x*(P[i].x*P[i].x + P[i].y*P[i].y - P[j].x*P[j].x - P[j].y*P[j].y)) / (P[i].x*(P[j].y - P[k].y) + P[j].x*(P[k].y - P[i].y) + P[k].x*(P[i].y - P[j].y) )); - R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); + C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y))); + C.y = 0.5 * ((P[i].x * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].x * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y))); + R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); if (!PointInCircle(P, C, R)) { continue; @@ -59,7 +60,6 @@ double circle(vector P) minR = R; minC = C; } - } for (size_t i = 0; i < P.size() - 1; i++) for (size_t j = i + 1; j < P.size(); j++) @@ -84,30 +84,30 @@ double circle(vector P) void test() { vector Pv(5); - Pv.push_back(Point(0,0)); - Pv.push_back(Point(1,3)); - Pv.push_back(Point(4,1)); - Pv.push_back(Point(5,4)); - Pv.push_back(Point(3,-2)); + Pv.push_back(Point(0, 0)); + Pv.push_back(Point(1, 3)); + Pv.push_back(Point(4, 1)); + Pv.push_back(Point(5, 4)); + Pv.push_back(Point(3, -2)); cout << circle(Pv) << endl; } void test2() { vector Pv(4); - Pv.push_back(Point(0,0)); - Pv.push_back(Point(0,2)); - Pv.push_back(Point(2,2)); - Pv.push_back(Point(2,0)); + Pv.push_back(Point(0, 0)); + Pv.push_back(Point(0, 2)); + Pv.push_back(Point(2, 2)); + Pv.push_back(Point(2, 0)); cout << circle(Pv) << endl; } void test3() { vector Pv(3); - Pv.push_back(Point(0.5,1)); - Pv.push_back(Point(3.5,3)); - Pv.push_back(Point(2.5,0)); + Pv.push_back(Point(0.5, 1)); + Pv.push_back(Point(3.5, 3)); + Pv.push_back(Point(2.5, 0)); cout << circle(Pv) << endl; } int main() diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp new file mode 100644 index 000000000..e6e6899ef --- /dev/null +++ b/others/spiral_print.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; + +void genArray(int a[][10], int r, int c) +{ + + int value = 1; + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + a[i][j] = value; + cout << a[i][j] << " "; + value++; + } + cout << endl; + } +} +void spiralPrint(int a[][10], int r, int c) +{ + + int startRow = 0, endRow = r - 1; + int startCol = 0, endCol = c - 1; + int cnt = 0; + + while (startRow <= endRow && startCol <= endCol) + { + + ///Print start row + for (int i = startCol; i <= endCol; i++, cnt++) + { + cout << a[startRow][i] << " "; + } + startRow++; + + ///Print the end col + for (int i = startRow; i <= endRow; i++, cnt++) + { + cout << a[i][endCol] << " "; + } + endCol--; + + ///Print the end row + if (cnt == r * c) + { + break; + } + + for (int i = endCol; i >= startCol; i--, cnt++) + { + cout << a[endRow][i] << " "; + } + endRow--; + + ///Print the start Col + if (cnt == r * c) + { + break; + } + for (int i = endRow; i >= startRow; i--, cnt++) + { + cout << a[i][startCol] << " "; + } + startCol++; + } +} + +int main() +{ + int a[10][10]; + + int r, c; + cin >> r >> c; + genArray(a, r, c); + spiralPrint(a, r, c); + + return 0; +} diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp new file mode 100644 index 000000000..281446a2f --- /dev/null +++ b/others/stairs_pattern.cpp @@ -0,0 +1,31 @@ +/* +This program is use to print the following pattern + ** + ** + **** + **** + ****** + ****** +******** +******** +where number of pairs line is given by user +*/ +#include +int main() { +int l, st = 2, x, r, z, n, sp; +std::cout << "enter Index "; +std::cin >> x; +z = x; +for (r = 1; r <= x; r++) { +z = z - 1; +for (n = 1; n <= 2; n++) { +for (sp = 1; sp <= z; sp++) { +std::cout << " "; +} +for (l = 1; l <= st; l++) { +std::cout << "*"; +} +std::cout <<"\n"; +} +st = st + 2; +}} diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp new file mode 100644 index 000000000..e0a70eeda --- /dev/null +++ b/others/vector_important_functions.cpp @@ -0,0 +1,45 @@ +// A C++ program to demonstrate working of sort(), +// reverse() +#include +#include +#include +#include //For accumulate operation +using namespace std; + +int main() +{ + // Initializing vector with array values + int arr[] = {10, 20, 5, 23 ,42 , 15}; + int n = sizeof(arr)/sizeof(arr[0]); + vector vect(arr, arr+n); + + cout << "Vector is: "; + for (int i=0; i +using namespace std; + +/** + * ` lowbit(x) ` aims to find the last 1 in binary of a positive number + * twos complement works good on this + * also using ` x - (x & (x - 1)) ` + */ +#define lowbit(x) (x & (-x) ) + +const int maxn = 1e5 + 7; +int tree[maxn] = {0}, + range; // segement of [1...range], notice it must be less than `maxn` + +void update(int x, int c) { + while(x <= range) { + tree[x] += c; + x += lowbit(x); + } +} +int query(int x) { + int ans = 0; + while(x) { + ans += tree[x]; + x -= lowbit(x); + } + return ans; +} +int query_segement(int l, int r) { + return query(r) - query(l - 1); +} + +int main() { + cin >> range; + for(int i = 1; i <= range; i++) { + int num; + cin >> num; + update(i, num); + } + int q; + cin >> q; + while(q--) { + int op; + cin >> op; + if(op == 0) { + int l, r; + cin >> l >> r; + cout << query_segement(l, r) << endl; + } else { + int x, c; + cin >> x >> c; + update(x, c); + } + } + return 0; +} diff --git a/range_queries/MO.cpp b/range_queries/MO.cpp new file mode 100644 index 000000000..7172bd632 --- /dev/null +++ b/range_queries/MO.cpp @@ -0,0 +1,77 @@ +#include +using namespace std; +const int N = 1e6 + 5; +int a[N], bucket[N], cnt[N]; +int bucket_size; +struct query +{ + int l, r, i; +} q[N]; +int ans = 0; + +void add(int index) +{ + cnt[a[index]]++; + if (cnt[a[index]] == 1) + ans++; +} +void remove(int index) +{ + cnt[a[index]]--; + if (cnt[a[index]] == 0) + ans--; +} + +bool mycmp(query x, query y) +{ + if (x.l / bucket_size != y.l / bucket_size) + return x.l / bucket_size < y.l / bucket_size; + return x.r < y.r; +} + +int main() +{ + int n, t, i, j, k = 0; + scanf("%d", &n); + for (i = 0; i < n; i++) + scanf("%d", &a[i]); + bucket_size = ceil(sqrt(n)); + scanf("%d", &t); + for (i = 0; i < t; i++) + { + scanf("%d %d", &q[i].l, &q[i].r); + q[i].l--; + q[i].r--; + q[i].i = i; + } + sort(q, q + t, mycmp); + int left = 0, right = 0; + for (i = 0; i < t; i++) + { + int L = q[i].l, R = q[i].r; + while (left < L) + { + remove(left); + left++; + } + while (left > L) + { + add(left - 1); + left--; + } + while (right <= R) + { + add(right); + right++; + } + while (right > R + 1) + { + remove(right - 1); + right--; + } + bucket[q[i].i] = ans; + } + for (i = 0; i < t; i++) + printf("%d\n", bucket[i]); + return 0; +} diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp new file mode 100644 index 000000000..e5e36ed24 --- /dev/null +++ b/range_queries/bit.cpp @@ -0,0 +1,76 @@ +// Binary Indexed Tree. +#include + +using namespace std; + +class Bit +{ + int n; + vector bit; + inline int offset(int x) + { + return (x & (-x)); + } + + public: + + Bit(vector& arr) + { + n = arr.size(); + bit.assign(n + 1, 0); + for (int i = 0; i < n; ++i) + { + update(i, arr[i]); + } + } + Bit(int x) + { + n = x; + bit.assign(n + 1, 0); + } + + void update(int id, int val) + { + // Add val at id + id++; + while (id <= n) + { + bit[id] += val; + id += offset(id); + } + } + + int sum(int id) + { + // Get prefix sum upto id. + id++; + int res = 0; + while (id > 0) + { + res += bit[id]; + id -= offset(id); + } + return res; + } + + int sum_range(int l, int r) + { + return sum(r) - sum(l - 1); + } +}; + +int main() +{ + int n = 5; + vector arr = { 1, 2, 3, 4, 5 }; + Bit x(arr); + + assert(x.sum_range(0, 0) == 1); + assert(x.sum_range(0, 1) == 3); + assert(x.sum_range(0, 2) == 6); + x.update(0, 6); + assert(x.sum_range(0, 0) == 6); + assert(x.sum_range(0, 1) == 8); + assert(x.sum_range(0, 2) == 11); + return 0; +} diff --git a/range_queries/segTree.cpp b/range_queries/segTree.cpp new file mode 100644 index 000000000..ee81453e1 --- /dev/null +++ b/range_queries/segTree.cpp @@ -0,0 +1,92 @@ +//#include +#incldue +#define MAX 4000000 +using namespace std; +typedef long long ll; +void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) +{ + if (low == high) + { + segtree[pos] = arr[low]; + return; + } + ll mid = (low + high) / 2; + ConsTree(arr, segtree, low, mid, 2 * pos + 1); + ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; +} +ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) +{ + if (low > high) + return 0; + if (qlow > high || qhigh < low) + return 0; + if (lazy[pos] != 0) + { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (qlow <= low && qhigh >= high) + return segtree[pos]; + ll mid = (low + high) / 2; + return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); +} +void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, ll high, ll pos) +{ + if (low > high) + return; + if (lazy[pos] != 0) + { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (start > high || end < low) + return; + if (start <= low && end >= high) + { + segtree[pos] += delta * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += delta; + lazy[2 * pos + 2] += delta; + } + return; + } + ll mid = (low + high) / 2; + update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); + update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; +} +int main() +{ + ll n, c; + scanf("%lld %lld", &n, &c); + ll arr[n] = {0}, p, q, v, choice; + ll segtree[MAX], lazy[MAX] = {0}; + ConsTree(arr, segtree, 0, n - 1, 0); + while (c--) + { + scanf("%lld", &choice); + if (choice == 0) + { + scanf("%lld %lld %lld", &p, &q, &v); + update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); + } + else + { + scanf("%lld %lld", &p, &q); + printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); + } + } + return 0; +} diff --git a/search/Binary Search.cpp b/search/Binary Search.cpp new file mode 100644 index 000000000..2e90855e8 --- /dev/null +++ b/search/Binary Search.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; +int binary_search(int a[], int l, int r, int key) +{ + while (l <= r) + { + int m = l + (r - l) / 2; + if (key == a[m]) + return m; + else if (key < a[m]) + r = m - 1; + else + l = m + 1; + } + return -1; +} +int main(int argc, char const *argv[]) +{ + int n, key; + cout << "Enter size of array: "; + cin >> n; + cout << "Enter array elements: "; + int a[n]; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << "Enter search key: "; + cin >> key; + int res = binary_search(a, 0, n - 1, key); + if (res != -1) + cout << key << " found at index " << res << endl; + else + cout << key << " not found" << endl; + return 0; +} \ No newline at end of file diff --git a/search/Interpolation Search.cpp b/search/Interpolation Search.cpp new file mode 100644 index 000000000..f52ce4f4f --- /dev/null +++ b/search/Interpolation Search.cpp @@ -0,0 +1,31 @@ +#include +int InterpolationSearch(int A[], int n, int x) +{ + int low = 0; + int high = n - 1; + while (low <= high) + { + int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); + if (x == A[mid]) + return mid; // Found x, return (exit) + else if (x < A[mid]) + high = mid - 1; // X lies before mid + else + low = mid + 1; // x lies after mid + } + return -1; +} + +int main() +{ + int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; + int x = 17; + int index = InterpolationSearch(A, 8, x); // passed array A inside the InterpolationSearch function + if (index != -1) + std::cout << "Number " << x << " is at " << index; + else + std::cout << "Number " << x << " not found"; +} + +// randomly set x bcoz array was defined by us , therefore not reasonable for asking input. +// We could have asked for input if array elements were inputed by the user. diff --git a/search/Linear Search.cpp b/search/Linear Search.cpp new file mode 100644 index 000000000..97e820437 --- /dev/null +++ b/search/Linear Search.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +int LinearSearch(int *array, int size, int key) +{ + for (int i = 0; i < size; ++i) + { + if (array[i] == key) + { + return i; + } + } + + return -1; +} + +int main() +{ + int size; + cout << "\nEnter the size of the Array : "; + cin >> size; + + int array[size]; + int key; + + //Input array + cout << "\nEnter the Array of " << size << " numbers : "; + for (int i = 0; i < size; i++) + { + cin >> array[i]; + } + + cout << "\nEnter the number to be searched : "; + cin >> key; + + int index = LinearSearch(array, size, key); + if (index != -1) + { + cout << "\nNumber found at index : " << index; + } + else + { + cout << "\nNot found"; + } + + return 0; +} diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp new file mode 100644 index 000000000..b8343fa02 --- /dev/null +++ b/search/exponential_search.cpp @@ -0,0 +1,56 @@ +// Copyright 2020 Divide-et-impera-11 +#include +#include +#include +using namespaces std; +// Binary Search Algorithm(use by struzik algorithm) +// Time Complexity O(log n) where 'n' is the number of elements +// Worst Time Complexity O(log n) +// Best Time Complexity Ω(1) +// Space Complexity O(1) +// Auxiliary Space Complexity O(1) +template inline Type* binary_s(Type *array, size_t size, Type key) { +int32_t lower_index(0), upper_index(size - 1), middle_index; +while (lower_index <= upper_index) { + middle_index = floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) lower_index = (middle_index + 1); + else if (*(array + middle_index) > key)upper_index = (middle_index - 1); + else return (array + middle_index); + } +return nullptr; +} +// Struzik Search Algorithm(Exponential) +// Time Complexity O(log i)where i is the position of search key in the list +// Worst Time Complexity O(log i) +// Best Time Complexity Ω(1) +// Space Complexity O(1) +// Auxiliary Space Complexity O(1) +/* Tha algorithm try to search the range where the key should be. +If it has been found we do a binary search there. +The range of the search grows by exponential every time. +If the key is larger than the last element of array, +the start of block(block_front) will be equal to the end of block(block_size) +and the algorithm return null ponter, +every other cases the algoritm return fom the loop. */ +template Type* struzik_search(Type* array, size_t size, Type key) { + uint32_t block_front(0), block_size = size == 0 ? 0 : 1; + while (block_front != block_size) { + if (*(array + block_size - 1) < key) { + block_front = block_size; + (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; + continue; + } + return binary_s(array + block_front, (block_size - block_front), key); + } +return nullptr; +} +int main() { +// TEST CASES +int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; +assert(struzik_search(sorted_array, 7, 0) == nullptr); +assert(struzik_search(sorted_array, 7, 1000) == nullptr); +assert(struzik_search(sorted_array, 7, 50) == nullptr); +assert(struzik_search(sorted_array, 7, 7) == sorted_array); +// TEST CASES +return 0; +} diff --git a/search/hash_search.cpp b/search/hash_search.cpp new file mode 100644 index 000000000..94d87b58a --- /dev/null +++ b/search/hash_search.cpp @@ -0,0 +1,100 @@ +// Copyright 2020 Arctic2333 +#include +#include +#define MAX 6 // Determines how much data +# define HASHMAX 5 // Determines the length of the hash table +/** + * Hash Search Algorithm + * Best Time Complexity Ω(1) + * In this algorithm, we use the method of division and reservation remainder to construct the hash function, + * and use the method of chain address to solve the conflict, that is, we link a chain list after the data, + * and store all the records whose keywords are synonyms in the same linear chain list. */ +int data[MAX] = { 1, 10, 15, 5, 8, 7}; // test data +typedef struct list { + int key; + struct list * next; +} +node, * link; +node hashtab[HASHMAX]; +int counter = 1; +/* int h(int key) + * Mode of hash detection : + * Division method */ +int h(int key) { + return key % HASHMAX; +} +/* void create_list(int key) + * The same after the remainder will be added after the same hash header + * To avoid conflict, zipper method is used + * Insert elements into the linked list in the header */ +void create_list(int key) { // Construct hash table + link p, n; + int index; + n = (link) malloc(sizeof(node)); + n -> key = key; + n -> next = NULL; + index = h(key); + p = hashtab[index].next; + if (p != NULL) { + n -> next = p; + hashtab[index].next = n; + } else { + hashtab[index].next = n; } +} +/* int hash_search(int key) + * Input the key to be searched, and get the hash header position through the H (int key) function, + * then one-dimensional linear search. + * If found @return element depth and number of searches + * If not found @return -1 */ +int hash_search(int key) { // Hash lookup function + link pointer; + int index; + counter = 0; + index = h(key); + pointer = hashtab[index].next; + printf("data[%d]:", index); + while (pointer != NULL) { + counter++; + printf("data[%d]:", pointer -> key); + if (pointer -> key == key) + return 1; + else + pointer = pointer -> next; + } + return 0; +} +int main() { + link p; + int key, index, i; // Key is the value to be found + index = 0; + // You can write the input mode here + while (index < MAX) { // Construct hash table + create_list(data[index]); + index++; + } + for (i = 0; i < HASHMAX; i++) { // Output hash table + printf("hashtab [%d]", i); + printf("\n"); + p = hashtab[i].next; + while (p != NULL) { + printf("please int key:"); + if (p -> key > 0) + printf("[%d]", p -> key); + p = p -> next; + } + printf("\n"); + } + while (key != -1) { + // You can write the input mode here + // test key = 10 + key = 10; + if (hash_search(key)) + printf("search time = %d\n", counter); + else + printf("no found!\n"); + key = -1; // Exit test + /* The test sample is returned as: data[0]:data[5]:data[15]:data[10]:search time = 3 + * The search is successful. There are 10 in this set of data */ + } + return 0; +} diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp new file mode 100644 index 000000000..afa9e7c50 --- /dev/null +++ b/search/interpolation_search.cpp @@ -0,0 +1,36 @@ +#include + +// function to search the value in an array using interpolation search +int search(int arr[], int value, int len) { + int low = 0, high, mid; + high = len-1; + while (arr[low] <= value && arr[high] >= value) { + mid = (low + ((value-arr[low])*(high-low)) / (arr[high]-arr[low])); + if (arr[mid] > value) + high = mid-1; + else if (arr[mid] < value) + low = mid+1; + else + return mid; + } + if (arr[low] == value) + return low; + return 0; +} + +int main() { + int n, value, array[100], re; + std::cout << "Enter the size of array(less than 100) : "; + std::cin >> n; + std::cout << "array in ascending (increasing) order : " << std::endl; + for (int i=0; i < n; i++) + std::cin >> array[i]; + std::cout << "Enter the value you want to search : "; + std::cin >> value; + re = search(array, value, n); + if (re == 0) + std::cout << "Entered value is not in the array" << std::endl; + else + std::cout << "The value is at the position " << re << std::endl; + return 0; + } diff --git a/search/median_search.cpp b/search/median_search.cpp new file mode 100644 index 000000000..be95b599f --- /dev/null +++ b/search/median_search.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace std; +vectorv; +vectors1; +vectors2; +vectors3; +template +void comp(X x) +{ + if(s1.size()>=x && s1.size()+s2.size()x) + { + sort(s1.begin(),s1.end()); + cout<x) + { + sort(s3.begin(),s3.end()); + cout<>x; + comp(x-1); + return 0; +} diff --git a/search/searching.cpp b/search/searching.cpp new file mode 100644 index 000000000..6a9dcac7d --- /dev/null +++ b/search/searching.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +using namespace std; +char paragraph; + +int main() +{ + string paragraph; + cout << "Please enter your paragraph: \n"; + getline(cin, paragraph); + cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; + cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; + + if (paragraph.empty()) + { + cout << "\nThe paragraph is empty" << endl; + } + else + { + while (true) + { + string word; + cout << "Please enter the word you are searching for: "; + getline(cin, word); + cout << "Hello, your word is " << word << "!\n"; + if (paragraph.find(word) == string::npos) + { + cout << word << " does not exist in the sentence" << endl; + } + else + { + cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl + << endl; + } + system("pause"); + } + } +} diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp new file mode 100644 index 000000000..4cb8d19d9 --- /dev/null +++ b/search/ternary_search.cpp @@ -0,0 +1,128 @@ +/* + * This is a divide and conquer algorithm. + * It does this by dividing the search space by 3 parts and + * using its property (usually monotonic property) to find + * the desired index. + * + * Time Complexity : O(log3 n) + * Space Complexity : O(1) (without the array) + */ + +#include +using namespace std; + +/* + * The absolutePrecision can be modified to fit preference but + * it is recommended to not go lower than 10 due to errors that + * may occur. + * + * The value of _target should be decided or can be decided later + * by using the variable of the function. + */ + +#define _target 10 +#define absolutePrecision 10 +#define MAX 10000000 + +int N = 21; +int A[MAX] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; + +/* + * get_input function is to receive input from standard IO + */ +void get_input() +{ + // TODO: Get input from STDIO or write input to memory as done above. +} + +/* + * This is the iterative method of the ternary search which returns the index of the element. + */ +int it_ternary_search(int left, int right, int A[], int target) +{ + while (1) + { + if (left < right) + { + if (right - left < absolutePrecision) + { + for (int i = left; i <= right; i++) + if (A[i] == target) + return i; + + return -1; + } + + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; + + if (A[oneThird] == target) + return oneThird; + else if (A[twoThird] == target) + return twoThird; + + else if (target > A[twoThird]) + left = twoThird + 1; + else if (target < A[oneThird]) + right = oneThird - 1; + + else + left = oneThird + 1, right = twoThird - 1; + } + else + return -1; + } +} + +/* + * This is the recursive method of the ternary search which returns the index of the element. + */ +int rec_ternary_search(int left, int right, int A[], int target) +{ + if (left < right) + { + if (right - left < absolutePrecision) + { + for (int i = left; i <= right; i++) + if (A[i] == target) + return i; + + return -1; + } + + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; + + if (A[oneThird] == target) + return oneThird; + if (A[twoThird] == target) + return twoThird; + + if (target < A[oneThird]) + return rec_ternary_search(left, oneThird - 1, A, target); + if (target > A[twoThird]) + return rec_ternary_search(twoThird + 1, right, A, target); + + return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); + } + else + return -1; +} + +/* + * ternary_search is a template function + * You could either use it_ternary_search or rec_ternary_search according to preference. + */ +void ternary_search(int N, int A[], int target) +{ + cout << it_ternary_search(0, N - 1, A, target) << '\t'; + cout << rec_ternary_search(0, N - 1, A, target) << '\t'; + cout << '\n'; +} + +int main() +{ + get_input(); + ternary_search(N, A, _target); + return 0; +} diff --git a/sleep sort.c b/sleep sort.c deleted file mode 100644 index e0217ca25..000000000 --- a/sleep sort.c +++ /dev/null @@ -1,41 +0,0 @@ -#include -#include -#include - -void routine(void *a) -{ - int n = *(int *) a; // typecasting from void to int - - // Sleeping time is proportional to the number - // More precisely this thread sleep for 'n' milliseconds - Sleep(n); - - // After the sleep, print the number - printf("%d ", n); - -void sleepSort(int arr[], int n) -{ - // An array of threads, one for each of the elements - // in the input array - HANDLE threads[n]; - - // Create the threads for each of the input array elements - for (int i = 0; i < n; i++) - threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]); - - // Process these threads - WaitForMultipleObjects(n, threads, TRUE, INFINITE); - return; -} - -// Driver program to test above functions -int main() -{ - // Doesn't work for negative numbers - int arr[] = {34, 23, 122, 9}; - int n = sizeof(arr) / sizeof(arr[0]); - - sleepSort (arr, n); - - return(0); -} \ No newline at end of file diff --git a/sorting/BeadSort.cpp b/sorting/BeadSort.cpp new file mode 100644 index 000000000..c8e27b250 --- /dev/null +++ b/sorting/BeadSort.cpp @@ -0,0 +1,63 @@ +// C++ program to implement gravity/bead sort +#include +#include +using namespace std; + +#define BEAD(i, j) beads[i * max + j] + +// function to perform the above algorithm +void beadSort(int *a, int len) +{ + // Find the maximum element + int max = a[0]; + for (int i = 1; i < len; i++) + if (a[i] > max) + max = a[i]; + + // allocating memory + unsigned char beads[max*len]; + memset(beads, 0, sizeof(beads)); + + // mark the beads + for (int i = 0; i < len; i++) + for (int j = 0; j < a[i]; j++) + BEAD(i, j) = 1; + + for (int j = 0; j < max; j++) + { + // count how many beads are on each post + int sum = 0; + for (int i=0; i < len; i++) + { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + + // Move beads down + for (int i = len - sum; i < len; i++) + BEAD(i, j) = 1; + } + + // Put sorted values in array using beads + for (int i = 0; i < len; i++) + { + int j; + for (j = 0; j < max && BEAD(i, j); j++); + + a[i] = j; + } +} + +// driver function to test the algorithm +int main() +{ + int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; + int len = sizeof(a)/sizeof(a[0]); + + beadSort(a, len); + + for (int i = 0; i < len; i++) + printf("%d ", a[i]); + + return 0; +} diff --git a/sorting/BitonicSort.cpp b/sorting/BitonicSort.cpp new file mode 100644 index 000000000..6ad2489d2 --- /dev/null +++ b/sorting/BitonicSort.cpp @@ -0,0 +1,76 @@ +// Source : https://www.geeksforgeeks.org/bitonic-sort/ + +/* C++ Program for Bitonic Sort. Note that this program + works only when size of input is a power of 2. */ + +#include +#include +using namespace std; + +/*The parameter dir indicates the sorting direction, ASCENDING + or DESCENDING; if (a[i] > a[j]) agrees with the direction, + then a[i] and a[j] are interchanged.*/ +void compAndSwap(int a[], int i, int j, int dir) +{ + if (dir == (a[i] > a[j])) + swap(a[i], a[j]); +} + +/*It recursively sorts a bitonic sequence in ascending order, + if dir = 1, and in descending order otherwise (means dir=0). + The sequence to be sorted starts at index position low, + the parameter cnt is the number of elements to be sorted.*/ +void bitonicMerge(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { + int k = cnt / 2; + for (int i = low; i < low + k; i++) + compAndSwap(a, i, i + k, dir); + bitonicMerge(a, low, k, dir); + bitonicMerge(a, low + k, k, dir); + } +} + +/* This function first produces a bitonic sequence by recursively + sorting its two halves in opposite sorting orders, and then + calls bitonicMerge to make them in the same order */ +void bitonicSort(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { + int k = cnt / 2; + + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); + + // sort in descending order since dir here is 0 + bitonicSort(a, low + k, k, 0); + + // Will merge wole sequence in ascending order + // since dir=1. + bitonicMerge(a, low, cnt, dir); + } +} + +/* Caller of bitonicSort for sorting the entire array of + length N in ASCENDING order */ +void sort(int a[], int N, int up) +{ + bitonicSort(a, 0, N, up); +} + +// Driver code +int main() +{ + int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; + int N = sizeof(a) / sizeof(a[0]); + + int up = 1; // means sort in ascending order + sort(a, N, up); + + printf("Sorted array: \n"); + for (int i = 0; i < N; i++) + printf("%d ", a[i]); + return 0; +} diff --git a/sorting/Bubble Sort.cpp b/sorting/Bubble Sort.cpp index 7bc5c0be8..7791a06b4 100644 --- a/sorting/Bubble Sort.cpp +++ b/sorting/Bubble Sort.cpp @@ -1,53 +1,53 @@ //Bubble Sort -#include -#include + +#include +#include + using namespace std; int main() { int n; - short swap_check=0; - cout << "Enter the amount of numbers to sort: "; + short swap_check = 1; + cout << "Enter the amount of numbers to sort: "; cin >> n; vector numbers; cout << "Enter " << n << " numbers: "; int num; - //Input - for(int i=0; i> num; numbers.push_back(num); } //Bubble Sorting - for(int i=0; inumbers[j+1]) + if (numbers[j] > numbers[j + 1]) { - swap_check=1; - swap(numbers[j], numbers[j+1]);// by changing swap location. I mean, j. If the number is greater than j + 1, then it means the location. + swap_check = 1; + swap(numbers[j], numbers[j + 1]);// by changing swap location. I mean, j. If the number is greater than j + 1, then it means the location. } } - if(swap_check == 0) - { - break; - } } //Output - cout<<"\nSorted Array : "; - for(int i=0; i +using namespace std; + +//Iterative Version + +void CocktailSelectionSort(vector &vec, int low, int high) +{ + while (low <= high) + { + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) + { + if (vec[i] >= maximum) + { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) + { + minimum = vec[i]; + minimumindex = i; + } + } + if (low != maximumindex || high != minimumindex) + { + swap(vec[low], vec[minimumindex]); + swap(vec[high], vec[maximumindex]); + } + else + { + swap(vec[low], vec[high]); + } + + low++; + high--; + } +} + +//Recursive Version + +void CocktailSelectionSort(vector &vec, int low, int high) +{ + + if (low >= high) + return; + + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) + { + if (vec[i] >= maximum) + { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) + { + minimum = vec[i]; + minimumindex = i; + } + } + if (low != maximumindex || high != minimumindex) + { + swap(vec[low], vec[minimumindex]); + swap(vec[high], vec[maximumindex]); + } + else + { + swap(vec[low], vec[high]); + } + + CocktailSelectionSort(vec, low + 1, high - 1); +} + +//main function, select any one of iterative or recursive version + +int main() +{ + + int n; + cout << "Enter number of elements\n"; + cin >> n; + std::vector v(n); + cout << "Enter all the elements\n"; + for (int i = 0; i < n; ++i) + { + cin >> v[i]; + } + + CocktailSelectionSort(v, 0, n - 1); + cout << "Sorted elements are\n"; + for (int i = 0; i < n; ++i) + { + cout << v[i] << " "; + } + + return 0; +} diff --git a/sorting/CountingSortString.cpp b/sorting/CountingSortString.cpp new file mode 100644 index 000000000..6179e5d11 --- /dev/null +++ b/sorting/CountingSortString.cpp @@ -0,0 +1,41 @@ +// C++ Program for counting sort +#include + +using namespace std; + +void countSort(string arr) +{ + + string output; + + int count[256], i; + for (int i = 0; i < 256; i++) + count[i] = 0; + + for (i = 0; arr[i]; ++i) + ++count[arr[i]]; + + for (i = 1; i <= 256; ++i) + count[i] += count[i - 1]; + + for (i = 0; arr[i]; ++i) + { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + for (i = 0; arr[i]; ++i) + arr[i] = output[i]; + + cout << "Sorted character array is " << arr; +} + +int main() +{ + string arr; + cin >> arr; + + countSort(arr); + + return 0; +} diff --git a/sorting/Counting_Sort.cpp b/sorting/Counting_Sort.cpp new file mode 100644 index 000000000..bda37bbd8 --- /dev/null +++ b/sorting/Counting_Sort.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; + +int Max(int Arr[], int N) +{ + int max = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] > max) + max = Arr[i]; + return max; +} + +int Min(int Arr[], int N) +{ + int min = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] < min) + min = Arr[i]; + return min; +} + +void Print(int Arr[], int N) +{ + for (int i = 0; i < N; i++) + cout << Arr[i] << ", "; +} + +int *Counting_Sort(int Arr[], int N) +{ + + int max = Max(Arr, N); + int min = Min(Arr, N); + int *Sorted_Arr = new int[N]; + + int *Count = new int[max - min + 1]; + + for (int i = 0; i < N; i++) + Count[Arr[i] - min]++; + + for (int i = 1; i < (max - min + 1); i++) + Count[i] += Count[i - 1]; + + for (int i = N - 1; i >= 0; i--) + { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; + } + + return Sorted_Arr; +} + +int main() +{ + + int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; + int *Sorted_Arr; + + cout << "\n\tOrignal Array = "; + Print(Arr, N); + Sorted_Arr = Counting_Sort(Arr, N); + cout << "\n\t Sorted Array = "; + Print(Sorted_Arr, N); + cout << endl; + + return 0; +} diff --git a/sorting/Insertion Sort.cpp b/sorting/Insertion Sort.cpp new file mode 100644 index 000000000..2563acaf8 --- /dev/null +++ b/sorting/Insertion Sort.cpp @@ -0,0 +1,40 @@ +//Insertion Sort + +#include +using namespace std; + +int main() +{ + int n; + cout << "\nEnter the length of your array : "; + cin >> n; + int Array[n]; + cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; + + //Input + for (int i = 0; i < n; i++) + { + cin >> Array[i]; + } + + //Sorting + for (int i = 1; i < n; i++) + { + int temp = Array[i]; + int j = i - 1; + while (j >= 0 && temp < Array[j]) + { + Array[j + 1] = Array[j]; + j--; + } + Array[j + 1] = temp; + } + + //Output + cout << "\nSorted Array : "; + for (int i = 0; i < n; i++) + { + cout << Array[i] << "\t"; + } + return 0; +} diff --git a/Sorting/Merge Sort.cpp b/sorting/Merge Sort.cpp similarity index 69% rename from Sorting/Merge Sort.cpp rename to sorting/Merge Sort.cpp index 9891b8630..b8edc8851 100644 --- a/Sorting/Merge Sort.cpp +++ b/sorting/Merge Sort.cpp @@ -1,20 +1,19 @@ -#include +#include using namespace std; void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; - int n2 = r - m; - + int n2 = r - m; + int L[n1], R[n2]; - - + for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) - R[j] = arr[m + 1+ j]; - + R[j] = arr[m + 1 + j]; + i = 0; j = 0; k = l; @@ -32,14 +31,13 @@ void merge(int arr[], int l, int m, int r) } k++; } - + while (i < n1) { arr[k] = L[i]; i++; k++; } - while (j < n2) { @@ -48,52 +46,48 @@ void merge(int arr[], int l, int m, int r) k++; } } - void mergeSort(int arr[], int l, int r) { if (l < r) { - - int m = l+(r-l)/2; - - + + int m = l + (r - l) / 2; + mergeSort(arr, l, m); - mergeSort(arr, m+1, r); - + mergeSort(arr, m + 1, r); + merge(arr, l, m, r); } } - void show(int A[], int size) { int i; - for (i=0; i < size; i++) - cout<>size; + cin >> size; int arr[size]; - - cout<<"\nEnter the unsorted elements : "; + + cout << "\nEnter the unsorted elements : "; for (int i = 0; i < size; ++i) { - cout<<"\n"; - cin>>arr[i]; + cout << "\n"; + cin >> arr[i]; } mergeSort(arr, 0, size); - - cout<<"Sorted array\n"; + + cout << "Sorted array\n"; show(arr, size); return 0; } diff --git a/sorting/NumericStringSort.cpp b/sorting/NumericStringSort.cpp new file mode 100644 index 000000000..02f6964ba --- /dev/null +++ b/sorting/NumericStringSort.cpp @@ -0,0 +1,62 @@ +//Using general algorithms to sort a collection of strings results in alphanumeric sort. +//If it is a numeric string, it leads to unnatural sorting + +//eg, an array of strings 1,10,100,2,20,200,3,30,300 +//would be sorted in that same order by using conventional sorting, +//even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300 + +//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order + +#include +#include +#include +using namespace std; + +bool NumericSort(string a, string b) +{ + while (a[0] == '0') + { + a.erase(a.begin()); + } + while (b[0] == '0') + { + b.erase(b.begin()); + } + int n = a.length(); + int m = b.length(); + if (n == m) + return a < b; + return n < m; +} + +int main() +{ + + int n; + cout << "Enter number of elements to be sorted Numerically\n"; + cin >> n; + + vector v(n); + cout << "Enter the string of Numbers\n"; + for (int i = 0; i < n; i++) + { + cin >> v[i]; + } + + sort(v.begin(), v.end()); + cout << "Elements sorted normally \n"; + for (int i = 0; i < n; i++) + { + cout << v[i] << " "; + } + cout << "\n"; + + sort(v.begin(), v.end(), NumericSort); + cout << "Elements sorted Numerically \n"; + for (int i = 0; i < n; i++) + { + cout << v[i] << " "; + } + + return 0; +} diff --git a/Sorting/OddEven Sort.cpp b/sorting/OddEven Sort.cpp similarity index 66% rename from Sorting/OddEven Sort.cpp rename to sorting/OddEven Sort.cpp index 6319cca91..62842c174 100644 --- a/Sorting/OddEven Sort.cpp +++ b/sorting/OddEven Sort.cpp @@ -7,23 +7,23 @@ using namespace std; void oddEven(vector &arr, int size) { bool sorted = false; - while( ! sorted ) + while (!sorted) { sorted = true; - for(int i = 1; i < size-1; i += 2)//Odd + for (int i = 1; i < size - 1; i += 2) //Odd { - if(arr[i] > arr[i+1]) + if (arr[i] > arr[i + 1]) { - swap(arr[i], arr[i+1]); + swap(arr[i], arr[i + 1]); sorted = false; } } - for(int i = 0; i < size-1; i += 2)//Even + for (int i = 0; i < size - 1; i += 2) //Even { - if(arr[i] > arr[i+1]) + if (arr[i] > arr[i + 1]) { - swap(arr[i], arr[i+1]); + swap(arr[i], arr[i + 1]); sorted = false; } } @@ -37,7 +37,6 @@ void show(vector A, int size) cout << A[i] << "\n"; } - int main() { int size, temp; @@ -46,7 +45,7 @@ int main() vector arr; - cout<<"\nEnter the unsorted elements : \n"; + cout << "\nEnter the unsorted elements : \n"; for (int i = 0; i < size; ++i) { @@ -56,7 +55,7 @@ int main() oddEven(arr, size); - cout<<"Sorted array\n"; + cout << "Sorted array\n"; show(arr, size); return 0; } diff --git a/sorting/Quick Sort.cpp b/sorting/Quick Sort.cpp new file mode 100644 index 000000000..0b807898f --- /dev/null +++ b/sorting/Quick Sort.cpp @@ -0,0 +1,67 @@ +/* C implementation QuickSort */ +#include +using namespace std; + +int partition(int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j < high; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; // increment index of smaller element + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); +} + +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + + int p = partition(arr, low, high); + + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); + } +} + +void show(int arr[], int size) +{ + for (int i = 0; i < size; i++) + cout << arr[i] << "\n"; +} + +// Driver program to test above functions +int main() +{ + int size; + cout << "\nEnter the number of elements : "; + + cin >> size; + + int arr[size]; + + cout << "\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) + { + cout << "\n"; + cin >> arr[i]; + } + quickSort(arr, 0, size); + cout << "Sorted array\n"; + show(arr, size); + return 0; +} diff --git a/sorting/Radix Sort.cpp b/sorting/Radix Sort.cpp new file mode 100644 index 000000000..09c91bb22 --- /dev/null +++ b/sorting/Radix Sort.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; +void radixsort(int a[], int n) +{ + int count[10]; + int output[n]; + memset(output, 0, sizeof(output)); + memset(count, 0, sizeof(count)); + int max = 0; + for (int i = 0; i < n; ++i) + { + if (a[i] > max) + { + max = a[i]; + } + } + int maxdigits = 0; + while (max) + { + maxdigits++; + max /= 10; + } + for (int j = 0; j < maxdigits; j++) + { + for (int i = 0; i < n; i++) + { + int t = pow(10, j); + count[(a[i] % (10 * t)) / t]++; + } + int k = 0; + for (int p = 0; p < 10; p++) + { + for (int i = 0; i < n; i++) + { + int t = pow(10, j); + if ((a[i] % (10 * t)) / t == p) + { + output[k] = a[i]; + k++; + } + } + } + memset(count, 0, sizeof(count)); + for (int i = 0; i < n; ++i) + { + a[i] = output[i]; + } + } +} +void print(int a[], int n) +{ + for (int i = 0; i < n; ++i) + { + cout << a[i] << " "; + } + cout << endl; +} +int main(int argc, char const *argv[]) +{ + int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(a) / sizeof(a[0]); + radixsort(a, n); + print(a, n); + return 0; +} \ No newline at end of file diff --git a/sorting/Selection Sort.cpp b/sorting/Selection Sort.cpp new file mode 100644 index 000000000..5b8724141 --- /dev/null +++ b/sorting/Selection Sort.cpp @@ -0,0 +1,39 @@ +//Selection Sort + +#include +using namespace std; + +int main() +{ + int Array[6]; + cout << "\nEnter any 6 Numbers for Unsorted Array : "; + + //Input + for (int i = 0; i < 6; i++) + { + cin >> Array[i]; + } + + //Selection Sorting + for (int i = 0; i < 6; i++) + { + int min = i; + for (int j = i + 1; j < 6; j++) + { + if (Array[j] < Array[min]) + { + min = j; //Finding the smallest number in Array + } + } + int temp = Array[i]; + Array[i] = Array[min]; + Array[min] = temp; + } + + //Output + cout << "\nSorted Array : "; + for (int i = 0; i < 6; i++) + { + cout << Array[i] << "\t"; + } +} diff --git a/sorting/Shell Sort.cpp b/sorting/Shell Sort.cpp new file mode 100644 index 000000000..b08c7ffd8 --- /dev/null +++ b/sorting/Shell Sort.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +int main() +{ + int size = 10; + int array[size]; + // Input + cout << "\nHow many numbers do want to enter in unsorted array : "; + cin >> size; + cout << "\nEnter the numbers for unsorted array : "; + for (int i = 0; i < size; i++) + { + cin >> array[i]; + } + + // Sorting + for (int i = size / 2; i > 0; i = i / 2) + { + for (int j = i; j < size; j++) + { + for (int k = j - i; k >= 0; k = k - i) + { + if (array[k] < array[k + i]) + { + break; + } + else + { + int temp = array[k + i]; + array[k + i] = array[k]; + array[k] = temp; + } + } + } + } + + // Output + cout << "\nSorted array : "; + for (int i = 0; i < size; ++i) + { + cout << array[i] << "\t"; + } + return 0; +} diff --git a/Sorting/Slow Sort.cpp b/sorting/Slow Sort.cpp similarity index 52% rename from Sorting/Slow Sort.cpp rename to sorting/Slow Sort.cpp index 686dcbccb..f8f7e74b8 100644 --- a/Sorting/Slow Sort.cpp +++ b/sorting/Slow Sort.cpp @@ -1,27 +1,27 @@ //Returns the sorted vector after performing SlowSort -//It is a sorting algorithm that is of humorous nature and not useful. -//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. +//It is a sorting algorithm that is of humorous nature and not useful. +//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. //It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. //This algorithm multiplies a single problem into multiple subproblems -//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically, +//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically, //and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result. -#include +#include using namespace std; void SlowSort(int a[], int i, int j) { - if(i>=j) + if (i >= j) return; - int m=i+(j-i)/2; //midpoint, implemented this way to avoid overflow + int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow int temp; SlowSort(a, i, m); SlowSort(a, m + 1, j); - if(a[j]>size; + cin >> size; - int arr[size]; - - cout<<"\nEnter the unsorted elements : "; + int arr[size]; - for (int i = 0; i < size; ++i) - { - cout<<"\n"; - cin>>arr[i]; - } + cout << "\nEnter the unsorted elements : "; - SlowSort(arr, 0, size); - - cout<<"Sorted array\n"; - - for (int i = 0; i < size; ++i) - { - cout << arr[i] << " "; - } - return 0; + for (int i = 0; i < size; ++i) + { + cout << "\n"; + cin >> arr[i]; + } + + SlowSort(arr, 0, size); + + cout << "Sorted array\n"; + + for (int i = 0; i < size; ++i) + { + cout << arr[i] << " "; + } + return 0; } diff --git a/Sorting/Tim Sort.cpp b/sorting/Tim Sort.cpp similarity index 99% rename from Sorting/Tim Sort.cpp rename to sorting/Tim Sort.cpp index a97a123a1..14d3a04d0 100644 --- a/Sorting/Tim Sort.cpp +++ b/sorting/Tim Sort.cpp @@ -1,5 +1,5 @@ // C++ program to perform TimSort. -#include +#include using namespace std; const int RUN = 32; diff --git a/sorting/bucketSort.cpp b/sorting/bucketSort.cpp new file mode 100644 index 000000000..0ffbf8e4c --- /dev/null +++ b/sorting/bucketSort.cpp @@ -0,0 +1,42 @@ +// C++ program to sort an array using bucket sort +#include +#include +#include +using namespace std; + +// Function to sort arr[] of size n using bucket sort +void bucketSort(float arr[], int n) +{ + // 1) Create n empty buckets + vector b[n]; + + // 2) Put array elements in different buckets + for (int i = 0; i < n; i++) + { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); + } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; +} + +/* Driver program to test above funtion */ +int main() +{ + float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); + + cout << "Sorted array is \n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} diff --git a/Sorting/combsort.cpp b/sorting/combsort.cpp similarity index 67% rename from Sorting/combsort.cpp rename to sorting/combsort.cpp index 7aa65ab80..2209c96fc 100644 --- a/Sorting/combsort.cpp +++ b/sorting/combsort.cpp @@ -1,5 +1,5 @@ //Kind of better version of Bubble sort. -//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1 +//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1 //Best case: O(n) //Worst case: O(n ^ 2) @@ -10,29 +10,34 @@ using namespace std; int a[100005]; int n; -int FindNextGap(int x) { +int FindNextGap(int x) +{ x = (x * 10) / 13; return max(1, x); } -void CombSort(int a[], int l, int r) { +void CombSort(int a[], int l, int r) +{ //Init gap int gap = n; - + //Initialize swapped as true to make sure that loop runs bool swapped = true; //Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) { + while (gap != 1 || swapped) + { //Find next gap gap = FindNextGap(gap); - + swapped = false; // Compare all elements with current gap - for(int i = l; i <= r - gap; ++i) { - if (a[i] > a[i + gap]) { + for (int i = l; i <= r - gap; ++i) + { + if (a[i] > a[i + gap]) + { swap(a[i], a[i + gap]); swapped = true; } @@ -40,12 +45,15 @@ void CombSort(int a[], int l, int r) { } } -int main() { +int main() +{ cin >> n; - for(int i = 1; i <= n; ++i) cin >> a[i]; + for (int i = 1; i <= n; ++i) + cin >> a[i]; CombSort(a, 1, n); - for(int i = 1; i <= n; ++i) cout << a[i] << ' '; + for (int i = 1; i <= n; ++i) + cout << a[i] << ' '; return 0; } diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp new file mode 100644 index 000000000..9948bb821 --- /dev/null +++ b/sorting/heap_sort.cpp @@ -0,0 +1,52 @@ +#include +#include + +void heapify(int *a, int i, int n) { + int largest = i; + const int l = 2 * i + 1; + const int r = 2 * i + 2; + + if (l < n && a[l] > a[largest]) + largest = l; + + if (r < n && a[r] > a[largest]) + largest = r; + + if (largest != i) { + std::swap(a[i], a[largest]); + heapify(a, n, largest); + } +} + +void heapsort(int *a, int n) { + for (int i = n - 1; i >= 0; --i) { + std::swap(a[0], a[i]); + heapify(a, 0, i); + } +} + +void build_maxheap(int *a, int n) { + for (int i = n / 2 - 1; i >= 0; --i) { + heapify(a, i, n); + } +} + +int main() { + int n; + std::cout << "Enter number of elements of array\n"; + std::cin >> n; + int a[20]; + for (int i = 0; i < n; ++i) { + std::cout << "Enter Element " << i << std::endl; + std::cin >> a[i]; + } + + build_maxheap(a, n); + heapsort(a, n); + std::cout << "Sorted Output\n"; + for (int i = 0; i < n; ++i) { + std::cout << a[i] << std::endl; + } + + std::getchar(); +} diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp new file mode 100644 index 000000000..6f1ab6245 --- /dev/null +++ b/sorting/library_sort.cpp @@ -0,0 +1,90 @@ +#include +#include + +void librarySort(int *index, int n) { + int lib_size, index_pos, + *gaps, // gaps + *library[2]; // libraries + + bool target_lib, *numbered; + + for (int i = 0; i < 2; i++) + library[i] = new int[n]; + + gaps = new int[n + 1]; + numbered = new bool[n + 1]; + + lib_size = 1; + index_pos = 1; + target_lib = 0; + library[target_lib][0] = index[0]; + + while (index_pos < n) { + // binary search + int insert = std::distance( + library[target_lib], + std::lower_bound(library[target_lib], + library[target_lib] + lib_size, index[index_pos])); + + // if there is no gap to insert a new index ... + + if (numbered[insert] == true) { + int prov_size = 0, next_target_lib = !target_lib; + + // update library and clear gaps + + for (int i = 0; i <= n; i++) { + if (numbered[i] == true) { + library[next_target_lib][prov_size] = gaps[i]; + prov_size++; + numbered[i] = false; + } + + if (i <= lib_size) { + library[next_target_lib][prov_size] = + library[target_lib][i]; + prov_size++; + } + } + + target_lib = next_target_lib; + lib_size = prov_size - 1; + } else { + numbered[insert] = true; + gaps[insert] = index[index_pos]; + index_pos++; + } + } + + int index_pos_for_output = 0; + for (int i = 0; index_pos_for_output < n; i++) { + if (numbered[i] == true) { + // std::cout << gaps[i] << std::endl; + index[index_pos_for_output] = gaps[i]; + index_pos_for_output++; + } + + if (i < lib_size) { + // std::cout << library[target_lib][i] << std::endl; + index[index_pos_for_output] = library[target_lib][i]; + index_pos_for_output++; + } + } +} + +int main() { + // ---example-- + int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; + int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); + + librarySort(index_ex, n_ex); + std::cout << "sorted array :" << std::endl; + for (int i = 0; i < n_ex; i++) + std::cout << index_ex[i] << " "; + std::cout << std::endl; + + /* --output-- + sorted array : + -12 -8 -6 0 1 1 1 4 5 9 9 + */ +} diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp new file mode 100644 index 000000000..3288b36b0 --- /dev/null +++ b/strings/brute_force_string_searching.cpp @@ -0,0 +1,52 @@ +#include +#include +#include + +using std::string; + +int brute_force(string text, string pattern); +std::vector> test_set = { + // {text, pattern, expected output} + {"a", "aa", "-1"}, + {"a", "a", "0"}, + {"ba", "b", "0"}, + {"bba", "bb", "0"}, + {"bbca", "c", "2"}, + {"ab", "b", "1"} +}; + +int main() { + for (size_t i = 0 ; i < test_set.size(); i++) { + int output = brute_force(test_set[i][0], test_set[i][1]); + if (std::to_string(output) == test_set[i][2]) + std::cout << "success\n"; + else + std::cout << "failure\n"; + } + return 0; +} + +/* + *@description Find a pattern in a string by comparing the pattern + * to every substring. + *@param text Any string that might contain the pattern. + *@param pattern String that we are searching for. + *@return Index where the pattern starts in the text or + * -1 if the pattern was not found. + */ + +int brute_force(string text, string pattern) { + size_t pat_l = pattern.length(); + size_t txt_l = text.length(); + int index = -1; + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l-pat_l+1; i++) { + string s = text.substr(i, pat_l); + if (s == pattern) { + index = i; + break; + } + } + } + return index; +} diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp new file mode 100644 index 000000000..f6f1169d3 --- /dev/null +++ b/strings/knuth_morris_pratt.cpp @@ -0,0 +1,64 @@ +/* + The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text + with complexity O(n + m) + 1) Preprocess pattern to identify any suffixes that are identical to prefixes + This tells us where to continue from if we get a mismatch between a character in our pattern + and the text. + 2) Step through the text one character at a time and compare it to a character in the pattern + updating our location within the pattern if necessary +*/ + +#include +#include +#include +using namespace std; +vector getFailureArray(string pattern){ + int pattern_length=pattern.size(); + vectorfailure(pattern_length+1); + failure[0]=-1; + int j=-1; + for(int i=0; ifailure=getFailureArray(pattern); + int k=0; + for(int j=0; ja[m2]) - return three_part_binary_search(a, x, m2 + 1, high); - } - else - return -1; -} \ No newline at end of file