diff --git a/.github/code-of-conduct.md b/.github/code-of-conduct.md new file mode 100644 index 00000000..f809c8b0 --- /dev/null +++ b/.github/code-of-conduct.md @@ -0,0 +1,40 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/contributing.md b/.github/contributing.md new file mode 100644 index 00000000..01f66006 --- /dev/null +++ b/.github/contributing.md @@ -0,0 +1,3 @@ +## Contributing + +> Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. \ No newline at end of file diff --git a/.github/issue-template.md b/.github/issue-template.md new file mode 100644 index 00000000..99764fe7 --- /dev/null +++ b/.github/issue-template.md @@ -0,0 +1 @@ +I am creating an issue because... diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md new file mode 100644 index 00000000..3bc0935e --- /dev/null +++ b/.github/pull-request-template.md @@ -0,0 +1,6 @@ +I am creating a pull request for... + +- [ ] New algorithm +- [ ] Update to an algorithm +- [ ] Fix an error +- [ ] Other - *Describe below* \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 6886d0f2..00000000 --- a/README.md +++ /dev/null @@ -1,46 +0,0 @@ -
- C Plus Plus Logo -
-
- -
-
-

All ▲lgorithms implemented in C Plus Plus

- - - - - -
-
- algorithms.abranhe.com -
- - -## Contents - -- [Arithmetic Analysis](arithmetic-analysis) -- [File Transfer Protocol](file-transfer-protocol) -- [Greedy Algorithms](greedy-algorithms) -- [Graphs](graphs) -- [Math](math) -- [Neutral Network](neutral-network) -- [Ciphers](ciphers) -- [Data Structures](data-structures) -- [Dynamic Programming](dynamic-programming) -- [Hashes](hashes) -- [Searches](searches) -- [Sorting](sorting) -- [Strings](strings) -- [Traversals](traversals) - -## License - -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) - -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) - -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. - - -[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png diff --git a/algorithms/Networks/Hamming_Code/hamming_code_reciever.cpp b/algorithms/Networks/Hamming_Code/hamming_code_reciever.cpp new file mode 100644 index 00000000..803fbdc5 --- /dev/null +++ b/algorithms/Networks/Hamming_Code/hamming_code_reciever.cpp @@ -0,0 +1,167 @@ +#include +#include +#include +#include +#include +#include +#include +#include + + +using namespace std; + +#define MAX 2048 +#define port 5200 + + +void flip(int &a) { + a=!a; +} + + +void revprint(int codeword[],int n) { + for(int i=n-1;i>=0;i--) { + cout<=1) { + cout<<"Hence flip bit "<=0;i--) { + if((i+1)!=1&&(i+1)!=2&&(i+1)!=4&&(i+1)!=8) { + message[j--]=codeword[i]; + } + } + + cout<<"Message : "; + revprint(message,8); + + int x=0; + for(int i=0;i<8;i++) { + if(message[i]==1) { + x+=(1<>ch; + + switch(ch) { + case 1:{ + cout<<"Recieved Message: "; + revprint(codeword,12); + decoded(codeword); + + cout<<"Meesage Recieved Successfully...!"< +#include +#include +#include +#include +#include + +using namespace std; + +#define MAX 500 +#define port 5200 + + +void tobinary(int a[],char c) { + int x=(int)c; + + cout<=0;i--) { + cout<=0;i--) { + if(a[i]==-1) { + a[i]=b[j]; + j--; + } + } +} + + +int main(){ + + int clientSocket , serverSocket , receiveMsgSize; + + clientSocket = socket(AF_INET , SOCK_STREAM , 0); // creating the socket + + if(clientSocket < 0){ + cout << "Creation of client socket failed" << endl; + return 0; + } + + struct sockaddr_in serverAddr , clientAddr; + + // providing socket with IP and port + serverAddr.sin_family = AF_INET; + serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); + serverAddr.sin_port = htons(port); + + if(connect(clientSocket , (struct sockaddr*) & serverAddr , sizeof(serverAddr)) < 0){ // connecting to the receiver + cout << "Connection Error..!" << endl; + return 0; + } + else{ + cout << "Connection Established..!" << endl; + } + + + char c; + cout<<"Enter the First letter of your name: "; + cin>>c; + + int binary[8]; + tobinary(binary,c); + + cout<<"The entered message in binary is: "; + revprint(binary,8); + + + int codeword[12]; + fillmessageintocodes(codeword,binary); + + + for(int i=0;i<4;i++) { + int count=0; + for(int j=0;j<12;j++) { + if((j+1)&(1< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + + + +void getMacAddress(char *uc_Mac) +{ + int fd; + + struct ifreq ifr; + const char* iface = "enp2s0"; + char* mac; + + fd = socket(AF_INET, SOCK_DGRAM, 0); + + ifr.ifr_addr.sa_family = AF_INET; + strncpy((char *)ifr.ifr_name , (const char *)iface , IFNAMSIZ-1); + + ioctl(fd, SIOCGIFHWADDR, &ifr); + + close(fd); + + mac = (char *)ifr.ifr_hwaddr.sa_data; + + //display mac address + sprintf((char *)uc_Mac,(const char *)"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + +} + +int main() +{ + char mac[32]={0}; + + getMacAddress(mac); + + cout< +#include +int main() +{ +clrscr(); +char string[100],c; +cout<<"Enter the string:\n"; +cin.getline(string,100); +for(int len=0;string[len]!='\0';len++); +int i,j,flag=1; +for(i=0,j=len-1;i +#include +#include +using namespace std; + +struct splay +{ + int key; + splay* lchild; + splay* rchild; +}; + +class SplayTree +{ + public: + SplayTree() + { + } + + // RR(Y rotates to the right) + splay* RR_Rotate(splay* k2) + { + splay* k1 = k2->lchild; + k2->lchild = k1->rchild; + k1->rchild = k2; + return k1; + } + + // LL(Y rotates to the left) + splay* LL_Rotate(splay* k2) + { + splay* k1 = k2->rchild; + k2->rchild = k1->lchild; + k1->lchild = k2; + return k1; + } + + // An implementation of top-down splay tree + splay* Splay(int key, splay* root) + { + if (!root) + return NULL; + splay header; + /* header.rchild points to L tree; + header.lchild points to R Tree */ + header.lchild = header.rchild = NULL; + splay* LeftTreeMax = &header; + splay* RightTreeMin = &header; + while (1) + { + if (key < root->key) + { + if (!root->lchild) + break; + if (key < root->lchild->key) + { + root = RR_Rotate(root); + // only zig-zig mode need to rotate once, + if (!root->lchild) + break; + } + /* Link to R Tree */ + RightTreeMin->lchild = root; + RightTreeMin = RightTreeMin->lchild; + root = root->lchild; + RightTreeMin->lchild = NULL; + } + else if (key > root->key) + { + if (!root->rchild) + break; + if (key > root->rchild->key) + { + root = LL_Rotate(root); + // only zag-zag mode need to rotate once, + if (!root->rchild) + break; + } + /* Link to L Tree */ + LeftTreeMax->rchild = root; + LeftTreeMax = LeftTreeMax->rchild; + root = root->rchild; + LeftTreeMax->rchild = NULL; + } + else + break; + } + /* assemble L Tree, Middle Tree and R tree */ + LeftTreeMax->rchild = root->lchild; + RightTreeMin->lchild = root->rchild; + root->lchild = header.rchild; + root->rchild = header.lchild; + return root; + } + + splay* New_Node(int key) + { + splay* p_node = new splay; + if (!p_node) + { + fprintf(stderr, "Out of memory!\n"); + exit(1); + } + p_node->key = key; + p_node->lchild = p_node->rchild = NULL; + return p_node; + } + + splay* Insert(int key, splay* root) + { + static splay* p_node = NULL; + if (!p_node) + p_node = New_Node(key); + else + p_node->key = key; + if (!root) + { + root = p_node; + p_node = NULL; + return root; + } + root = Splay(key, root); + /* This is BST that, all keys <= root->key is in root->lchild, all keys > + root->key is in root->rchild. */ + if (key < root->key) + { + p_node->lchild = root->lchild; + p_node->rchild = root; + root->lchild = NULL; + root = p_node; + } + else if (key > root->key) + { + p_node->rchild = root->rchild; + p_node->lchild = root; + root->rchild = NULL; + root = p_node; + } + else + return root; + p_node = NULL; + return root; + } + + splay* Delete(int key, splay* root) + { + splay* temp; + if (!root) + return NULL; + root = Splay(key, root); + if (key != root->key) + return root; + else + { + if (!root->lchild) + { + temp = root; + root = root->rchild; + } + else + { + temp = root; + /*Note: Since key == root->key, + so after Splay(key, root->lchild), + the tree we get will have no right child tree.*/ + root = Splay(key, root->lchild); + root->rchild = temp->rchild; + } + free(temp); + return root; + } + } + + splay* Search(int key, splay* root) + { + return Splay(key, root); + } + + void InOrder(splay* root) + { + if (root) + { + InOrder(root->lchild); + cout<< "key: " <key; + if(root->lchild) + cout<< " | left child: "<< root->lchild->key; + if(root->rchild) + cout << " | right child: " << root->rchild->key; + cout<< "\n"; + InOrder(root->rchild); + } + } +}; + +int main() +{ + SplayTree st; + int vector[10] = {9,8,7,6,5,4,3,2,1,0}; + splay *root; + root = NULL; + const int length = 10; + int i; + for(i = 0; i < length; i++) + root = st.Insert(vector[i], root); + cout<<"\nInOrder: \n"; + st.InOrder(root); + int input, choice; + while(1) + { + cout<<"\nSplay Tree Operations\n"; + cout<<"1. Insert "<>choice; + switch(choice) + { + case 1: + cout<<"Enter value to be inserted: "; + cin>>input; + root = st.Insert(input, root); + cout<<"\nAfter Insert: "<>input; + root = st.Delete(input, root); + cout<<"\nAfter Delete: "<>input; + root = st.Search(input, root); + cout<<"\nAfter Search "< +using namespace std; + +// A Linked List node +struct Node +{ + int data; + Node* next; +}; + +// Returns true if first list is present in second +// list +bool findList(Node* first, Node* second) +{ + Node* ptr1 = first, *ptr2 = second; + + // If both linked lists are empty, return true + if (first == NULL && second == NULL) + return true; + + // Else If one is empty and other is not return + // false + if ( first == NULL || + (first != NULL && second == NULL)) + return false; + + // Traverse the second list by picking nodes + // one by one + while (second != NULL) + { + // Initialize ptr2 with current node of second + ptr2 = second; + + // Start matching first list with second list + while (ptr1 != NULL) + { + // If second list becomes empty and first + // not then return false + if (ptr2 == NULL) + return false; + + // If data part is same, go to next + // of both lists + else if (ptr1->data == ptr2->data) + { + ptr1 = ptr1->next; + ptr2 = ptr2->next; + } + + // If not equal then break the loop + else break; + } + + // Return true if first list gets traversed + // completely that means it is matched. + if (ptr1 == NULL) + return true; + + // Initialize ptr1 with first again + ptr1 = first; + + // And go to next node of second list + second = second->next; + } + + return false; +} + +/* Function to print nodes in a given linked list */ +void printList(Node* node) +{ + while (node != NULL) + { + printf("%d ", node->data); + node = node->next; + } +} + +// Function to add new node to linked lists +Node *newNode(int key) +{ + Node *temp = new Node; + temp-> data= key; + temp->next = NULL; + return temp; +} + +/* Driver program to test above functions*/ +int main() +{ + /* Let us create two linked lists to test + the above functions. Created lists shall be + a: 1->2->3->4 + b: 1->2->1->2->3->4*/ + Node *a = newNode(1); + a->next = newNode(2); + a->next->next = newNode(3); + a->next->next->next = newNode(4); + + Node *b = newNode(1); + b->next = newNode(2); + b->next->next = newNode(1); + b->next->next->next = newNode(2); + b->next->next->next->next = newNode(3); + b->next->next->next->next->next = newNode(4); + + findList(a,b) ? cout << "LIST FOUND" : + cout << "LIST NOT FOUND"; + + return 0; +} diff --git a/algorithms/artificial-intelligence/TicTac(maxmin).cpp b/algorithms/artificial-intelligence/TicTac(maxmin).cpp new file mode 100644 index 00000000..963a6659 --- /dev/null +++ b/algorithms/artificial-intelligence/TicTac(maxmin).cpp @@ -0,0 +1,242 @@ +#include +#include +using namespace std; +const int M = 3; +const int N = 3; +int c=0; +struct Move +{ + int row, col; +}; +bool isMovesLeft(string Game[M][N]) +{ + for (int i = 0; i bestVal) + { + bestMove.row = i; + bestMove.col = j; + } + } + } + } + return bestMove; +} +void display(string Game[M][N]) +{ + cout << " " << Game[0][0] << " | " << Game[0][1] << " | " << Game[0][2] << " " << endl + << "---+---+---" << endl + << " " << Game[1][0] << " | " << Game[1][1] << " | " << Game[1][2] << " " << endl + << "---+---+---" << endl + << " " << Game[2][0] << " | " << Game[2][1] << " | " << Game[2][2] << " " << endl; +} +int main() +{ + string Game[M][N]; + int l,m; + int b=0; + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + Game[i][j]=" "; + } + } + display(Game); + for(int k=0;k>=0;k++) + { + if(b==0) + { + cout<<"Enter the move of Player 1(write Rowno. and ColNo.) "<>l>>m; + if(Game[l-1][m-1]==" ") + { + Game[l-1][m-1]="x"; + c++; + b++; + display(Game); + if((Game[0][0]=="x" && Game[0][1]=="x" && Game[0][2]=="x" )|| (Game[1][0]=="x" && Game[1][1]=="x" && Game[1][2]=="x") || (Game[2][0]=="x" && Game[2][1]=="x" && Game[2][2]=="x") || (Game[0][2]=="x" && Game[1][2]=="x" && Game[2][2]=="x") || (Game[0][1]=="x" && Game[1][1]=="x" && Game[2][1]=="x") || (Game[0][0]=="x" && Game[1][0]=="x" && Game[2][0]=="x") || (Game[0][0]=="x" && Game[1][1]=="x" && Game[2][2]=="x") || (Game[0][2]=="x" && Game[1][1]=="x" && Game[2][0]=="x")) + { + cout<<"Player 1 Wins"<4) + { + Move bestMove = findBestMove(Game); + int k=bestMove.row; + int l=bestMove.col; + Game[k+1][l+1]="O"; + } + else + { + { + srand(time(0)); + int computer= (rand()%9)+1; + int row=(computer-1)/3; + int col=(computer-1)%3; + if(Game[row][col]=="x" || Game[row][col]=="O") + { + continue; + } + else + { + Game[row][col]="O"; + } + } + } + + c++; + b--; + display(Game); + if((Game[0][0]=="x" && Game[0][1]=="x" && Game[0][2]=="x" )|| (Game[1][0]=="x" && Game[1][1]=="x" && Game[1][2]=="x") || (Game[2][0]=="x" && Game[2][1]=="x" && Game[2][2]=="x") || (Game[0][2]=="x" && Game[1][2]=="x" && Game[2][2]=="x") || (Game[0][1]=="x" && Game[1][1]=="x" && Game[2][1]=="x") || (Game[0][0]=="x" && Game[1][0]=="x" && Game[2][0]=="x") || (Game[0][0]=="x" && Game[1][1]=="x" && Game[2][2]=="x") || (Game[0][2]=="x" && Game[1][1]=="x" && Game[2][0]=="x")) + { + cout<<"Player 1 Wins"< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +// SAT Solver +// CDCL Solver +// Author togatoga +// https://github.com/togatoga/Togasat +namespace togasat +{ +using Var = int; +using CRef = int; +using lbool = int; +const CRef CRef_Undef = -1; +class Solver +{ + +private: + const lbool l_True = 0; + const lbool l_False = 1; + const lbool l_Undef = 2; + + const int var_Undef = -1; + + // Literal + struct Lit + { + int x; + inline bool operator==(Lit p) const + { + return x == p.x; + } + inline bool operator!=(Lit p) const + { + return x != p.x; + } + inline bool operator<(Lit p) const + { + return x < p.x; + } + inline Lit operator~() + { + Lit q; + q.x = x ^ 1; + return q; + } + }; + + inline Lit mkLit(Var var, bool sign) + { + Lit p; + p.x = var + var + sign; + return p; + } + inline bool sign(Lit p) const + { + return p.x & 1; + } + inline int var(Lit p) const + { + return p.x >> 1; + } + inline int toInt(Var v) + { + return v; + } + inline int toInt(Lit p) + { + return p.x; + } + inline Lit toLit(int x) + { + Lit p; + p.x = x; + return p; + } + const Lit lit_Undef = {-2}; + + // lifted boolean + // VarData + struct VarData + { + CRef reason; + int level; + }; + inline VarData mkVarData(CRef cr, int l) + { + VarData d = {cr, l}; + return d; + } + // Watcher + struct Watcher + { + CRef cref; + Lit blocker; + Watcher() + { + } + Watcher(CRef cr, Lit p) : cref(cr), blocker(p) + { + } + bool operator==(const Watcher &w) const + { + return cref == w.cref; + } + bool operator!=(const Watcher &w) const + { + return cref != w.cref; + } + }; + + // Clause + class Clause + { + public: + struct + { + bool learnt; + int size; + } header; + std::vector data; //(x1 v x2 v not x3) + Clause() + { + } + Clause(const std::vector &ps, bool learnt) + { + header.learnt = learnt; + header.size = ps.size(); + //data = move(ps); + data.resize(header.size); + for (size_t i = 0; i < ps.size(); i++) + data[i] = ps[i]; + // //data.emplace_back(ps[i]); + } + + int size() const + { + return header.size; + } + bool learnt() const + { + return header.learnt; + } + Lit &operator[](int i) + { + return data[i]; + } + Lit operator[](int i) const + { + return data[i]; + } + }; + + CRef allocClause(std::vector &ps, bool learnt = false) + { + static CRef res = 0; + ca[res] = Clause(ps, learnt); + return res++; + } + + Var newVar(bool sign = true, bool dvar = true) + { + int v = nVars(); + + assigns.emplace_back(l_Undef); + vardata.emplace_back(mkVarData(CRef_Undef, 0)); + activity.emplace_back(0.0); + seen.push_back(false); + polarity.push_back(sign); + decision.push_back(0); + setDecisionVar(v, dvar); + return v; + } + + bool addClause_(std::vector &ps) + { + //std::sort(ps.begin(), ps.end()); + // empty clause + if (ps.size() == 0) + return false; + else if (ps.size() == 1) + uncheckedEnqueue(ps[0]); + else + { + CRef cr = allocClause(ps, false); + //clauses.insert(cr); + attachClause(cr); + } + + return true; + } + void attachClause(CRef cr) + { + const Clause &c = ca[cr]; + + assert(c.size() > 1); + + watches[(~c[0]).x].emplace_back(Watcher(cr, c[1])); + watches[(~c[1]).x].emplace_back(Watcher(cr, c[0])); + } + + // Input + void readClause(const std::string &line, std::vector &lits) + { + lits.clear(); + int var; + var = 0; + std::stringstream ss(line); + while (ss) + { + int val; + ss >> val; + if (val == 0) + break; + var = abs(val) - 1; + while (var >= nVars()) + newVar(); + lits.emplace_back(val > 0 ? mkLit(var, false) : mkLit(var, true)); + } + } + + std::unordered_map ca; // store clauses + std::unordered_set clauses; // original problem; + std::unordered_set learnts; + std::unordered_map> watches; + std::vector vardata; // store reason and level for each variable + std::vector polarity; // The preferred polarity of each variable + std::vector decision; + std::vector seen; + // Todo + size_t qhead; + std::vector trail; + std::vector trail_lim; + // Todo rename(not heap) + std::set> order_heap; + std::vector activity; + double var_inc; + std::vector model; + std::vector conflict; + int nVars() const + { + return vardata.size(); + } + int decisionLevel() const + { + return trail_lim.size(); + } + void newDecisionLevel() + { + trail_lim.emplace_back(trail.size()); + } + + inline CRef reason(Var x) const + { + return vardata[x].reason; + } + inline int level(Var x) const + { + return vardata[x].level; + } + inline void varBumpActivity(Var v) + { + std::pair p = std::make_pair(activity[v], v); + activity[v] += var_inc; + if (order_heap.erase(p) == 1) + order_heap.emplace(std::make_pair(activity[v], v)); + + if (activity[v] > 1e100) + { + //Rescale + std::set> tmp_order; + tmp_order = std::move(order_heap); + order_heap.clear(); + for (int i = 0; i < nVars(); i++) + activity[i] *= 1e-100; + for (auto &val : tmp_order) + order_heap.emplace(std::make_pair(activity[val.second], val.second)); + var_inc *= 1e-100; + } + } + bool satisfied(const Clause &c) const + { + for (int i = 0; i < c.size(); i++) + if (value(c[i]) == l_True) + return true; + + return false; + } + lbool value(Var p) const + { + return assigns[p]; + } + lbool value(Lit p) const + { + if (assigns[var(p)] == l_Undef) + return l_Undef; + return assigns[var(p)] ^ sign(p); + } + void setDecisionVar(Var v, bool b) + { + decision[v] = b; + order_heap.emplace(std::make_pair(0.0, v)); + } + void uncheckedEnqueue(Lit p, CRef from = CRef_Undef) + { + assert(value(p) == l_Undef); + assigns[var(p)] = sign(p); + vardata[var(p)] = mkVarData(from, decisionLevel()); + trail.emplace_back(p); + } + // decision + Lit pickBranchLit() + { + Var next = var_Undef; + while (next == var_Undef or value(next) != l_Undef) + { + if (order_heap.empty()) + { + next = var_Undef; + break; + } + else + { + auto p = *order_heap.rbegin(); + next = p.second; + order_heap.erase(p); + } + } + return next == var_Undef ? lit_Undef : mkLit(next, polarity[next]); + } + // clause learning + void analyze(CRef confl, std::vector &out_learnt, int &out_btlevel) + { + int pathC = 0; + Lit p = lit_Undef; + int index = trail.size() - 1; + out_learnt.emplace_back(mkLit(0, false)); + do + { + assert(confl != CRef_Undef); + Clause &c = ca[confl]; + for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++) + { + Lit q = c[j]; + if (not seen[var(q)] and level(var(q)) > 0) + { + varBumpActivity(var(q)); + seen[var(q)] = 1; + if (level(var(q)) >= decisionLevel()) + pathC++; + else + out_learnt.emplace_back(q); + } + } + while (not seen[var(trail[index--])]) + ; + p = trail[index + 1]; + confl = reason(var(p)); + seen[var(p)] = 0; + pathC--; + } while (pathC > 0); + + out_learnt[0] = ~p; + + // unit clause + if (out_learnt.size() == 1) + out_btlevel = 0; + else + { + int max_i = 1; + for (size_t i = 2; i < out_learnt.size(); i++) + if (level(var(out_learnt[i])) > level(var(out_learnt[max_i]))) + max_i = i; + + Lit p = out_learnt[max_i]; + out_learnt[max_i] = out_learnt[1]; + out_learnt[1] = p; + out_btlevel = level(var(p)); + } + + for (size_t i = 0; i < out_learnt.size(); i++) + seen[var(out_learnt[i])] = false; + } + + // backtrack + void cancelUntil(int level) + { + if (decisionLevel() > level) + { + for (int c = trail.size() - 1; c >= trail_lim[level]; c--) + { + Var x = var(trail[c]); + assigns[x] = l_Undef; + polarity[x] = sign(trail[c]); + order_heap.emplace(std::make_pair(activity[x], x)); + } + qhead = trail_lim[level]; + trail.erase(trail.end() - (trail.size() - trail_lim[level]), trail.end()); + trail_lim.erase(trail_lim.end() - (trail_lim.size() - level), + trail_lim.end()); + } + } + CRef propagate() + { + CRef confl = CRef_Undef; + int num_props = 0; + while (qhead < trail.size()) + { + Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. + std::vector &ws = watches[p.x]; + std::vector::iterator i, j, end; + num_props++; + + for (i = j = ws.begin(), end = i + ws.size(); i != end;) + { + // Try to avoid inspecting the clause: + Lit blocker = i->blocker; + if (value(blocker) == l_True) + { + *j++ = *i++; + continue; + } + + CRef cr = i->cref; + Clause &c = ca[cr]; + Lit false_lit = ~p; + if (c[0] == false_lit) + c[0] = c[1], c[1] = false_lit; + assert(c[1] == false_lit); + i++; + + Lit first = c[0]; + Watcher w = Watcher(cr, first); + if (first != blocker && value(first) == l_True) + { + *j++ = w; + continue; + } + + // Look for new watch: + for (int k = 2; k < c.size(); k++) + if (value(c[k]) != l_False) + { + c[1] = c[k]; + c[k] = false_lit; + watches[(~c[1]).x].emplace_back(w); + goto NextClause; + } + *j++ = w; + if (value(first) == l_False) // conflict + { + confl = cr; + qhead = trail.size(); + while (i < end) + *j++ = *i++; + } + else + uncheckedEnqueue(first, cr); + NextClause:; + } + int size = i - j; + ws.erase(ws.end() - size, ws.end()); + } + return confl; + } + + static double luby(double y, int x) + { + + // Find the finite subsequence that contains index 'x', and the + // size of that subsequence: + int size, seq; + for (size = 1, seq = 0; size < x + 1; seq++, size = 2 * size + 1) + ; + + while (size - 1 != x) + { + size = (size - 1) >> 1; + seq--; + x = x % size; + } + + return std::pow(y, seq); + } + + lbool search(int nof_conflicts) + { + int backtrack_level; + std::vector learnt_clause; + learnt_clause.emplace_back(mkLit(-1, false)); + int conflictC = 0; + while (true) + { + CRef confl = propagate(); + + if (confl != CRef_Undef) + { + // CONFLICT + conflictC++; + if (decisionLevel() == 0) + return l_False; + learnt_clause.clear(); + analyze(confl, learnt_clause, backtrack_level); + cancelUntil(backtrack_level); + if (learnt_clause.size() == 1) + uncheckedEnqueue(learnt_clause[0]); + else + { + CRef cr = allocClause(learnt_clause, true); + //learnts.insert(cr); + attachClause(cr); + uncheckedEnqueue(learnt_clause[0], cr); + } + //varDecay + var_inc *= 1.05; + } + else + { + // NO CONFLICT + if ((nof_conflicts >= 0 and conflictC >= nof_conflicts)) + { + cancelUntil(0); + return l_Undef; + } + Lit next = pickBranchLit(); + + if (next == lit_Undef) + return l_True; + newDecisionLevel(); + uncheckedEnqueue(next); + } + } + } + +public: + std::vector assigns; // The current assignments (ex assigns[0] = 0 -> + // X1 = True, assigns[1] = 1 -> X2 = False) + lbool answer; // SATISFIABLE 0 UNSATISFIABLE 1 UNKNOWN 2 + Solver() + { + qhead = 0; + } + void parseDimacsProblem(std::string problem_name) + { + std::vector lits; + int vars = 0; + int clauses = 0; + std::string line; + std::ifstream ifs(problem_name, std::ios_base::in); + while (ifs.good()) + { + getline(ifs, line); + if (line.size() > 0) + { + if (line[0] == 'p') + sscanf(line.c_str(), "p cnf %d %d", &vars, &clauses); + else if (line[0] == 'c' or line[0] == 'p') + continue; + else + { + readClause(line, lits); + if (lits.size() > 0) + addClause_(lits); + } + } + } + ifs.close(); + } + lbool solve() + { + model.clear(); + conflict.clear(); + lbool status = l_Undef; + answer = l_Undef; + var_inc = 1.01; + int curr_restarts = 0; + double restart_inc = 2; + double restart_first = 100; + while (status == l_Undef) + { + double rest_base = luby(restart_inc, curr_restarts); + status = search(rest_base * restart_first); + curr_restarts++; + } + answer = status; + return status; + } + + void addClause(std::vector &clause) + { + std::vector lits; + lits.resize(clause.size()); + for (size_t i = 0; i < clause.size(); i++) + { + int var = abs(clause[i]) - 1; + while (var >= nVars()) + newVar(); + lits[i] = clause[i] > 0 ? mkLit(var, false) : mkLit(var, true); + } + addClause_(lits); + } + void printAnswer() + { + if (answer == 0) + { + std::cout << "SAT" << std::endl; + for (size_t i = 0; i < assigns.size(); i++) + { + if (assigns[i] == 0) + std::cout << (i + 1) << " "; + else + std::cout << -(i + 1) << " "; + } + std::cout << "0" << std::endl; + } + else + std::cout << "UNSAT" << std::endl; + } +}; +} // namespace togasat \ No newline at end of file diff --git a/algorithms/backtracking/All_Codes_Recursion.cpp b/algorithms/backtracking/All_Codes_Recursion.cpp new file mode 100644 index 00000000..726efea0 --- /dev/null +++ b/algorithms/backtracking/All_Codes_Recursion.cpp @@ -0,0 +1,89 @@ +/* + +Problem Statement + +Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. +You are given a numeric string S. +Write a program to return the list of all possible codes that can be generated from the given string. + +For Example - +Input: +1123 + +Output: +aabc +kbc +alc +aaw +kw + +Being a recursive solution, this won't work for large inputs. But we can use DP to make it work for Large results. + +*/ + + +#include +#include +using namespace std; + +int getString(string str) { + int res = 99999; + if(str.size() == 1) { + int num = str[0] - '0'; + //c = 'a' + (num-1); + return num-1; + } + else if(str.size() > 1) { + int num = ((str[0] - '0')*10) + (str[1] - '0'); + if(num > 26) { + return res; + } + else { + //c = 'a' + (num-1); + return num-1; + } + + } + + return res; + +} + +int helper(string input, string curString, string modString, string output[10000]) { + static int i; + int cs = getString(curString); + if(input.empty() && cs < 27) { + modString +=('a' + cs); + output[i++] = modString; + return i; + } + + if(cs < 27) { + modString +=('a' + cs); + } + + int count = helper(input.substr(1),input.substr(0,1),modString,output); + if(input.length() > 1) { + int check = getString(input.substr(0,2)); + if(check < 27) { + count = helper(input.substr(2),input.substr(0,2),modString,output); + } + } + return count; + } + + +int getCodes(string input, string output[10000]) { + return helper(input,"","",output); +} + +int main(){ + string input; + cin >> input; + + string output[10000]; + int count = getCodes(input, output); + for(int i = 0; i < count && i < 10000; i++) + cout << output[i] << endl; + return 0; +} diff --git a/algorithms/backtracking/N-Queen Problem.cpp b/algorithms/backtracking/N-Queen Problem.cpp new file mode 100644 index 00000000..29adf965 --- /dev/null +++ b/algorithms/backtracking/N-Queen Problem.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +void queen(int row,int n); +int board[20],count; +void main() +{ + int n,i,j; + clrscr(); + printf(".....N Queens Problem Using Backtracking.....\n"); + printf("Enter number of Queens: "); + scanf("%d",&n); + queen(1,n); + getch(); +} +void print(int n) +{ + int i,j; + printf("\nSolution %d:\n`",++count); + for(i=1;i<=n;++i) + printf("\t%d",i); + for(i=1;i<=n;++i) + { + printf("\n\n%d\t",i); + for(j=1;j<=n;++j) + { + if(board[i]==j) + printf("Q%d\t",i); + else + printf("--\t"); + } + } +} +int place(int row,int column) +{ + int i; + for(i=1;i<=row-1;++i) + { + if(board[i]==column) + return 0; + else + if(abs(board[i]-column)==abs(i-row)) + return 0; + } + return 1; +} +void queen(int row,int n) +{ + int column; + for(column=1;column<=n;++column) + { + if(place(row,column)) + { + board[row]=column; + if(row==n) + print(n); + else + queen(row+1,n); + } + } +} \ No newline at end of file diff --git a/algorithms/backtracking/crossword_puzzle.cpp b/algorithms/backtracking/crossword_puzzle.cpp new file mode 100644 index 00000000..d8c200d1 --- /dev/null +++ b/algorithms/backtracking/crossword_puzzle.cpp @@ -0,0 +1,171 @@ +#include +using namespace std; + +// ways are to calculate the number of +// possible ways to fill the grid +int ways = 0; + +// this function is used to print +// the resultant matrix +void printMatrix(vector& matrix, int n) +{ + for (int i = 0; i < n; i++) + cout << matrix[i] << endl; +} + +// this function checks for the current word +// if it can be placed horizontally or not +// x -> it represent index of row +// y -> it represent index of column +// currentWord -> it represent the +// current word in word array +vector checkHorizontal(int x, int y, + vector matrix, + string currentWord) +{ + int n = currentWord.length(); + + for (int i = 0; i < n; i++) { + if (matrix[x][y + i] == '#' || + matrix[x][y + i] == currentWord[i]) { + matrix[x][y + i] = currentWord[i]; + } + else { + + // this shows that word cannot + // be placed horizontally + matrix[0][0] = '@'; + return matrix; + } + } + + return matrix; +} + +// this function checks for the current word +// if it can be placed vertically or not +// x -> it represent index of row +// y -> it represent index of column +// currentWord -> it represent the +// current word in word array +vector checkVertical(int x, int y, + vector matrix, + string currentWord) +{ + int n = currentWord.length(); + + for (int i = 0; i < n; i++) { + if (matrix[x + i][y] == '#' || + matrix[x + i][y] == currentWord[i]) { + matrix[x + i][y] = currentWord[i]; + } + else { + + // this shows that word + // cannot be placed vertically + matrix[0][0] = '@'; + return matrix; + } + } + return matrix; +} + +// this function recursively checks for every +// word that can align vertically in one loop +// and in another loop it checks for those words +// that can align horizontally words -> it +// contains all the words to fill in a crossword +// puzzle matrix -> it contain the current +// state of crossword index -> it represent +// the index of current word n -> it represent +// the length of row or column of the square matrix +void solvePuzzle(vector& words, + vector matrix, + int index, int n) +{ + if (index < words.size()) { + string currentWord = words[index]; + int maxLen = n - currentWord.length(); + + // loop to check the words that can align vertically. + for (int i = 0; i < n; i++) { + for (int j = 0; j <= maxLen; j++) { + vector temp = checkVertical(j, i, + matrix, currentWord); + + if (temp[0][0] != '@') { + solvePuzzle(words, temp, index + 1, n); + } + } + } + + // loop to check the words that can align horizontally. + for (int i = 0; i < n; i++) { + for (int j = 0; j <= maxLen; j++) { + vector temp = checkHorizontal(i, j, + matrix, currentWord); + + if (temp[0][0] != '@') { + solvePuzzle(words, temp, index + 1, n); + } + } + } + } + else { + // calling of print function to + // print the crossword puzzle + cout << (ways + 1) << " way to solve the puzzle " + << endl; + printMatrix(matrix, n); + cout << endl; + + // increase the ways + ways++; + return; + } +} + +// Driver Code +int main() +{ + // length of grid + int n1 = 10; + + // matrix to hold the grid of puzzle + vector matrix; + + // take input of puzzle in matrix + // input of grid of size n1 x n1 + matrix.push_back("*#********"); + matrix.push_back("*#********"); + matrix.push_back("*#****#***"); + matrix.push_back("*##***##**"); + matrix.push_back("*#****#***"); + matrix.push_back("*#****#***"); + matrix.push_back("*#****#***"); + matrix.push_back("*#*######*"); + matrix.push_back("*#********"); + matrix.push_back("***#######"); + + vector words; + + // the words matrix will hold all + // the words need to be filled in the grid + words.push_back("PUNJAB"); + words.push_back("JHARKHAND"); + words.push_back("MIZORAM"); + words.push_back("MUMBAI"); + + // initialize the number of ways + // to solve the puzzle to zero + ways = 0; + + // recursive function to solve the puzzle + // Here 0 is the initial index of words array + // n1 is length of grid + solvePuzzle(words, matrix, 0, n1); + cout << "Number of ways to fill the grid is " + << ways << endl; + + return 0; +} diff --git a/algorithms/backtracking/sudoku_solver.cc b/algorithms/backtracking/sudoku_solver.cc new file mode 100644 index 00000000..898d79b6 --- /dev/null +++ b/algorithms/backtracking/sudoku_solver.cc @@ -0,0 +1,107 @@ +/* +https://leetcode.com/problems/sudoku-solver/ + +Sudoku Solver +============== + +Write a program to solve a Sudoku puzzle by filling the empty cells. + +Empty cells are indicated by the character '.'. + +You may assume that there will be only one unique solution. + +![before filled](http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png) +A sudoku puzzle... + +![after filled](http://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png) +...and its solution numbers marked in red. +*/ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { + static const int kSize = 9; + bool rowUsed[kSize][kSize]; + bool colUsed[kSize][kSize]; + bool areaUsed[kSize][kSize]; + +public: + bool backtrack(vector >& board, int r, int c) { + if(r >= kSize) return true; // the last cell. + if(c >= kSize) return backtrack(board, r+1, 0); // row complete, move to next row. + if(isdigit(board[r][c])) return backtrack(board, r, c+1); // skip the given cell. + + // empty cell, try each value [0-9] to fill it. + for(int num = 1; num <= kSize; ++num) { + int area = (r/3) * 3 + (c/3); + if(rowUsed[r][num] || colUsed[num][c] || areaUsed[area][num]) { + continue; + } + + // emplace num as char. + board[r][c] = num + '0'; + rowUsed[r][num] = colUsed[num][c] = areaUsed[area][num] = true; + + // try next position... + if(backtrack(board, r, c+1)) return true; // stop searching when the first solution found. + + // can not continue to place, backtrack. + board[r][c] = '.'; + rowUsed[r][num] = colUsed[num][c] = areaUsed[area][num] = false; + } + return false; + } + + void solveSudoku(vector >& board) { + memset(rowUsed, false, sizeof(rowUsed)); + memset(colUsed, false, sizeof(colUsed)); + memset(areaUsed, false, sizeof(areaUsed)); + vector > result(board); + if (backtrack(result, 0, 0)) { // found solution + board = result; // copy back + } + } +}; + +template +void printMatrix(Matrix m) +{ + for(int i = 0; i < m.size(); i++) { + for(int j = 0; j < m[i].size(); j++) { + cout << m[i][j]; + } + cout << "\n"; + } + cout << endl; +} + +// get sudoku puzzle from sudokupuzzle.org: +// curl -s "http://sudokupuzzle.org/online2.php?nd=0&y=`date +%Y\&m=%m\&d=%d`" | grep tmda= | sed "s/.*tmda='//g" | cut -c -81 + +int main(int argc, char* argv[]) +{ + const int N = 9; + vector > board; + string puzzle = argc > 1 ? argv[1] : "000005001097004000005620008951060873804510209063700050149076080032041690780350402"; + + board.resize(N); + for (int i = 0; i < N; i++) { + board[i].resize(N); + for (int j = 0; j < N; j++) { + const char c = puzzle[i*N + j]; + board[i][j] = (c == '0' ? '.' : c); + } + } + printMatrix(board); + + Solution().solveSudoku(board); + printMatrix(board); + + return 0; +} + diff --git a/algorithms/data-structures/BinaryIndexedTree2d.cpp b/algorithms/data-structures/BinaryIndexedTree2d.cpp new file mode 100644 index 00000000..a840eb87 --- /dev/null +++ b/algorithms/data-structures/BinaryIndexedTree2d.cpp @@ -0,0 +1,35 @@ +// Binary Indexed Tree of sum in 2d array +// AbraaoCF - UFCG +#include +using namespace std; +#define maxx 1100 +int bit[maxx][maxx]; +void update(int idx, int idy, int value) +{ + while(idx <= maxx) + { + int idy_temp = idy; + while(idy_temp <= maxx) + { + bit[idx][idy_temp] += value; + idy_temp += (idy_temp &-idy_temp); + } + idx += (idx&-idx); + } + return; +} +int query(int idx,int idy) +{ + int sum = 0; + while(idx > 0) + { + int idy_temp = idy; + while(idy_temp > 0) + { + sum += bit[idx][idy_temp]; + idy_temp -= (idy_temp &-idy_temp); + } + idx -= (idx&-idx); + } + return sum; +} diff --git a/algorithms/data-structures/BinarySearchTree.cpp b/algorithms/data-structures/BinarySearchTree.cpp new file mode 100644 index 00000000..970e7c6a --- /dev/null +++ b/algorithms/data-structures/BinarySearchTree.cpp @@ -0,0 +1,170 @@ +#include +#define ll long long int +#define ull unsigned long long int +#define pb push_back +#define MIN 2 +#define sc(n) scanf("%d",&n) +#define pr(n) printf("%d",n) +#define gc getchar_unlocked +#define AC 0 +#define MOD 1000000007 +#define mp make_pair +#define vc vector +#define wh(n) while(n--) +#define ite(type,datatype,name) type::iterator name +#define gt goto + +using namespace std; + + /*Structure of node*/ +struct node{ + int data; + struct node *left,*right; +}; + /*Create a new Node*/ +struct node *newnode(int p){ + struct node *temp = new node(); + temp->data = p; + temp->left = temp->right = NULL; + return temp; +} + + /*Insert a new Node in BST*/ +struct node *insert(struct node *root,int p){ + if(root == NULL){ + return newnode(p); + } + if(root->data > p){ + root->left = insert(root->left,p); + } + else{ + root->right = insert(root->right,p); + } + return root; +} +/* Display BST */ +void display(struct node *root){ + if(root != NULL){ + cout<data<<" "; //Pre-Order + display(root->left); + // cout<data<<" "; + display(root->right); + + } +} + /*Return node with minimum value*/ +struct node *minvalue(struct node *root){ + struct node *curr = root; + + while(curr->left != NULL){ + curr = curr->left; + } + return curr; +} + +/* Delete node with given key value in BST */ +struct node *del(struct node* root,int key){ + //Base case for root + if(root == NULL) return root; + if(root->data > key){ + root->left = del(root->left,key); + } + else if(root->data < key){ + root->right = del(root->right,key); + } + else{ + //noDe has one or nO noDe + if(root->left == NULL){ + struct node *temp = root->right; + free(root); + return temp; + } + else if(root->right == NULL){ + struct node *temp = root->left; + free(root); + return temp; + } + //tWo chiLd + struct node *temp = minvalue(root->right); + root->data = temp->data; + root->right = del(root->right,temp->data); + } + return root; +} + + /* Return height of BST */ +int maxheight(struct node *node){ + if(node == NULL){ + return 0; + } + int lh = maxheight(node->left); + int rh = maxheight(node->right); + + if(lh>rh) return (lh+1); + else return (rh+1); +} +/* return the search value for given key */ +int search(struct node* temp,int key){ + int p=key; + while(1){ + if(temp->data == key){ + return p; + } + else if(temp->data > key){ + p = max(p,temp->data); + temp = temp->left; + } + else if(temp->data < key){ + temp = temp->right; + } + } + return p; +} + + /*Print BST in zigzag Pattern */ +void zigzeg(struct node* root){ + stack s[2]; + int curr = 0; + int oth = 1; + s[curr].push(root->data); + struct node* temp1 = root; + struct node* temp2 = root; + while((!s[curr].empty()) || (!s[oth].empty())){ + if(curr == 0){ + int p = s[curr].top(); + s[curr].pop(); + s[oth].push(temp1->left->data); + s[oth].push(temp1->right->data); + temp1= temp1->right; + cout<right->data); + s[curr].push(temp1->left->data); + temp1= temp1->left; + cout< +#include + +using namespace std; + +int main() +{ + +struct node{ + int info; + node *next; +}*ptr,*head,*start; + +int c=1,data; + +ptr=new node; +ptr->next=NULL; + +start=head=ptr; + +while(c<3 && c>0){ + cout<<"1.Insert\n2.Link List\n"; + cin>>c; + + switch(c){ + case 1: + cout<<"Enter Data\n"; + cin>>data; + + ptr=new node; + ptr->next=start; + ptr->info=data; + + head->next=ptr; + head=ptr; + + break; + + case 2: + ptr=start->next; + + while(ptr!=start && ptr!=NULL){ + cout<info<<"->"; + ptr=ptr->next; + } + cout<<"\n"; + break; + + default: + cout<<"Wrong Choice\nExiting...\n"; + } + +} + +getch(); +return 0; +} \ No newline at end of file diff --git a/algorithms/data-structures/CircularlyLinkedList/CircularlySinglyLinkedList.cpp b/algorithms/data-structures/CircularlyLinkedList/CircularlySinglyLinkedList.cpp new file mode 100644 index 00000000..1a650c2d --- /dev/null +++ b/algorithms/data-structures/CircularlyLinkedList/CircularlySinglyLinkedList.cpp @@ -0,0 +1,286 @@ + +#include"CircularlySinglyLinkedList.h" + + + +template +void CircularlySinglyLinkedList :: Add_to_empty_list(T val) +{ + Node* new_node = new Node(val); + + Tail = new_node; + Tail->next = new_node; + +Size_++; +} + + +template +void CircularlySinglyLinkedList ::Push_back( T val) +{ + if(Tail == NULL) + { + Add_to_empty_list(val); + + } + else + { + Node* new_node = new Node(val); + new_node->next = Tail->next; + Tail->next = new_node; + Tail= new_node; + Size_++; + } +} + +template +void CircularlySinglyLinkedList :: Clear() +{ + + if(Size_ == 0 ) + { + cout<<" all cleared linked list is empty"<<'\n'; + } + else + { + Node* tmp1 = Tail->next; + Node* tmp2 = tmp1; + + while(tmp1 != Tail) + { + tmp1 = tmp1->next; + //free the memory of the node to delete it + delete tmp2; + tmp2=tmp1; + } + // after the loop we make Tail point to NULL because it points + //to a deleted location in the memory (dangling pointer) + delete Tail; + tmp1 = NULL; + tmp2 = NULL; + Tail = NULL; + Size_ = 0; + } + +} +template + +void CircularlySinglyLinkedList :: Display() +{ + if(Size_ == 0) + { + cout<<"List is empty"<<'\n'; + return; + } + Node* tmp = Tail->next; //Head + + do + { + cout<data<<" "; + tmp = tmp->next; + + + } + while(tmp != Tail->next); + + + + cout<<'\n'; +} +template +void CircularlySinglyLinkedList :: Pop_back() +{ + if( Size_ == 0) + { + cout<<"Can't pop back. list is empty"<<'\n'; + return; + + } + + if(Size_ == 1) + { + delete Tail; + Tail = NULL; + + + } + else + { + Node* tmp = Tail->next; + + + while(tmp->next != Tail) + { + tmp = tmp->next; + } + + tmp->next = Tail->next; + delete Tail; + Tail = tmp; + } + +Size_--; +} + + +template +void CircularlySinglyLinkedList :: Push_front(T val) +{ + if(Tail == NULL) + { + Add_to_empty_list(val); + + } + else + { + Node* new_node = new Node(val); + new_node->next = Tail->next; + Tail->next = new_node; + Size_++; + } + +} + +template +void CircularlySinglyLinkedList :: Pop_front() +{ + + if(Size_ == 0) + { + cout<<"Can't pop front. List is empty "<<'\n'; + return; + } + + + if( Size_ == 1) + { + delete Tail; + Tail = NULL; + + + } + else + { + + Node* tmp = Tail->next; + Tail->next = Tail->next->next; + delete tmp; + + } + +Size_--; + +} + +template +void CircularlySinglyLinkedList :: Insert_at(T val, int position,string afterOrbefore_flag) +{ + + + if(Size_ == 0) + { + cout<<"no existing nodes.Linked list is empty. "; + return; + } + + if(position >Size_ || position < 0) + { + cout<<"invalid position choose a position between 1 and size "<<'\n'; + cout<<"size is: "<* tmp; + if(afterOrbefore_flag == "before") + { + + if(position == 1) + { + Push_front(val); + return; + + } + else + { + tmp=Tail->next; + for(int i = 1 ; i next); + + } + + + } + else if(afterOrbefore_flag == "after") + { + + if(position == Size_) + { + Push_back(val); + return; + + } + else + { + tmp=Tail->next; + for( int i = 1 ; i next); + + } + + } + + Node* new_node = new Node(val); + new_node->next = tmp->next; + tmp->next = new_node; + Size_++; + +} +template + +void CircularlySinglyLinkedList :: Delete_at(int position) +{ + if(Size_ == 0) + { + cout<<"no existing nodes.Linked list is empty. "; + return; + } + + if(position >Size_ || position < 0) + { + cout<<"invalid position choose a position between 1 and size "<<'\n'; + cout<<"size is: "<* tmp = Tail->next; + + for(int i = 1 ; i < position-1; i++,tmp = tmp->next); + + Node* node = tmp->next; + + tmp->next = node->next; + + delete node; + + + Size_--; + + } + + +} diff --git a/algorithms/data-structures/CircularlyLinkedList/CircularlySinglyLinkedList.h b/algorithms/data-structures/CircularlyLinkedList/CircularlySinglyLinkedList.h new file mode 100644 index 00000000..fcc4fdbe --- /dev/null +++ b/algorithms/data-structures/CircularlyLinkedList/CircularlySinglyLinkedList.h @@ -0,0 +1,62 @@ +#include + +using namespace std; + + +template +class Node +{ + public: + T data; + + Node* next; + + + Node() + { + next = NULL; + } + + Node(T val) + { + data = val; + next = NULL; + } + + + + +}; + +template +class CircularlySinglyLinkedList +{ + public: + + Node* Tail; + int Size_; + + CircularlySinglyLinkedList() + { + Size_ = 0; + Tail = NULL; + + } + void Push_front(T val); + void Pop_front(); + void Push_back(T val); + void Pop_back(); + void Display(); + void Clear(); + void Insert_at(T val,int position,string afterOrbefore_flag); // has generalized code for add before node and add after node + void Delete_at(int position); + + void Add_to_empty_list(T val); + + ~CircularlySinglyLinkedList() + { + Clear(); + } + + +}; diff --git a/algorithms/data-structures/Deque/deque.c b/algorithms/data-structures/Deque/deque.c new file mode 100644 index 00000000..047cbf9d --- /dev/null +++ b/algorithms/data-structures/Deque/deque.c @@ -0,0 +1,202 @@ +#include +#include +#define MAX 30 + +typedef struct dequeue +{ + int data[MAX]; + int rear,front; +}dequeue; + +void initialize(dequeue *p); +int empty(dequeue *p); +int full(dequeue *p); +void enqueueR(dequeue *p,int x); +void enqueueF(dequeue *p,int x); +int dequeueF(dequeue *p); +int dequeueR(dequeue *p); +void print(dequeue *p); + +void main() +{ + int i,x,op,n; + dequeue q; + + initialize(&q); + + do + { + printf("\n1.Create\n2.Insert(rear)\n3.Insert(front)\n4.Delete(rear)\n5.Delete(front)"); + printf("\n6.Print\n7.Exit\n\nEnter your choice:"); + scanf("%d",&op); + + switch(op) + { + case 1: printf("\nEnter number of elements:"); + scanf("%d",&n); + initialize(&q); + printf("\nEnter the data:"); + + for(i=0;irear=-1; + P->front=-1; +} + +int empty(dequeue *P) +{ + if(P->rear==-1) + return(1); + + return(0); +} + +int full(dequeue *P) +{ + if((P->rear+1)%MAX==P->front) + return(1); + + return(0); +} + +void enqueueR(dequeue *P,int x) +{ + if(empty(P)) + { + P->rear=0; + P->front=0; + P->data[0]=x; + } + else + { + P->rear=(P->rear+1)%MAX; + P->data[P->rear]=x; + } +} + +void enqueueF(dequeue *P,int x) +{ + if(empty(P)) + { + P->rear=0; + P->front=0; + P->data[0]=x; + } + else + { + P->front=(P->front-1+MAX)%MAX; + P->data[P->front]=x; + } +} + +int dequeueF(dequeue *P) +{ + int x; + + x=P->data[P->front]; + + if(P->rear==P->front) //delete the last element + initialize(P); + else + P->front=(P->front+1)%MAX; + + return(x); +} + +int dequeueR(dequeue *P) +{ + int x; + + x=P->data[P->rear]; + + if(P->rear==P->front) + initialize(P); + else + P->rear=(P->rear-1+MAX)%MAX; + + return(x); +} + +void print(dequeue *P) +{ + if(empty(P)) + { + printf("\nQueue is empty!!"); + exit(0); + } + + int i; + i=P->front; + + while(i!=P->rear) + { + printf("\n%d",P->data[i]); + i=(i+1)%MAX; + } + + printf("\n%d\n",P->data[P->rear]); +} diff --git a/algorithms/data-structures/DoublyLinkedList/doubly_linked_list.cpp b/algorithms/data-structures/DoublyLinkedList/doubly_linked_list.cpp new file mode 100644 index 00000000..2808971c --- /dev/null +++ b/algorithms/data-structures/DoublyLinkedList/doubly_linked_list.cpp @@ -0,0 +1,271 @@ +#include"doubly_linked_list.h" + +using namespace std; + +template +void DoublyLinkedList :: Push_back(T val) +{ + + auto* new_node = new Node(move(val)); + + if(Tail != nullptr) //or if(Size != 0) + { + Tail->next = new_node; + new_node->prev = Tail; + Tail = new_node; + + } + else + { + Tail = new_node; + Head = new_node; + } + + Size_++; +} + + +template +void DoublyLinkedList :: Pop_back() +{ + //if list is empty + if(Tail == nullptr) //or Head == NULL + { + throw runtime_error("Can't pop back the DLS is empty"); + } + + if(Tail == Head) // if there's only one element in the DLS + { + delete Tail; + Tail = nullptr; + Head = nullptr; + + } + else + { + Node* previous_node = Tail->prev; + + delete Tail; + + Tail = previous_node; + Tail->next = nullptr; + } + + Size_--; + +} + +template +void DoublyLinkedList :: Push_front(T val) +{ + + auto* new_node = new Node(move(val)); + + new_node->next = Head; + if(Head != nullptr) + { + Head->prev = new_node; + + } + Head = new_node; + if(Tail == nullptr) + { + Tail = Head; + } + + Size_++; + +} + +template +void DoublyLinkedList :: Pop_front() +{ + if(Head == nullptr) //if dls is empty can't pop + { + throw runtime_error("Can't pop front the DLS is empty"); + } + + Node* next_node = Head->next; + delete Head; + Head = next_node; + + if(Head == nullptr) //if we popped the last element + { + Tail = nullptr; + } + else + { + Head->prev = nullptr; + } + + Size_--; + +} + +template +void DoublyLinkedList :: Add_before(Node* node, T val) +{ + + auto* new_node = new Node(move(val)); + new_node->next = node; + new_node->prev = node->prev; + node->prev = new_node; + + if(new_node->prev != nullptr) + { + new_node->prev->next = new_node; + } + + if(Head == node) + { + Head = new_node; + + } + Size_++; +} + + + +template +void DoublyLinkedList :: Add_after(Node* node,T val) +{ + + auto* new_node = new Node(move(val)); + new_node->prev = node; + new_node->next = node->next; + node->next = new_node; + + + if(new_node->next != nullptr) + { + new_node->next->prev = new_node; + + } + + if(Tail == node) + { + Tail = new_node; + } + + Size_++; + +} + +template +void DoublyLinkedList :: Display() const +{ + + if(Size_ == 0) + { + cout<<"Linked List is empty"; + } + else + { + for(Node* tmp_ptr = Head;tmp_ptr!= nullptr; tmp_ptr= tmp_ptr->next) + { + cout<data<<" "; + + } + } + cout<<'\n'; +} + + + +template +void DoublyLinkedList :: Clear() +{ + + Node* tmp = Head; + if(Size_ == 0 ) + { + throw runtime_error(" all cleared linked list is empty"); + } + + while(Head != nullptr) + { + + Head = Head->next; + delete tmp; + tmp = Head; + + } + cout<<" all cleared linked list is empty"<<'\n'; + Tail = nullptr; + Size_ = 0; +} +template +void DoublyLinkedList :: Insert_at(T val ,int position) +{ + if(position >Size_ || position <= 0) + { + cout<<"invalid position choose a position between 1 and size "<<'\n'; + cout<<"size is: "<* tmp = Head; + //get a pointer of that position that position + for(int i =1 ; i<=position-1 ; i++,tmp = tmp->next); + Add_before(tmp,val); + } + + +} + +template +void DoublyLinkedList :: Delete_at(int position) +{ + + + if(Size_ ==0) + { + cout<<"Can't delete DLS is empty "<<'\n'; + return; + } + + if(position >Size_ || position < 0) + { + cout<<"invalid position choose a position between 1 and size "<<'\n'; + cout<<"size is: "<* tmp = Head; + + for(int i = 1; i <= position-1; i++,tmp = tmp->next); + + if(tmp->next != nullptr) + { + tmp->next->prev = tmp->prev; + } + + if(tmp->prev != nullptr) + { + tmp->prev->next = tmp->next; + + } + + if(Head == tmp) + { + Head = tmp->next; + + } + + if(Tail == tmp) + { + Tail = Tail->prev; + } + + delete tmp; + Size_--; + + +} + + + diff --git a/algorithms/data-structures/DoublyLinkedList/doubly_linked_list.h b/algorithms/data-structures/DoublyLinkedList/doubly_linked_list.h new file mode 100644 index 00000000..cf6976f6 --- /dev/null +++ b/algorithms/data-structures/DoublyLinkedList/doubly_linked_list.h @@ -0,0 +1,66 @@ +#pragma once +#include + +template +class Node{ + + + //each node has a next pointer and a previous pinter +public: + T data; + Node* next; + Node* prev; + + + Node() + { + next = nullptr; + prev = nullptr; + + } + + explicit Node(T&& value) : + data(std::move(value)), + next(nullptr), + prev(nullptr) + { + } + +}; + + +template +class DoublyLinkedList{ + +private: + Node* Head; + Node* Tail; + int Size_; + +public: + + DoublyLinkedList(): + Head(nullptr), + Tail(nullptr), + Size_(0) + { + } + + void Push_back(T val); //append + void Pop_back(); + void Push_front(T val); //prepend + void Pop_front(); + void Display() const; + void Clear(); + void Insert_at(T val, int position); + void Delete_at(int position); + void Add_before(Node* node, T val); + void Add_after(Node* node,T val); + + ~DoublyLinkedList() + { + std::cout<<"destructor is called"<<'\n'; + Clear(); + } + +}; diff --git a/algorithms/data-structures/Doubly_Linked_List.cpp b/algorithms/data-structures/Doubly_Linked_List.cpp new file mode 100644 index 00000000..782c1b2c --- /dev/null +++ b/algorithms/data-structures/Doubly_Linked_List.cpp @@ -0,0 +1,93 @@ +#include +#include + +using namespace std; +int main() +{ +struct node{ + int info; + node *left,*right; +}*ptr,*start,*last,*save; + +int c=1,i=0,data,item; +start=last=NULL; + +while(c<4 && c>0){ + cout<<"1.Insert\n2.Deletion\n3.Link List\n"; + cin>>c; + + switch(c){ + case 1: + cout<<"Enter Data\n"; + cin>>data; + + ptr=new node; + ptr->info=data; + ptr->left=last; + ptr->right=NULL; + + if(start==NULL){ + start=last=ptr; + } + + else{ + last->right=ptr; + last=ptr; + } + break; + + case 2: + if(start==NULL){ + cout<<"Underflow\n"; + } + + else{ + cout<<"Enter Item to be Deleted\n"; + cin>>item; + ptr=start; + + while(ptr!=NULL){ + if(ptr->info==item){ + i++; + if(ptr==start){ + start->left=NULL; + start=start->right; + } + + else{ + ptr->left->right=ptr->right; + ptr->right->left=ptr->left; + } + delete ptr; + cout<<"Item Deleted\n"; + } + ptr=ptr->right; + } + + if(i==0){ + cout<<"Item Does not exist\n"; + } + i=0; + } + break; + + case 3: + + ptr=start; + + while(ptr!=NULL){ + cout<info<<"->"; + ptr=ptr->right; + } + cout<<"\n"; + break; + + default: + cout<<"Wrong Choice\nExiting...\n"; + } + +} + +getch(); +return 0; +} \ No newline at end of file diff --git a/algorithms/data-structures/Find the Unique Element b/algorithms/data-structures/Find the Unique Element new file mode 100644 index 00000000..ce2a7bd8 --- /dev/null +++ b/algorithms/data-structures/Find the Unique Element @@ -0,0 +1,32 @@ +/* +Given an integer array of size 2N + 1. In this given array, +N numbers are present twice and one number is present only once in the array. +You need to find and return that number which is unique in the array. +*/ + +#include +#include +#include "solution.h" +using namespace std; + +int FindUnique(int arr[], int size){ + int xor1 = 0; + for(int i = 0; i < size; i++) + xor1 ^= arr[i]; + return xor1; +} + +int main() { + + int size; + + cin>>size; + int *input=new int[1+size]; + + for(int i=0;i>input[i]; + + cout< +using namespace std; +const int SIZE = 26; + +struct MyNode{ + struct MyNode *children[SIZE]; + bool isEndOfWord; +}; + +// Returns new trie node +struct MyNode *getNode(void) +{ + struct MyNode *pNode = new MyNode; + + pNode->isEndOfWord = false; + + for (int i = 0; i < SIZE; i++) + pNode->children[i] = NULL; + + return pNode; +} + +/* If not present, inserts key into trie + If the key is prefix of trie node, just + marks leaf node*/ +void insert(struct MyNode *root, string key) +{ + struct MyNode *pCrawl = root; + + for (int i = 0; i < key.length(); i++) + { + int index = key[i] - 'a'; + if (!pCrawl->children[index]) + pCrawl->children[index] = getNode(); + + pCrawl = pCrawl->children[index]; + } + + // mark last node as leaf + pCrawl->isEndOfWord = true; +} + +// Returns true if key presents in trie, else false +bool search(struct MyNode *root, string key) +{ + struct MyNode *pCrawl = root; + + for (int i = 0; i < key.length(); i++) + { + int index = key[i] - 'a'; + if (!pCrawl->children[index]) + return false; + + pCrawl = pCrawl->children[index]; + } + + return (pCrawl != NULL && pCrawl->isEndOfWord); +} + +// Driver Programme to check above functions +int main() +{ + // For input keys use only lower case + string keys[] = {"the", "a", "there", + "answer", "any", "by", + "bye", "their" }; + int n = sizeof(keys)/sizeof(keys[0]); + + struct MyNode *root = getNode(); + + // Build trie + for (int i = 0; i < n; i++) + insert(root, keys[i]); + + // Search for different keys to check is it present in our dictonary or not..?? + search(root, "the")? cout << "Yes\n" : cout << "No\n"; + search(root, "these")? cout << "Yes\n" : cout << "No\n"; + return 0; +} diff --git a/algorithms/data-structures/avl-tree/AVL.cpp b/algorithms/data-structures/avl-tree/AVL.cpp new file mode 100644 index 00000000..556e74d3 --- /dev/null +++ b/algorithms/data-structures/avl-tree/AVL.cpp @@ -0,0 +1,125 @@ +#include "AVL.h" +using namespace std; + +//Calcule altura de um n +int height_node(struct _Node_* node){ + if(node == NULL) + return -1; + else + return node->height; +} +//Calcule o fator de balanceamento de um n +int fatorBalanceamento_node(struct _Node_* node){ + int valor = (height_node(node->right))-(height_node(node->left)); + return valor; +} +//Calcula o maior valor +int maior(int x, int y){ + if(x > y) + return x; + else + return y; +} +//Rotao a esquerda +AVLnode* RotationLL(AVLnode* root){ + AVLnode*node; + node = root->left; + root->left = node->right; + root->height = maior(height_node(root->left),height_node(root->right)) + 1; + node->height = maior(height_node(node->left),height_node(root)) + 1; + root = node; + return root; +} +//Rotao a direita +AVLnode* RotationRR(AVLnode* root){ + AVLnode* node; + node = root->right; + root->right = node->left; + root->height = maior(height_node(root->left),height_node(root->right)) + 1; + node->height = maior(height_node(node->right),height_node(root)) + 1; + root = node; + return root; +} +//Rotao dupla a esquerda +AVLnode* RotationLR(AVLnode* root){ + root->left = RotationRR(root->left); + root = RotationLL(root); + return root; +} +//Rotao dupla a direita +AVLnode* RotationRL(AVLnode* root){ + root->right = RotationLL(root->right); + root = RotationRR(root); + return root; +} +//Insert AVLtree +AVLnode* insert_AVLnode(AVLnode* root,Data* data){ + //rvore vazia ou n folha + if(root == NULL){ + AVLnode* novo; + novo = new AVLnode[1]; + if(novo == NULL) + return NULL; + novo->data = data; + novo->height = 0; + novo->left = NULL; + novo->right = NULL; + return novo; + } + + AVLnode* current = root; + + /*Balaneamento*/ + if(data->key < current->data->key){ + current->left = insert_AVLnode(current->left, data); + if(current->left != NULL){ + if(fatorBalanceamento_node(current) <= -2){ + if(data->key < current->left->data->key) + root = RotationLL(root); + else + root = RotationLR(root); + } + } + return root; + }else{ + if(data->key > current->data->key){ + current->right = insert_AVLnode(current->right, data); + if(current->right != NULL){ + if(fatorBalanceamento_node(current) >= 2){ + if(data->key > current->right->data->key) + root = RotationRR(root); + else + root = RotationRL(root); + } + } + } + return root; + } + return NULL; +} +//Query +void Query(AVLnode* root,Data** aux,string str,int* passos){ + int value = valorString(str); + if(root != NULL){ + if(root->data->key == value){ + *aux = root->data; + }else if(value > root->data->key){ + Query(root->right, &*aux, str, &*passos); + }else{ + Query(root->left, &*aux, str, &*passos); + } + } + *passos = *passos + 1; +} + +//Destruir +void Destroy(AVLnode *t){ + if(t != NULL){ + Destroy(t->left); + Destroy(t->right); + t->data->linhas.clear(); + t->data->ocorrencias.clear(); + delete[]t->data; + delete[]t; + } +} diff --git a/algorithms/data-structures/avl-tree/AVL.h b/algorithms/data-structures/avl-tree/AVL.h new file mode 100644 index 00000000..2e22c600 --- /dev/null +++ b/algorithms/data-structures/avl-tree/AVL.h @@ -0,0 +1,17 @@ +#ifndef _AVL_H_ +#define _AVL_H_ +#include "structs.h" + +typedef struct _Node_{ + struct _data_ *data; + int height; + struct _Node_ *left; + struct _Node_ *right; +} AVLnode; + +AVLnode* insert_AVLnode(AVLnode* root,Data* data); +void Query(AVLnode* root,Data** aux,string str, int* passos); +void Destroy(AVLnode *t); + +#endif + diff --git a/algorithms/data-structures/binary_search_tree.cpp b/algorithms/data-structures/binary_search_tree.cpp new file mode 100644 index 00000000..9609c66a --- /dev/null +++ b/algorithms/data-structures/binary_search_tree.cpp @@ -0,0 +1,142 @@ +#include +#include +#include +using namespace std; +struct tree +{ + int value; + tree *left; + tree *right; +}*root=NULL; +void inserte() +{ + int v,insert_left=0,insert_right=0; + cout<<"Enter Value To Insert: "; + cin>>v; + tree *newnode=(tree*)malloc(sizeof(tree)); + newnode->value=v; + newnode->left=NULL; + newnode->right=NULL; + if(root==NULL) + root=newnode; + else + { + tree *temp=root; + while(1) + { + if(insert_left==1||insert_right==1) + break; + if(vvalue) + { + if(temp->left!=NULL) + temp=temp->left; + else + insert_left=1; + } + else + if(v>temp->value) + { + if(temp->right!=NULL) + temp=temp->right; + else + insert_right=1; + } + } + if(insert_left==1) + temp->left=newnode; + else + if(insert_right==1) + temp->right=newnode; + } +} +void preorder() +{ + tree *temp=root; + stack s; + repeat: + while(1) + { + if(temp->right!=NULL) + s.push(temp->right); + if(temp->left!=NULL) + { + cout<value<<" "; + temp=temp->left; + } + else + if(temp->left==NULL) + { + cout<value<<" "; + break; + } + } + while(!s.empty()) + { + temp=s.top(); + s.pop(); + goto repeat; + } +} +void inorder() +{ + tree *temp=root; + stack s; + repeat: + while(1) + { + s.push(temp); + if(temp->left!=NULL) + temp=temp->left; + else + break; + } + while(1) + { + repeat1: + temp=s.top(); + cout<value<<" "; + s.pop(); + if(temp->right==NULL) + goto repeat1; + else + if(temp->right!=NULL) + { + temp=temp->right; + goto repeat; + } + else + if(s.empty()) + break; + } +} + +int main() +{ + int ch; + while(1) + { + cout<>ch; + if(ch==1) + inserte(); + else + if(ch==2) + { + preorder(); + cout< +#include +using namespace std; + +int lengthOfLongestSubsetWithZeroSum(int* arr, int size){ + unordered_map mymap; + int sum = 0; + int maxLength = -1; + for(int i = 0; i < size; i++){ + sum += arr[i]; + int length = 0; + + if(sum == 0){ + length = i+1; + }else if(mymap.count(sum)){ + length = i - mymap[sum]; + + }else{ + mymap[sum] = i; + } + + if(length > maxLength){ + maxLength = length; + } + } + return maxLength; +} + +int main(){ + int size; + + cin >> size; + int* arr = new int[size]; + for(int i = 0; i < size; i++){ + cin >> arr[i]; + } + int ans = lengthOfLongestSubsetWithZeroSum(arr,size); + cout << ans << endl; + delete arr; +} diff --git a/algorithms/data-structures/largest_rectangle_area.cpp b/algorithms/data-structures/largest_rectangle_area.cpp new file mode 100644 index 00000000..294b0c4b --- /dev/null +++ b/algorithms/data-structures/largest_rectangle_area.cpp @@ -0,0 +1,61 @@ +/** + * + *@gaurav yadav + + Maintain a stack + a. If stack is empty heights[stack.top()] <= heights[i]) + push this i into stack. + b. Else keep popooing from stack till value at i at top of stack is + less than value at current index. + c. While popping calculate area + if stack is empty + area = i * heights[top]; + it means that till this point value just removed has to be smallest element + if stack is not empty + area = heights[top] * (i - stack.top() - 1); + + * Finally return maxArea + * Time complexity is O(n) + * Space complexity is O(n) + */ +class Solution { +public: + + int largestRectangleArea(vector& heights) { + int area = 0; + int maxArea = 0; + stack s; + int i; + for (i = 0; i < heights.size();) { + if (s.empty() || heights[s.top()] <= heights[i]) { + s.push(i++); + } + else { + int top = s.top(); + s.pop(); + if (s.empty()) { + area = i * heights[top]; + } + else { + area = heights[top] * (i- s.top() -1); + } + if (area > maxArea) + maxArea = area; + } + } + + while (!s.empty()) { + int top = s.top(); + s.pop(); + if (s.empty()) { + area = i * heights[top]; + } + else { + area = heights[top] * (i- s.top() -1); + } + if (area > maxArea) + maxArea = area; + } + return maxArea; + } +}; diff --git a/algorithms/data-structures/linkedlist/linkedLists.cpp b/algorithms/data-structures/linkedlist/linkedLists.cpp new file mode 100644 index 00000000..518031bd --- /dev/null +++ b/algorithms/data-structures/linkedlist/linkedLists.cpp @@ -0,0 +1,151 @@ +#include + +using namespace std; + + + +struct btNode +{ + int data; + btNode* left; + btNode* right; +}; + + + + + + +void bst_insert(btNode*& bst_root, int anInt) +{ + if(bst_root == 0) // if list is empty + { + btNode* newNode = new btNode; + + newNode->data = anInt; + newNode->left = 0; + newNode->right= 0; + + bst_root = newNode; + return; // end function call + } + + btNode* marker = new btNode; // traverse pointer + marker = bst_root; + + while( marker != 0) // not at a leaf + { + if(marker->data == anInt) // if duplicate is found + { + marker->data = anInt; // overwrite and leave function + return; + } + + + + if(marker->data > anInt) // if # is less than + { + if(marker->left != 0) + { + marker = marker->left; // if not empty move left + } + + else // if empty, populate + { + btNode* newNode = new btNode; // create + + newNode->data = anInt; // populate + newNode->left = 0; + newNode->right = 0; + + marker->left = newNode; // attach + return; + + } + } + + if(marker->data < anInt) // if # is greater + { + if(marker->right != 0) + marker = marker->right; + + else + { + btNode* newNode = new btNode; + + newNode->data = anInt; + newNode->left = 0; + newNode->right = 0; + + marker->right = newNode; + return; + } + + } + + } +} + + + bool bst_remove(btNode*& bst_root, int anInt) + { + + if(bst_root == 0) // if empty tree return false + return false; + + + if(bst_root->data > anInt) // if # is less than + return bst_remove(bst_root->left,anInt); // shift and recurse + + if(bst_root->data < anInt) // if # is greater than + return bst_remove(bst_root->right,anInt); + + + if(bst_root->data == anInt) // if # is found + { + if(bst_root->left == 0) // if no left node + { + btNode* temp = bst_root; //mini remove max + + bst_root = bst_root->right; + + delete temp; + return true; + } + + // if left node is occupied + bst_remove_max(bst_root->left, bst_root->data); + return true; + } + + return false; // if nothing is found + + } + + void bst_remove_max(btNode*& bst_root, int& info) + { + + if(bst_root->right != 0) // if right node is still occupied + return bst_remove_max(bst_root->right, info); + + + btNode* tempNode = new btNode; // prepare node to be deleted + tempNode = 0; // make NULL + + btNode* marker = new btNode; // make a node to traverse tree + marker = bst_root; + + + if(bst_root->right == 0) // if at rightmost node + { + info = bst_root->data; // get information stored in node + + tempNode = marker; + + bst_root = bst_root->left; + + delete tempNode; + } + + } + diff --git a/algorithms/data-structures/queue/circular_buffer.cpp b/algorithms/data-structures/queue/circular_buffer.cpp new file mode 100644 index 00000000..dc4e8c54 --- /dev/null +++ b/algorithms/data-structures/queue/circular_buffer.cpp @@ -0,0 +1,65 @@ +// +// Queue: the entities in the collection are kept in +// order and the principal (or only) operations on the +// collection are the addition of entities to the rear +// terminal position +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/data-scructures/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Carlos Abraham +// Github: @abranhe +// +#include +#include + +template +class circular_buffer +{ +private: + T* m_buffer; + long m_index; + +public: + circular_buffer() + : m_buffer {new T[SZ]()} + , m_index {0} + { + } + + ~circular_buffer() + { + delete m_buffer; + } + + std::vector get_ordered() noexcept + { + std::vector vec; + for (long i = 0; i < SZ; ++i) + vec.push_back(m_buffer[(i + m_index) % SZ]); + return vec; + } + + void push(T x) noexcept + { + m_buffer[m_index] = x; + m_index = (m_index + 1) % SZ; + } +}; + +int main() +{ + circular_buffer buf; + + buf.push(1); + buf.push(2); + buf.push(3); + buf.push(4); + buf.push(5); + buf.push(6); + + for (auto x : buf.get_ordered()) + std::cout << x << std::endl; +} diff --git a/algorithms/data-structures/queue/queue.cpp b/algorithms/data-structures/queue/queue.cpp new file mode 100644 index 00000000..5a07ef27 --- /dev/null +++ b/algorithms/data-structures/queue/queue.cpp @@ -0,0 +1,86 @@ +// +// Queue: the entities in the collection are kept in +// order and the principal (or only) operations on the +// collection are the addition of entities to the rear +// terminal position +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/data-scructures/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: ANUJ MODI +// Github: @descifrado +// +#include +#define qsize 5 +struct queue +{ + int arr[qsize]; + int f, r; +}; +typedef struct queue Queue; +void +enqueue (Queue * q, int x) +{ + if (q->r == qsize - 1) + printf ("QUEUE OVERFLOW\n"); + else + q->arr[++q->r] = x; +} + +int +dequeue (Queue * q) +{ + if (q->f - q->r == 1) + printf ("Queue Underflow"); + else + return (q->arr[q->f++]); +} + +int +main () +{ + Queue q; + q.f = 0; + q.r = -1; + while (1) + { + printf("Enter 1 to Enqueue\nEnter 2 to Dequeue\nEnter 3 to Display All Elements\nEnter 0 to Exit\n"); + int c; + scanf ("%d", &c); + switch (c) + { + case 0: + printf("Ended\n"); + return 0; + case 1: + printf ("Enter Element to Enqueue\n"); + int x; + scanf ("%d", &x); + enqueue (&q, x); + break; + case 2: + if (q.f - q.r == 1) + printf ("Queue Undeflow\n"); + else + printf ("Dequeued Element is %d\n", dequeue (&q)); + break; + case 3: + printf ("Elements of Queue Are\n"); + if (q.f - q.r == 1) + { + printf ("Queue is Empty\n"); + break; + } + int i; + for (i = q.f; i <= q.r; i++) + printf ("%d ", q.arr[i]); + printf ("\n"); + break; + default: + printf ("Wrong Choice\n"); + } + } + return 0; +} diff --git a/algorithms/data-structures/red-black-tree/RedBlack.cpp b/algorithms/data-structures/red-black-tree/RedBlack.cpp new file mode 100644 index 00000000..2710e388 --- /dev/null +++ b/algorithms/data-structures/red-black-tree/RedBlack.cpp @@ -0,0 +1,143 @@ +#include "RedBlack.h" + +//Rotao a esquerda +void rightRotate(RBnode** root, RBnode* x){ + RBnode* y = x->left; + x->left = y->right; + if(y->right != NULL) + y->right->dad = x; + y->dad = x->dad; + if (x->dad == NULL){ + *root = y; + }else{ + if(x == x->dad->right) + x->dad->right = y; + else + x->dad->left = y; + } + y->right = x; + x->dad = y; +} +//Rotao a direita +void leftRotate(RBnode** root,RBnode* x){ + RBnode* y = x->right; + x->right = y->left; + if(y->left != NULL) + y->left->dad = x; + y->dad = x->dad; + if(x->dad == NULL) + *root = y; + else{ + if(x == x->dad->left) + x->dad->left = y; + else + x->dad->right = y; + } + y->left = x; + x->dad = y; +} + +//color 1-red 0-black +void fix_insert(RBnode **root, RBnode *node){ + RBnode* z = node; + while((*root != z) && (z->dad->color==1)){ + if(z->dad == z->dad->dad->left){ + RBnode* y = z->dad->dad->right; + /*Caso 1: Um n x est sendo inserido, e seu tio + vermelho ento necessrio recolorir o pai, o tio + o av*/ + if((y!=NULL) && (y->color == 1)){ + z->dad->color = 0; + y->color = 0; + z->dad->dad->color = 1; + z = z->dad->dad; + }else{ + if(z == z->dad->right){ + /*Caso 2:irmo preto e pai vermelho*/ + z = z->dad; + leftRotate(&*root,z); + } + /*Caso 3:pai vermelho, irmo preto, av preto*/ + z->dad->color = 0; + z->dad->dad->color = 1; + rightRotate(&*root,z->dad->dad); + } + }else{ + RBnode* y = z->dad->dad->left; + if((y!=NULL) && (y->color == 1)){ + /*caso 4*/ + z->dad->color = 0; + y->color = 0; + z->dad->dad->color = 1; + z = z->dad->dad; + }else{ + /*Caso 5:*/ + if(z == z->dad->left){ + z = z->dad; + rightRotate(&*root,z); + } + /*Caso 6:pai vermelho, av preto, tio preto*/ + z->dad->color = 0;//pai fica preto + z->dad->dad->color = 1;//av fica vermelho + leftRotate(&*root, z->dad->dad);//gera uma rotao a esquerda + } + } + } +} + +void RB_Insert(RBnode** root, Data* data){ + RBnode* y = NULL; + RBnode* x = *root; + while(x != NULL){ + y = x; + if(data->key < x->data->key) + x = x->left; + else + x = x->right; + } + RBnode* newnode = new RBnode[1]; + if(newnode != NULL){ + newnode->data = data; + newnode->color = 1; + newnode->left = NULL; + newnode->right = NULL; + newnode->dad = y; + } + if(y == NULL){ + *root = newnode; + }else{ + if(data->key < y->data->key) + y->left = newnode; + else + y->right = newnode; + } + fix_insert(&*root, newnode); + (*root)->color = 0; +} + +//Query +void RBQuery(RBnode* root,Data** aux,string str,int* passos){ + int value = valorString(str); + if(root != NULL){ + if(root->data->key == value){ + *aux = root->data; + }else if(value > root->data->key){ + RBQuery(root->right, &*aux, str, &*passos); + }else{ + RBQuery(root->left, &*aux, str, &*passos); + } + } + *passos = *passos+1; +} + +//Destruir +void RBDestroy(RBnode *t){ + if(t != NULL){ + RBDestroy(t->left); + RBDestroy(t->right); + t->data->linhas.clear(); + t->data->ocorrencias.clear(); + delete[]t->data; + delete[]t; + } +} diff --git a/algorithms/data-structures/red-black-tree/RedBlack.h b/algorithms/data-structures/red-black-tree/RedBlack.h new file mode 100644 index 00000000..d2743f54 --- /dev/null +++ b/algorithms/data-structures/red-black-tree/RedBlack.h @@ -0,0 +1,14 @@ +#ifndef _REDBLACK_H_ +#define _REDBLACK_H_ +#include "structs.h" + + typedef struct _RBNode_{ + int color; + struct _data_ *data; + struct _RBNode_ *left, *right, *dad; + } RBnode; + + extern void RB_Insert(RBnode** root, Data* data); + extern void RBQuery(RBnode* root,Data** aux,string str,int* passos); + void RBDestroy(RBnode *t); +#endif diff --git a/algorithms/data-structures/segment_tree/a.out b/algorithms/data-structures/segment_tree/a.out new file mode 100755 index 00000000..2aa14deb Binary files /dev/null and b/algorithms/data-structures/segment_tree/a.out differ diff --git a/algorithms/data-structures/segment_tree/min_in_range.cpp b/algorithms/data-structures/segment_tree/min_in_range.cpp new file mode 100644 index 00000000..2a5fcb63 --- /dev/null +++ b/algorithms/data-structures/segment_tree/min_in_range.cpp @@ -0,0 +1,98 @@ +// +// SEGMENT TREE : A Segment Tree is a data structure that allows +// answering range queries over an array effectively, +// while still being flexible enough to allow modifying the array. +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/data-scructures/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: RITUPARNO BISWAS +// Github: @roopbiswas +// + + +#include +using namespace std; + + +int st[400005],a[100005],y,l,r,x; + +void build(int in,int s,int e) +{ + if(s==e) + { + st[in]=a[s]; + return; + } + int m=(s+e)/2; + build(2*in,s,m); + build(2*in+1,m+1,e); + st[in]= min(st[2*in],st[2*in+1]); +} + +void update(int in,int s,int e) +{ + if(s==e) + { + st[in]=y; + return; + } + int m=(s+e)/2; + if(s<=x && x<=m) + update(2*in,s,m); + else + update(2*in+1,m+1,e); + st[in]=min(st[2*in],st[2*in+1]); +} + +int query(int in,int s,int e) +{ + if(r>n; + for(i=0;i>a[i]; + cin>>t; + char ch; + build(1,0,n-1); + while(t--) + { + cout<<"Enter choice : \nu : for update\nq : for query\n"; + cin>>ch; + + if(ch=='u') + { + cout<<"Enter values of index(1 based) and updated value\n"; + cin>>x>>y; + x--; + update(1,0,n-1); + } + else + { + cout<<"Enter values(1 based) of upper and lower index\n"; + cin>>l>>r; + l--; + r--; + cout<<"\nMINIMUM : "< +using namespace std; + + +int st[400005],a[100005],y,l,r,x; + +void build(int in,int s,int e) +{ + if(s==e) + { + st[in]=a[s]; + return; + } + int m=(s+e)/2; + build(2*in,s,m); + build(2*in+1,m+1,e); + st[in]= st[2*in]+st[2*in+1]; +} + +void update(int in,int s,int e) +{ + if(s==e) + { + st[in]=y; + return; + } + int m=(s+e)/2; + if(s<=x && x<=m) + update(2*in,s,m); + else + update(2*in+1,m+1,e); + st[in]=st[2*in]+st[2*in+1]; +} + +int query(int in,int s,int e) +{ + if(r>n; + for(i=0;i>a[i]; + cin>>t; + char ch; + build(1,0,n-1); + while(t--) + { + cout<<"Enter choice : \nu : for update\nq : for query\n"; + cin>>ch; + + if(ch=='u') + { + cout<<"Enter values of index(1 based) and updated value\n"; + cin>>x>>y; + x--; + update(1,0,n-1); + } + else + { + cout<<"Enter values(1 based) of upper and lower index\n"; + cin>>l>>r; + l--; + r--; + cout<<"\nSUM : "< +#include + +using namespace std; + +//- Global Variable (came from main)! +struct Node *top = NULL; + +struct Node{ + int data; + struct Node *next; +}; + +void linkedlistTraversal(struct Node * ptr){ + while(ptr!=NULL){ + printf("Element: %d\n", ptr->data); + ptr = ptr->next; + } +} + +int isEmpty(struct Node* top){ + if(top == NULL){ + return 1; + } + return 0; +} + +int isFull(struct Node* top){ + struct Node * n = (struct Node *) malloc(sizeof(struct Node)); + if(n == NULL){ + return 1; + } + return 0; +} + +struct Node* push(struct Node* top, int data){ + if(isFull(top)){ + printf("Stack Overflow!\n"); + } + else{ + struct Node * n = (struct Node*) malloc(sizeof(struct Node)); + n->data = data; + n->next = top; + top = n; + return top; + } +} + +int pop(struct Node * tp){ + if(isEmpty(tp)){ + printf("Stack Underflow!"); + } + else{ + struct Node * n = tp; + top = (tp)->next; + int x = n->data; + free(n); + return x; + } +} + +int peek(int pos){ + struct Node * ptr = top; + for (int i = 0; (i < pos-1 && ptr!=NULL); i++) + { + ptr = ptr->next; + } + if(ptr!=NULL){ + return ptr->data; + } + else{ + return -1; // assuming there's no -ve element in stack + } +} + +int stackTop(struct Node * top){ + return top->data; +} + +int stackBottom(struct Node * top){ + struct Node * p = top; + while(p->next!=NULL){ + p = p->next; + } + return p->data; +} + +int main() +{ + top = push(top, 69); + top = push(top, 10); + top = push(top, 8); + top = push(top, 7); + linkedlistTraversal(top); + + for (int i = 1; i <= 4; i++) + { + printf("The element at position %d is %d\n",i,peek(i)); + } + + // printf("The top most element in stack is %d\n",stackTop(top)); + printf("The bottom most element in stack is %d\n",stackBottom(top)); + + + + return 0; +} diff --git a/algorithms/data-structures/stack/stack_using_two_queues.cpp b/algorithms/data-structures/stack/stack_using_two_queues.cpp new file mode 100644 index 00000000..30443571 --- /dev/null +++ b/algorithms/data-structures/stack/stack_using_two_queues.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; + +class QueueStack{ +private: + queue q1; + queue q2; +public: + void push(int); + int pop(); +}; + + +int main() +{ + int T; + cin>>T; + while(T--) + { + QueueStack *qs = new QueueStack(); + + int Q; + cin>>Q; + while(Q--){ + int QueryType=0; + cin>>QueryType; + if(QueryType==1) + { + int a; + cin>>a; + qs->push(a); + }else if(QueryType==2){ + cout<pop()<<" "; + + } + } + cout< q1; + queue q2; +public: + void push(int); + int pop(); +}; +void QueueStack :: push(int x) +{ + q2.push(x); + while(!q1.empty()){ + q2.push(q1.front()); + q1.pop(); + } + swap(q1,q2); +} +int QueueStack :: pop() +{ + if(q1.empty()) return -1; + else{ + int x = q1.front(); + q1.pop(); + return x; + } +} diff --git a/algorithms/data-structures/stack/stacks_using_array.cpp b/algorithms/data-structures/stack/stacks_using_array.cpp new file mode 100644 index 00000000..02d4db84 --- /dev/null +++ b/algorithms/data-structures/stack/stacks_using_array.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +int stack[100], n=100, top=-1; +void push(int val) //Used for pushing in to the stack +{ + if(top>=n-1) + cout<<"Stack Overflow"<=0) { + cout<<"Stack elements are:"; + for(int i=top; i>=0; i--) + cout<>ch; + switch(ch) { + case 1: { + cout<<"Enter value to be pushed:"<>val; + push(val); + break; + } + case 2: { + pop(); + break; + } + case 3: { + display(); + break; + } + case 4: { + cout<<"Exit"< +#include +struct tree //declaring a structure tree +{ + int data; + struct tree* left; + struct tree* right; +}*root=NULL; //creates a root pointer + +struct node //declaring a sructure node +{ + struct tree* link; //node refering to structure tree + struct node* next; +}*top=NULL; //creates a top pointer + + +void insert_bt(int d) //Insertion in Binary tree +{ + struct tree* temp; + temp=(struct tree*)malloc(sizeof(struct tree)); + temp->left=NULL; + temp->right=NULL; + temp->data=d; + if( root == NULL) + root = temp; + else + { + struct tree* parent,*curr; + curr=root; + while(curr) + { + parent=curr; + if(d < curr->data) + { + curr=curr->left; + } + else + { + curr=curr->right; + } + + } + if(d < parent->data) + { + parent->left=temp; + } + else + { + parent->right=temp; + } + + } + +} +//********************************************************* +void inorder(struct tree*t) // Inorder traversal using recurrsion +{ + if(t!=NULL) + { + inorder(t->left); + printf(" %d",t->data); + inorder(t->right); + } +} +//********************************************************* + + +void push(struct tree* c) //Pushing into the stack +{ + struct node* temp; + temp=(struct node*)malloc(sizeof(struct node)); + temp->link=c; + + temp->next=top; + top=temp; +} +//******************************************************** + +int pop() //poping out +{ + if(top == NULL) + return 0; + else + { + struct node* temp; + temp=top; + printf(" %d",temp->link->data); + top=top->next; + + temp->link=NULL; + temp->next=NULL; + free(temp); + temp=NULL; //assinging the top to the root + + + } +} +//********************************************************* +void display() //display function +{ + struct node* t; + t=top; + printf("\n"); + while(t!=NULL) + { + printf(" %d",t->link->data); + t=t->next; + } +} +//*************************************************** +int isempty() //function to check wheather the function is empty or not +{ + if( top == NULL) + return 1; + else return 0; +} +//****************************************************** + +void iterative(struct tree* t) // iterative method +{ + while(1) + { + if(t!=NULL) + { + push(t); + t=t->left; + } + else + { + if(isempty()) + break; + else + { + t=top->link; // before poping we need to initialize the root to + // to the top of the stack + pop(); + + t=t->right; + } + + } + + } +} + +//*******************************MAIN FUNCTION************************************** +int main() +{ + int n; + printf("\n Enter how many element you want to enter: "); + scanf("%d",&n); + int i,m; + printf("\n Enter the elements: "); + for( int i=0; i +#include +using namespace std; +int main() +{ + vector v; + int n; + cin>>n; //to enter the element + for(int i=0; i>m; + v.push_back(m); + } + for(int i: v) + { + cout<<" "< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; +} + +int find_parent(int val) +{ + while (parent[val] != val) { + parent[val] = parent[parent[val]]; + val = parent[val]; + } + return val; +} + +void union_set(int x, int y) +{ + x = find_parent(x); + y = find_parent(y); + if(x != y) + { + parent[y] = x; + } +} + +int main() +{ + int n = 5; + int elements[n]; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; +} + +int find_parent_path_compression(int val) +{ + if(val == parent[val]) + { + return val; + } + return parent[val] = find_parent_path_compression(parent[val]); +} + +void union_set(int x, int y) +{ + x = find_parent_path_compression(x); + y = find_parent_path_compression(y); + if(x != y) + { + parent[y] = x; + } +} + +int main() +{ + int n = 5; + int elements[n]; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; +int rank_v[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; + rank_v[val] = 0; +} +int find_parent_path_compression(int val) +{ + if(val == parent[val]) + { + return val; + } + return parent[val] = find_parent_path_compression(parent[val]); +} + +void union_set(int x, int y) +{ + x = find_parent_path_compression(x); + y = find_parent_path_compression(y); + if(x != y) + { + if(rank_v[x] +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; +int size_v[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; + size_v[val] = 1; +} +int find_parent_path_compression(int val) +{ + if(val == parent[val]) + { + return val; + } + return parent[val] = find_parent_path_compression(parent[val]); +} + +void union_set(int x, int y) +{ + x = find_parent_path_compression(x); + y = find_parent_path_compression(y); + if(x != y) + { + if(size_v[x] +#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/algorithms/dynamic-programming/Sine_Series.CPP b/algorithms/dynamic-programming/Sine_Series.CPP new file mode 100644 index 00000000..0123af85 --- /dev/null +++ b/algorithms/dynamic-programming/Sine_Series.CPP @@ -0,0 +1,29 @@ +#include //to add input and output stream +#include //to add console based functions + +void main() +{ + int i,j,n,fact,sign=-1; + float x, p,sum=0; + cout<<"\nEnter the value of x : "; + cin>>x; //values of sine series + cout<<"\nEnter the value of n : "; + cin>>n; //number of terms required in sine series + + for(i=1;i<=n;i+=2) + { + p=1; + fact=1; + for(j=1;j<=i;j++) + { + p=p*x; + fact=fact*j; + } + sign=-1*sign; + sum+=sign*p/fact; + } + cout<<"\nsin "< +using namespace std; + +/* A utility function to check whether a word is +present in dictionary or not. An array of strings +is used for dictionary. Using array of strings for +dictionary is definitely not a good idea. We have +used for simplicity of the program*/ +int dictionaryContains(string word) +{ + string dictionary[] = {"mobile","samsung","sam","sung", + "man","mango","icecream","and", + "go","i","like","ice","cream"}; + int size = sizeof(dictionary)/sizeof(dictionary[0]); + for (int i = 0; i < size; i++) + if (dictionary[i].compare(word) == 0) + return true; + return false; +} + +// returns true if string can be segmented into space +// separated words, otherwise returns false +bool wordBreak(string str) +{ + int size = str.size(); + + // Base case + if (size == 0) return true; + + // Try all prefixes of lengths from 1 to size + for (int i=1; i<=size; i++) + { + // The parameter for dictionaryContains is + // str.substr(0, i) which is prefix (of input + // string) of length 'i'. We first check whether + // current prefix is in dictionary. Then we + // recursively check for remaining string + // str.substr(i, size-i) which is suffix of + // length size-i + if (dictionaryContains( str.substr(0, i) ) && + wordBreak( str.substr(i, size-i) )) + return true; + } + + // If we have tried all prefixes and + // none of them worked + return false; +} + +// Driver program to test above functions +int main() +{ + wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n"; + wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n"; + wordBreak("")? cout <<"Yes\n": cout << "No\n"; + wordBreak("ilikelikeimangoiii")? cout <<"Yes\n": cout << "No\n"; + wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n"; + wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "No\n"; + return 0; +} diff --git a/algorithms/dynamic-programming/binomial_dp.cpp b/algorithms/dynamic-programming/binomial_dp.cpp new file mode 100644 index 00000000..e2792652 --- /dev/null +++ b/algorithms/dynamic-programming/binomial_dp.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; +int comb(int n, int k){ + int dp[n+1][k+1]; + for(int i=0;i<=n;i++){ + for(int j=0;j<=min(i,k);j++){ + if(j==0 || j==i){ + dp[i][j] = 1; + } + else{ + dp[i][j] = dp[i-1][j]+dp[i][j-1]; + } + } + } + return dp[n][k]; +} + +//Space Optimized Solution +int comb(int n, int k){ + int dp[k+1]; + dp[0]=1; + for(int i=1;i<=n;i++){ + for(int j=min(i,k);j>0;j--){ + dp[j] = dp[j]+dp[j-1]; + } + } + return dp[k]; +} +int main(){ + int n=4,k=2; + cout< + +using namespace std; + +int count( int S[], int m, int n ) +{ + int i, j, x, y; + + // We need n+1 rows as the table is constructed + // in bottom up manner using the base case 0 + // value case (n = 0) + int table[n+1][m]; + + // Fill the enteries for 0 value case (n = 0) + for (i=0; i= 0)? table[i - S[j]][j]: 0; + // Count of solutions excluding S[j] + y = (j >= 1)? table[i][j-1]: 0; + table[i][j] = x + y; + } + } + return table[n][m-1]; +} + +int main() +{ + int coins[] = {1, 2, 3}; + int m = sizeof(coins)/sizeof(int); + int n = 5; + cout << count(coins, m, n); + return 0; +} diff --git a/algorithms/dynamic-programming/digit_dp.cpp b/algorithms/dynamic-programming/digit_dp.cpp new file mode 100644 index 00000000..326b2b6a --- /dev/null +++ b/algorithms/dynamic-programming/digit_dp.cpp @@ -0,0 +1,64 @@ +#include "bits/stdc++.h" +using namespace std; + +long long dp[20][180][2]; + +long long getDigits(long long x, vector &digit) +{ + while (x) + { + digit.push_back(x%10); + x /= 10; + } +} + +long long digitSum(int idx, int sum, int tight, + vector &digit) +{ + if (idx == -1) + return sum; + + if (dp[idx][sum][tight] != -1 and tight != 1) + return dp[idx][sum][tight]; + + long long ret = 0; + + int k = (tight)? digit[idx] : 9; + + for (int i = 0; i <= k ; i++) + { + int newTight = (digit[idx] == i)? tight : 0; + + ret += digitSum(idx-1, sum+i, newTight, digit); + } + + if (!tight) + dp[idx][sum][tight] = ret; + + return ret; +} + +int rangeDigitSum(int a, int b) +{ + memset(dp, -1, sizeof(dp)); + + vector digitA; + getDigits(a-1, digitA); + + long long ans1 = digitSum(digitA.size()-1, 0, 1, digitA); + + vector digitB; + getDigits(b, digitB); + + long long ans2 = digitSum(digitB.size()-1, 0, 1, digitB); + + return (ans2 - ans1); +} + +int main() +{ + long long a = 123, b = 1024; + cout << "digit sum for given range : " + << rangeDigitSum(a, b) << endl; + return 0; +} diff --git a/algorithms/dynamic-programming/edit_distance.cpp b/algorithms/dynamic-programming/edit_distance.cpp new file mode 100644 index 00000000..cdc96d23 --- /dev/null +++ b/algorithms/dynamic-programming/edit_distance.cpp @@ -0,0 +1,70 @@ +// +// A Dynamic Programming based C++ program to find minimum +// number operations to convert str1 to str2 +// +// The All ▲lgorithms library for python +// +// https://allalgorithms.com/dynamic-programming/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Carlos Abraham +// Github: @abranhe +// + +#include +using namespace std; + +// Utility function to find the minimum of three numbers +int min(int x, int y, int z) +{ + return min(min(x, y), z); +} + +int editDistDP(string str1, string str2, int m, int n) +{ + // Create a table to store results of 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 first string is empty, only option is to + // isnert all characters of second string + if (i==0) + dp[i][j] = j; // Min. operations = j + + // If second string is empty, only option is to + // remove all characters of second string + else if (j==0) + dp[i][j] = i; // Min. operations = i + + // If last characters are same, ignore last char + // and recur for remaining string + else if (str1[i-1] == str2[j-1]) + dp[i][j] = dp[i-1][j-1]; + + // If the last character is different, consider all + // possibilities and find the minimum + 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]; +} + +// Driver program +int main() +{ + // your code goes here + string str1 = "sunday"; + string str2 = "saturday"; + + cout << editDistDP(str1, str2, str1.length(), str2.length()); + + return 0; +} diff --git a/algorithms/dynamic-programming/fibonacci_number.cpp b/algorithms/dynamic-programming/fibonacci_number.cpp new file mode 100644 index 00000000..d8d0f2fe --- /dev/null +++ b/algorithms/dynamic-programming/fibonacci_number.cpp @@ -0,0 +1,18 @@ +#include +int fibonacci_fast(int n) { + // write your code here + int fin[n]; + fin[0]=0; + fin[1]=1; + for (int i=2;i<=n;i++) + fin[i]=fin[i-1]+fin[i-2]; + + return fin[n]; +} +int main() { + int n = 0; + std::cin >> n; + + std::cout << fibonacci_fast(n) << '\n'; + return 0; +} diff --git a/algorithms/dynamic-programming/gold_mine.cpp b/algorithms/dynamic-programming/gold_mine.cpp new file mode 100644 index 00000000..59f7c2d8 --- /dev/null +++ b/algorithms/dynamic-programming/gold_mine.cpp @@ -0,0 +1,61 @@ +// C++ program to solve Gold Mine problem +#include +using namespace std; + +const int MAX = 100; + +// Returns maximum amount of gold that can be collected +// when journey started from first column and moves +// allowed are right, right-up and right-down +int getMaxGold(int gold[][MAX], int m, int n) +{ + // Create a table for storing intermediate results + // and initialize all cells to 0. The first row of + // goldMineTable gives the maximum gold that the miner + // can collect when starts that row + int goldTable[m][n]; + memset(goldTable, 0, sizeof(goldTable)); + + for (int col=n-1; col>=0; col--) + { + for (int row=0; row) + int right = (col==n-1)? 0: goldTable[row][col+1]; + + // Gold collected on going to the cell to right up (/) + int right_up = (row==0 || col==n-1)? 0: + goldTable[row-1][col+1]; + + // Gold collected on going to the cell to right down (\) + int right_down = (row==m-1 || col==n-1)? 0: + goldTable[row+1][col+1]; + + // Max gold collected from taking either of the + // above 3 paths + goldTable[row][col] = gold[row][col] + + max(right, max(right_up, right_down)); + + } + } + + // The max amount of gold collected will be the max + // value in first column of all rows + int res = goldTable[0][0]; + for (int i=1; i + +// A utility function that returns maximum of two integers +int max(int a, int b) { return (a > b)? a : b; } + +// Returns the maximum value that can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + int i, w; + int K[n+1][W+1]; + + // Build table K[][] in bottom up manner + for (i = 0; i <= n; i++) + { + for (w = 0; w <= W; w++) + { + if (i==0 || w==0) + K[i][w] = 0; + else if (wt[i-1] <= w) + K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); + else + K[i][w] = K[i-1][w]; + } + } + + return K[n][W]; +} + +int main() +{ + int val[] = {60, 100, 120}; + int wt[] = {10, 20, 30}; + int W = 50; + int n = sizeof(val)/sizeof(val[0]); + cout << knapSack(W, wt, val, n); + return 0; +} diff --git a/algorithms/dynamic-programming/largest_divisible_pairs_subset.cpp b/algorithms/dynamic-programming/largest_divisible_pairs_subset.cpp new file mode 100644 index 00000000..053905db --- /dev/null +++ b/algorithms/dynamic-programming/largest_divisible_pairs_subset.cpp @@ -0,0 +1,32 @@ +#include +#define blue ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); + +using namespace std; + +int largestSubset(int a[], int n) +{ + sort(a, a + n); + int dp[n]; + dp[n - 1] = 1; + + for (int i = n - 2; i >= 0; i--) + { + int mxm = 0; + for (int j = i + 1; j < n; j++) + if (a[j] % a[i] == 0) + mxm = max(mxm, dp[j]); + + dp[i] = 1 + mxm; + } + + return *max_element(dp, dp + n); +} + +int main() +{ + blue; + int a[] = { 21, 4, 6, 13, 11, 2 }; + int n = sizeof(a) / sizeof(a[0]); + cout << largestSubset(a, n) << endl; + return 0; +} diff --git a/algorithms/dynamic-programming/largest_sum_contiguous_subarray.cpp b/algorithms/dynamic-programming/largest_sum_contiguous_subarray.cpp new file mode 100644 index 00000000..bdfedeab --- /dev/null +++ b/algorithms/dynamic-programming/largest_sum_contiguous_subarray.cpp @@ -0,0 +1,31 @@ +/* +Author : AMEY GONDHALEKAR +*/ + +#include +#define blue ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); +using namespace std; + +int maxSubArraySum(int arr[], int size) +{ + int maxsofar = arr[0]; + int currentmax = arr[0]; + + for (int i = 1; i < size; i++) + { + currentmax = max(arr[i], currentmax+arr[i]); + maxsofar = max(maxsofar, currentmax); + } + return maxsofar; +} + + +int main() +{ + blue; + int arr[] = {6,-2, -1, 5, -1, -4, 1, 6, -2}; + int n = sizeof(arr)/sizeof(arr[0]); + int sum = maxSubArraySum(arr, n); + cout << "Maximum contiguous sum is " << sum; + return 0; +} diff --git a/algorithms/dynamic-programming/lcs.cpp b/algorithms/dynamic-programming/lcs.cpp new file mode 100644 index 00000000..f3c7aada --- /dev/null +++ b/algorithms/dynamic-programming/lcs.cpp @@ -0,0 +1,61 @@ +// +// Dynamic Programming C/C++ implementation of LCS problem +// +// The All ▲lgorithms library for python +// +// https://allalgorithms.com/dynamic-programming/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Unknown +// Github: Unknown +// +#include + +int max(int a, int b); + +/* Returns length of LCS for X[0..m-1], Y[0..n-1] */ +int lcs( char *X, char *Y, int m, int n ) +{ + int L[m+1][n+1]; + int i, j; + + /* Following steps build L[m+1][n+1] in bottom up fashion. Note + that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ + for (i=0; i<=m; i++) + { + for (j=0; j<=n; j++) + { + if (i == 0 || j == 0) + L[i][j] = 0; + + else if (X[i-1] == Y[j-1]) + L[i][j] = L[i-1][j-1] + 1; + + else + L[i][j] = max(L[i-1][j], L[i][j-1]); + } + } + + /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ + return L[m][n]; +} + +/* Utility function to get max of 2 integers */ +int max(int a, int b) +{ + return (a > b)? a : b; +} + +/* Driver program to test above function */ +int main() +{ + char X[] = "AGGTAB"; + char Y[] = "GXTXAYB"; + + int m = strlen(X); + int n = strlen(Y); + + cout << "Length of LCS is " << lcs( X, Y, m, n ) ; + + return 0; +} diff --git a/algorithms/dynamic-programming/lis.cpp b/algorithms/dynamic-programming/lis.cpp new file mode 100644 index 00000000..0ff515f5 --- /dev/null +++ b/algorithms/dynamic-programming/lis.cpp @@ -0,0 +1,39 @@ +#include +#include + +/* lis() returns the length of the longest increasing + subsequence in arr[] of size n */ +int lis( int arr[], int n ) +{ + int *lis, i, j, max = 0; + lis = (int*) malloc ( sizeof( int ) * n ); + + /* Initialize LIS values for all indexes */ + for (i = 0; i < n; i++ ) + lis[i] = 1; + + /* Compute optimized LIS values in bottom up manner */ + for (i = 1; i < n; i++ ) + for (j = 0; j < i; j++ ) + if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + + /* Pick maximum of all LIS values */ + for (i = 0; i < n; i++ ) + if (max < lis[i]) + max = lis[i]; + + /* Free memory to avoid memory leak */ + free(lis); + + return max; +} + +int main() +{ + /* Driver program to find Longest Increasing Subsequence */ + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; + int n = sizeof(arr)/sizeof(arr[0]); + printf("Length of lis is %d", lis( arr, n ) ); + return 0; +} diff --git a/algorithms/dynamic-programming/longest_increasing_subsequence.cpp b/algorithms/dynamic-programming/longest_increasing_subsequence.cpp new file mode 100644 index 00000000..55073440 --- /dev/null +++ b/algorithms/dynamic-programming/longest_increasing_subsequence.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; +int longestIncreasingSubsequence(int A[],int size){ + int dp[size]; + for(int i=0;i +#define n 3 +using namespace std; + +// Returns length of the longest path beginning with mat[i][j]. +// This function mainly uses lookup table dp[n][n] +int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]) +{ + // Base case + if (i<0 || i>=n || j<0 || j>=n) + return 0; + + // If this subproblem is already solved + if (dp[i][j] != -1) + return dp[i][j]; + + // Since all numbers are unique and in range from 1 to n*n, + // there is atmost one possible direction from any cell + if (j0 && (mat[i][j] +1 == mat[i][j-1])) + return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp); + + if (i>0 && (mat[i][j] +1 == mat[i-1][j])) + return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp); + + if (i +#include + +using namespace std; + + +int MatrixChainMultiplication(int p[], int n) +{ + int m[n][n]; + int i, j, k, L, q; + + for (i=1; i>n; + + + int arr[n]; + + cout<<"Enter dimensions \n"; + + for(i=0;i>arr[i]; + } + + int size = sizeof(arr)/sizeof(arr[0]); + + cout<<"Minimum number of multiplications is "< +using namespace std; + +int largestRectangleArea(vector &hist) { + + + stack s; + int n=hist.size(); + int max_area = 0; + int tp; + int area_with_top; + + int i = 0; + while (i < n) + { + if (s.empty() || hist[s.top()] <= hist[i]) + s.push(i++); + + + else + { + tp = s.top(); + s.pop(); + + area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1); + + if (max_area < area_with_top) + max_area = area_with_top; + } + } + + + while (s.empty() == false) + { + tp = s.top(); + s.pop(); + area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1); + + if (max_area < area_with_top) + max_area = area_with_top; + } + + return max_area; +} + + +int maximalRectangle(vector > &A) { + + int i,j,k,l,n=A.size(),m=A[0].size(),maxi=0; + vector vec(m,0); + + for(i=0;i > vec; + vector arr; + cin>>n>>m; + + for(i=0;i>x; + arr.push_back(x); + } + vec.push_back(arr); + } + + cout< +using namespace std; + + int isSubsetSum(int set[], int n, int sum) + { + bool subset[sum + 1][n + 1]; + int count[sum + 1][n + 1]; + + for (int i = 0; i <= n; i++) + { + subset[0][i] = true; + count[0][i] = 0; + } + + for (int i = 1; i <= sum; i++) + { + subset[i][0] = false; + count[i][0] = -1; + } + + for (int i = 1; i <= sum; i++) + { + for (int j = 1; j <= n; j++) + { + subset[i][j] = subset[i][j - 1]; + count[i][j] = count[i][j - 1]; + if (i >= set[j - 1]) + { + subset[i][j] = subset[i][j] || + subset[i - set[j - 1]][j - 1]; + + if (subset[i][j]) + count[i][j] = max(count[i][j - 1], + count[i - set[j - 1]][j - 1] + 1); + } + } + } + + return count[sum][n]; + } + +int main() +{ + int set[] = { 2, 3, 5, 10 }; + int sum = 20; + int n = 4; + cout<< isSubsetSum(set, n, sum); +} diff --git a/algorithms/dynamic-programming/pretty_printing.c b/algorithms/dynamic-programming/pretty_printing.c new file mode 100644 index 00000000..1e9cb0d7 --- /dev/null +++ b/algorithms/dynamic-programming/pretty_printing.c @@ -0,0 +1,188 @@ +#include +#include +#include +#include + +#define inf FLT_MAX +#define pline printf("\n"); + +int tChar=0; + +struct strg{ + char *x; +}; + +int wordcnt(char *str){ + int i=0;int flag=0; int wc=1; + while(str[i]!='\0'){ + i++; + if(flag==0 && str[i]==' '){ + wc++; + flag=1; + } + else if(str[i]!=' '){ + flag=0; + } + } +return wc; +} + +int* wlen(char *str, int wc){ + int* wl = malloc(sizeof(int)*wc); + int i=0, flag=0, wordlen,j=0; + while(str[i]!='\0'){ + if(flag==0 && str[i]==' '){ + wl[j]=wordlen;j++; + tChar += wordlen; + wordlen=0; + flag=1; + } + else if(str[i]!=' '){ + flag=0; + wordlen++; printf("%c",str[i]); + } + i++; + }wl[j]=wordlen-1;tChar += wordlen-1; +// for(i=0;i=0) + mat[i][j] = (line-temp)*(line-temp); + else + mat[i][j]=50000; + } + } +} + +int* justify(int **mat, int dim){ + int minCost[dim]; + int* result = malloc(sizeof(int)*dim); + int i; + for(i=0;i= 0 ; i--){ + minCost[i] = mat[i][dim-1]; + result[i] = dim; + int j; + for(j=dim-1; j > i; j--){ + if(mat[i][j-1] == 50000){ + continue; + } + if(minCost[i] > (minCost[j] + mat[i][j-1])){ + minCost[i] = minCost[j] + mat[i][j-1]; + result[i] = j; + } + } + } + printf("Min cost %d\n",minCost[0]); + for(i=0;imax){ + max=q[j]; + n[k]=max;k++; + } + } + for(i=0;i-1; i--) + mat[i]=(int*)calloc(i+1,sizeof(int)); + +badness(mat,p,dim,10); + +printf("Badness Matrix: \n"); +for(i=0; i=i?mat[i][j]:0,j!=dim-1?' ':'\n'); + +int *q = justify(mat,dim); +printf("tchar %d\n",tChar); +char *pstr = clearText(str, tChar); +pretty(pstr,p,q,dim); + +return 0; +} diff --git a/algorithms/dynamic-programming/rod_cutting.cpp b/algorithms/dynamic-programming/rod_cutting.cpp new file mode 100644 index 00000000..ac93e726 --- /dev/null +++ b/algorithms/dynamic-programming/rod_cutting.cpp @@ -0,0 +1,46 @@ +#include +#include + +using namespace std; + +int rodCutting(int n, int value[]) +{ + int i,j; + + + int result[n+1]; + + result[0]=0; + + for(i=1;i<=n;i++) + { + result[i]=INT_MIN; + + for(j=0;j>n; + + int value[n]; + cout<<"Enter the values of pieces of rod of all size"<>value[i]; + + cout<<"Maximum obtainable value by cutting up the rod in many pieces are"< +using namespace std; + +// Function to count numbers of such subsequences +// having product less than k. +int productSubSeqCount(vector &arr, int k) +{ + int n = arr.size(); + int dp[k + 1][n + 1]; + memset(dp, 0, sizeof(dp)); + + for (int i = 1; i <= k; i++) { + for (int j = 1; j <= n; j++) { + + // number of subsequence using j-1 terms + dp[i][j] = dp[i][j - 1]; + + // if arr[j-1] > i it will surely make product greater + // thus it won't contribute then + if (arr[j - 1] <= i && arr[j - 1] > 0) + + // number of subsequence using 1 to j-1 terms + // and j-th term + dp[i][j] += dp[i/arr[j-1]][j-1] + 1; + } + } + return dp[k][n]; +} + +// Driver code +int main() +{ + vector A; + A.push_back(1); + A.push_back(2); + A.push_back(3); + A.push_back(4); + int k = 10; + cout << productSubSeqCount(A, k) << endl; +} diff --git a/algorithms/dynamic-programming/ways_to_cover.cpp b/algorithms/dynamic-programming/ways_to_cover.cpp new file mode 100644 index 00000000..c64b5a2b --- /dev/null +++ b/algorithms/dynamic-programming/ways_to_cover.cpp @@ -0,0 +1,37 @@ +// +// A Dynamic Programming based C++ program to count number of ways +// to cover a distance with 1, 2 and 3 steps +// +// The All ▲lgorithms library for python +// +// https://allalgorithms.com/dynamic-programming/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Unknown +// Github: Unknown +// +#include +using namespace std; + +int printCountDP(int dist) +{ + int count[dist+1]; + + // Initialize base values. There is one way to cover 0 and 1 + // distances and two ways to cover 2 distance + count[0] = 1, count[1] = 1, count[2] = 2; + + // Fill the count array in bottom up manner + for (int i=3; i<=dist; i++) + count[i] = count[i-1] + count[i-2] + count[i-3]; + + return count[dist]; +} + +// driver program +int main() +{ + int dist = 4; + cout << printCountDP(dist); + return 0; +} diff --git a/algorithms/dynamic.cpp b/algorithms/dynamic.cpp new file mode 100644 index 00000000..15563d86 --- /dev/null +++ b/algorithms/dynamic.cpp @@ -0,0 +1,79 @@ +//Stack is a data structure based on a last in first out (LIFO) method +//This code defines and implements stack's functions using linked list + + +#include +#include +void pop(); +void push(); +void display(); +struct node{ + int value; + struct node *link; + }*top=NULL; + +void main(){ + int choice; + do{ + printf("*****Menu*****"); + printf("\n1.Push\n2.Pop\n3.Display\n4.Exit"); + printf("\nEnter you choice number::\t"); + scanf("%d",&choice"); + switch(choice){ + case 1: push(); + break; + case 2: pop(); + break; + case 3: display(); + break; + case 4: exit(0); + default:printf("\nWrong choice, Try entering again"); + } + }while(1); + getch(); + } + + void push(){ + int n; + ptr=(struct node *)malloc(sizeof(struct node)); + if (!ptr) + { + printf("\nMemory Overflow"); + return; + } + + printf("\nEnter the number to be pushed"); + scanf("%d",n); + ptr->value=n; + top->link=ptr; + top=ptr; + printf("\nElement pushed Successfully"); + } +void pop(){ + struct node *ptr=top; + if(!top) + { + printf("\nMemory Underflow"); + return; + } + top=top->link; + free(ptr); + printf("\nElement popped succefully"); + } + void display(){ + struct node *ptr=top; + printf("\n"); + if(!top) + { + printf("The stack is Empty"); + return; + } + while(!ptr) + { + printf("\t%d",ptr->value"); + ptr=ptr->link; + } + } + + + diff --git a/algorithms/factorial_sum.cpp b/algorithms/factorial_sum.cpp new file mode 100644 index 00000000..02d11899 --- /dev/null +++ b/algorithms/factorial_sum.cpp @@ -0,0 +1,22 @@ +Following are the steps for an efficient solution: + +n! can be represented as :- n! = (a1^p1) (a2^p2)x...(ak^pk). + +where ak is the prime divisor lesser than n and pk is the highest power which can divide n!. + +Through sieve find the prime number and the highest power can be easily find out by : + +countofpower = [n/a] + [n/a^2] + [n/a^3] +...... or ` while (n) +{ + n/ = a; + ans += n +} +Count Of Factors = (ans1 +1)*(ans2 +1)*....(ansk +1) + +After calculating this last step is the sum : + +SUM = product of all (pow(ak,pk+1)-1)/(ak-1); +ex = 4! +4! = 2^3 * 3^1; +count of factors = (3+1)*(1+1) = 8 (1,2,3,4,6,8,12,24) +sum = ( 1 + 2 + 4 + 8)*(1 + 3) = 60. diff --git a/algorithms/floyd_warshall.cpp b/algorithms/floyd_warshall.cpp new file mode 100644 index 00000000..07951274 --- /dev/null +++ b/algorithms/floyd_warshall.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; +#define V 4 +#define INF 99999 +void printSolution(int dist[][V]); +void floydWarshall (int graph[][V]) +{ + int dist[V][V], i, j, k; + for (i = 0; i < V; i++) + for (j = 0; j < V; j++) + dist[i][j] = graph[i][j]; + for (k = 0; k < V; k++) + { + for (i = 0; i < V; i++) + { + for (j = 0; j < V; j++) + { + if (dist[i][k] + dist[k][j] < dist[i][j]) + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + printSolution(dist); +} +void printSolution(int dist[][V]) +{ + cout<<"The following matrix shows the shortest distances" + " between every pair of vertices \n"; + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { + if (dist[i][j] == INF) + cout<<"INF"<<" "; + else + cout< +#include + +#define MAX_DEGREE 5 +#define MAX_NUM_VERTICES 20 + +struct vertices_s { + int visited; + int deg; + int adj[MAX_DEGREE]; /* < 0 if incoming edge */ +} vertices[] = { + {0, 3, {2, -3, 4}}, + {0, 2, {-1, 3}}, + {0, 3, {1, -2, 7}}, + {0, 3, {-1, -5, 6}}, + {0, 2, {4, -7}}, + {0, 3, {-4, 7, -8}}, + {0, 4, {-3, 5, -6, -12}}, + {0, 3, {6, -9, 11}}, + {0, 2, {8, -10}}, + {0, 3, {9, -11, -12}}, + {0, 3, {-8, 10, 12}}, + {0, 3, {7, 10, -11}} +}; +int num_vertices = sizeof(vertices) / sizeof(vertices[0]); + +struct stack_s { + int top; + int items[MAX_NUM_VERTICES]; +} stack = {-1, {}}; + +void stack_push(int v) { + stack.top++; + if (stack.top < MAX_NUM_VERTICES) + stack.items[stack.top] = v; + else { + printf("Stack is full!\n"); + exit(1); + } +} + +int stack_pop() { + return stack.top < 0 ? -1 : stack.items[stack.top--]; +} + +void dfs(int v, int transpose) { + int i, c, n; + vertices[v].visited = 1; + for (i = 0, c = vertices[v].deg; i < c; ++i) { + n = vertices[v].adj[i] * transpose; + if (n > 0) + /* n - 1 because vertex indexing begins at 0 */ + if (!vertices[n - 1].visited) + dfs(n - 1, transpose); + } + if (transpose < 0) + stack_push(v); + else + printf("%d ", v + 1); +} + +void reset_visited() { + int i; + for (i = 0; i < num_vertices; ++i) + vertices[i].visited = 0; +} + +void order_pass() { + int i; + for (i = 0; i < num_vertices; ++i) + if (!vertices[i].visited) + dfs(i, -1); +} + +void scc_pass() { + int i = 0, v; + while((v = stack_pop()) != -1) { + if (!vertices[v].visited) { + printf("scc %d: ", ++i); + dfs(v, 1); + printf("\n"); + } + } +} + +int main(void) { + order_pass(); + reset_visited(); + scc_pass(); + return 0; +} diff --git a/algorithms/graphs/Kruskal's.cpp b/algorithms/graphs/Kruskal's.cpp new file mode 100644 index 00000000..3ebb1d5d --- /dev/null +++ b/algorithms/graphs/Kruskal's.cpp @@ -0,0 +1,131 @@ +// C++ program for Kruskal's algorithm to find Minimum +// Spanning Tree of a given connected, undirected and +// weighted graph +#include +using namespace std; + +// Creating shortcut for an integer pair + + +// Structure to represent a graph +struct Graph +{ + int V, E; + vector< pair> > edges; + Graph(int V, int E) + { + this->V = V; + this->E = E; + } + // Utility function to add an edge + void addEdge(int u, int w, int v) + { + edges.push_back({w, {u, v}}); + } + int kruskalMST(); +}; + +// To represent Disjoint Sets +struct DisjointSets +{ + int *parent, *rnk; + int n; + + // Constructor. + DisjointSets(int n) + { + // Allocate memory + this->n = n; + parent = new int[n+1]; + rnk = new int[n+1]; + for (int i = 0; i <= n; i++) + { + rnk[i] = 0; + parent[i] = i; + } + } + int find(int u) + { + if (u != parent[u]) + parent[u] = find(parent[u]); + return parent[u]; + } + + // Union by rank + void merge(int x, int y) + { + x = find(x), y = find(y); + + /* Make tree with smaller height + a subtree of the other tree */ + if (rnk[x] > rnk[y]) + parent[y] = x; + else // If rnk[x] <= rnk[y] + parent[x] = y; + + if (rnk[x] == rnk[y]) + rnk[y]++; + } +}; + +/* Functions returns weight of the MST*/ + +int Graph::kruskalMST() +{ + int mst_wt = 0; // Initialize result + + // Sort edges in increasing order on basis of cost + sort(edges.begin(), edges.end()); + + // Create disjoint sets + DisjointSets ds(V); + + // Iterate through all sorted edges + vector< pair> >::iterator it; + for (it=edges.begin(); it!=edges.end(); it++) + { + int u = it->second.first; + int v = it->second.second; + + int set_u = ds.find(u); + int set_v = ds.find(v); + + // Check if the selected edge is creating + // a cycle or not (Cycle is created if u + // and v belong to same set) + if (set_u != set_v) + { + cout << u << " - " << v << endl; + mst_wt += it->first; + ds.merge(set_u, set_v); + } + } + + return mst_wt; +} + +// Driver program to test above functions +int main() +{ + /* Let us create above shown weighted + and unidrected graph */ + int V = 9, E = 14; + Graph g(V, E); + // making above shown graph + g.addEdge(0, 5, 1); + g.addEdge(0, 10, 3); + g.addEdge(1, 2, 2); + g.addEdge(1, 10, 5); + g.addEdge(1, 5, 4); + g.addEdge(2, 1, 3); + g.addEdge(2, 5, 4); + g.addEdge(2, 3, 0); + g.addEdge(4, 2, 5); + + cout << "Edges of MST are \n"; + int mst_wt = g.kruskalMST(); + + cout << "\nWeight of MST is " << mst_wt; + + return 0; +} diff --git a/algorithms/graphs/MST_using_Kruskals.cpp b/algorithms/graphs/MST_using_Kruskals.cpp new file mode 100644 index 00000000..f602081f --- /dev/null +++ b/algorithms/graphs/MST_using_Kruskals.cpp @@ -0,0 +1,136 @@ +#include +#include +using namespace std; +int flag = 0, v[3]; +struct node_info +{ + int no; +}*q = NULL, *r = NULL; +struct node +{ + node_info *pt; + node *next; +}*top = NULL, *p = NULL, *np = NULL; +void push(node_info *ptr) +{ + np = new node; + np->pt = ptr; + np->next = NULL; + if (top == NULL) + { + top = np; + } + else + { + np->next = top; + top = np; + } +} + node_info *pop() +{ + if (top == NULL) + { + cout<<"underflow\n"; + } + else + { + p = top; + top = top->next; + return(p->pt); + delete(p); + } + return 0; +} +int back_edges(int *v,int am[][3],int i,int k) +{ + q = new node_info; + q->no = i; + push(q); + v[i] = 1; + for (int j = 0; j < 3; j++) + { + if (am[i][j] == 1 && v[j] == 0) + { + back_edges(v, am, j, i); + } + else if (am[i][j] == 0) + continue; + else if ((j == k) && (am[i][k] == 1 && v[j] == 1)) + continue; + else + { + flag = -1; + } + } + r = pop(); + return(flag); +} +void init() +{ + for (int i = 0; i < 3; i++) + v[i] = 0; + while (top != NULL) + { + pop(); + } +} +void kruskals(int am[][3], int wm[][3]) +{ + int ve = 1, min, temp, temp1; + cout<<"/n/nEDGES CREATED AS FOLLOWS:-/n/n"; + while (ve <= 6) + { + min = 999, temp = 0, temp1 = 0; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + if ((wm[i][j] < min) && wm[i][j]!=0) + { + min = wm[i][j]; + temp = i; + temp1 = j; + } + else if (wm[i][j] == 0) + continue; + } + } + wm[temp][temp1]=wm[temp1][temp] = 999; + am[temp][temp1]=am[temp1][temp] = 1; + init(); + if (back_edges(v, am, temp, 0) < 0) + { + am[temp][temp1]=am[temp1][temp] = 0; + flag = 0; + continue; + } + else + { + cout<<"edge created between "<>wm[i][j]; + } + } + kruskals(am,wm); + return 0; +} diff --git a/algorithms/graphs/bellman_ford.cpp b/algorithms/graphs/bellman_ford.cpp new file mode 100644 index 00000000..6bdf1c71 --- /dev/null +++ b/algorithms/graphs/bellman_ford.cpp @@ -0,0 +1,117 @@ +// +// BellmanFord algorithm implementation in C++ +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/cpp/graphs/bellman-ford/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Nikunj Taneja +// Github: @underscoreorcus +// +#include + +struct Edge +{ + int src, dest, weight; +}; + +struct Graph +{ + // V-> Number of vertices, E-> Number of edges + int V, E; + // graph is represented as an array of edges. + struct Edge* edge; +}; + +struct Graph* createGraph(int V, int E) +{ + struct Graph* graph = new Graph; + graph->V = V; + graph->E = E; + graph->edge = new Edge[E]; + return graph; +} + +void printArr(int dist[], int n) +{ + printf("Vertex Distance from Source\n"); + for (int i = 0; i < n; ++i) + printf("%d \t\t %d\n", i, dist[i]); +} + +void BellmanFord(struct Graph* graph, int src) +{ + int V = graph->V; + int E = graph->E; + int dist[V]; + + // Step 1: Initialize distances from src to all other vertices + // as INFINITE + for (int i = 0; i < V; i++) + dist[i] = INT_MAX; + dist[src] = 0; + + // Step 2: Relax all edges |V| - 1 times. A simple shortest + // path from src to any other vertex can have at-most |V| - 1 + // edges + for (int i = 1; i <= V-1; i++) + { + for (int j = 0; j < E; j++) + { + int u = graph->edge[j].src; + int v = graph->edge[j].dest; + int weight = graph->edge[j].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + + // Step 3: check for negative-weight cycles. The above step + // guarantees shortest distances if graph doesn't contain + // negative weight cycle. If we get a shorter path, then there + // is a cycle. + for (int i = 0; i < E; i++) + { + int u = graph->edge[i].src; + int v = graph->edge[i].dest; + int weight = graph->edge[i].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) + printf("Graph contains negative weight cycle"); + } + printArr(dist, V); + return; +} +int main() +{ + /* Sample graph */ + int V = 5; + int E = 8; + struct Graph* graph = createGraph(V, E); + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + graph->edge[0].weight = -1; + graph->edge[1].src = 0; + graph->edge[1].dest = 2; + graph->edge[1].weight = 4; + graph->edge[2].src = 1; + graph->edge[2].dest = 2; + graph->edge[2].weight = 3; + graph->edge[3].src = 1; + graph->edge[3].dest = 3; + graph->edge[3].weight = 2; + graph->edge[4].src = 1; + graph->edge[4].dest = 4; + graph->edge[4].weight = 2; + graph->edge[5].src = 3; + graph->edge[5].dest = 2; + graph->edge[5].weight = 5; + graph->edge[6].src = 3; + graph->edge[6].dest = 1; + graph->edge[6].weight = 1; + graph->edge[7].src = 4; + graph->edge[7].dest = 3; + graph->edge[7].weight = -3; + BellmanFord(graph, 0); + return 0; +} diff --git a/algorithms/graphs/bfs.cpp b/algorithms/graphs/bfs.cpp new file mode 100644 index 00000000..d2b504d6 --- /dev/null +++ b/algorithms/graphs/bfs.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; +char mx[100][100]; +bool visited[100][100]; +int V,E,k,l,N,M; +bool isvalid(int x,int y) +{ + if(x<=N && y<=M && x>=1 && y>=1) + return true; + return false; +} +bool bfs(int x,int y) +{ + for(int i=1;i<100;i++) + for(int j=1;j<100;j++) + visited[i][j]=0; +queue > q; +q.push({x,y}); +visited[x][y]=1; +while(!q.empty()) +{ + x=q.front().first; + y=q.front().second; + visited[x][y]=true; + q.pop(); + if(isvalid(x,y+1) && !visited[x][y+1] && mx[x][y+1]==mx[x][y]) + q.push({x,y+1}); + if(isvalid(x,y-1) && !visited[x][y-1] && mx[x][y-1]==mx[x][y]) + q.push({x,y-1}); + if(isvalid(x+1,y) && !visited[x+1][y] && mx[x+1][y]==mx[x][y]) + q.push({x+1,y}); + if(isvalid(x-1,y) && !visited[x-1][y] && mx[x-1][y]==mx[x][y]) + q.push({x-1,y}); + int counter=0; + if(visited[x][y+1]) + counter++; + if(visited[x][y-1]) + counter++; + if(visited[x+1][y]) + counter++; + if(visited[x-1][y]) + counter++; + if(counter>1) + return true; + +} +return false; +} + +int main() +{ + cin>>N>>M; + for(int i=1;i<=N;i++) + for(int j=1;j<=M;j++) + cin>>mx[i][j]; + for(int i=1;i<=N;i++) + for(int j=1;j<=M;j++) + if( bfs(i,j)){ + cout<<"Yes"; + return 0; + } + + cout<<"No"; + + + + return 0; +} diff --git a/algorithms/graphs/count_diconnected_components.cpp b/algorithms/graphs/count_diconnected_components.cpp new file mode 100644 index 00000000..5c71c96d --- /dev/null +++ b/algorithms/graphs/count_diconnected_components.cpp @@ -0,0 +1,80 @@ +// +// Count disconnected components implementation in C++ +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/graphs +// https://github.com/allalgorithms/cpp +// +// Contributed by: Rituparno Biswas +// Github: @roopbiswas +// +#include +#include +using namespace std; + +int count=1; +// Graph class represents a directed graph +// using adjacency list representation +class Graph +{ + int V; + list *adj; + void DFSUtil(int v, bool visited[]); +public: + Graph(int V); + void addEdge(int v, int w); + void DFS(int v); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::DFSUtil(int v, bool visited[]) +{ + visited[v] = true; + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); +} +void Graph::DFS(int v) +{ + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + DFSUtil(v, visited); + for (int i = 0; i < V; i++) + if(visited[i] == false) + { + count++; + DFSUtil(i, visited); + } +} + +int main() +{ + Graph g(9); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + g.addEdge(4, 5); + g.addEdge(6, 7); + g.addEdge(6, 8); + + g.DFS(2); + cout << "Number of disconnected components in the given graph is : " < + +using namespace std; + +long long answer = 0; +int N, M; +bool map[50][50] = { + 0, +}; + +void dfs(int start, int current, int before, int depth) { + if (depth == 2) { + if (current == start) { + answer++; + } + return; + } + + int iteration_start, iteration_end; + if (depth != 1) { + iteration_start = current + 1; + iteration_end = N; + } else { + iteration_start = 0; + iteration_end = current; + } + + for (int i = iteration_start; i < iteration_end; i++) { + if (map[current][i] && i != before) { + dfs(start, i, current, depth + 1); + } + } +} + +void solution() { + answer = 0; + cin >> N >> M; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + map[i][j] = 0; + } + } + + int x, y; + for (int i = 0; i < M; i++) { + cin >> x >> y; + x--; + y--; + map[x][y] = 1; + map[y][x] = 1; + } + + for (int i = 0; i < N - 1; i++) { + for (int j = i + 1; j < N; j++) { + if (map[i][j]) { + dfs(i, j, i, 0); + } + } + } + + cout << "number of triangle : " << answer; +} + +int main() { + ios_base ::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + + solution(); + + return 0; +} \ No newline at end of file diff --git a/algorithms/graphs/cpp-graph_class.cpp b/algorithms/graphs/cpp-graph_class.cpp new file mode 100644 index 00000000..039c23aa --- /dev/null +++ b/algorithms/graphs/cpp-graph_class.cpp @@ -0,0 +1,198 @@ +/**Author : Vivek Bhardwaj + * Contributed to : https://github.com/AllAlgorithms/cpp + **/ + +#include +using namespace std; + +class graph{ + private : + vector> adj; + vector> weight_matrix; + vector visited; + vector distance; + vector> edge_list; + long long ** weight; + const long long INF=1e18; + + + void visited_util(){ + fill(visited.begin(),visited.end(),false); + } + + void dfs_util(int start){ + visited[start]=true; + //do something ...... + cout< q; q.push(start); visited[start]=true; + //do something ...... + //cout<vertices=vertex; + } + + void add_directed_edge(int from,int to){ + adj[from].push_back(to); + edge_list.emplace_back(from,to); + } + + void add_directed_edge(int from,int to,int weigh){ + adj[from].push_back(to); + weight[from][to]=weigh; + edge_list.emplace_back(from,to); + } + + void add_undirected_edge(int x,int y,int weigh=1){ + adj[x].push_back(y); + adj[y].push_back(x); + edge_list.emplace_back(x,y); + edge_list.emplace_back(y,x); + weight[x][y]=weigh; + weight[y][x]=weigh; + } + + void bfs(int start){ + visited_util(); + bfs_util(start); + } + + void dfs(int start){ + visited_util(); + dfs_util(start); + } + + void dijkstra(int start){ + visited_util(); + fill(distance.begin(),distance.end(),INF); + distance[start]=0; + dijkstra_util(start); + } + + void bellman_ford(int start){ + visited_util(); + fill(distance.begin(),distance.end(),INF); + distance[start]=0; + bellman_ford_util(start); + } + + void floyd_warshell(){ + + for(int i=0;i +#include +#include +#include +using namespace std; + +vector visited; //this vector will mark visited components +vector > graph; //this will store the graph represented internally as an adjacency list +//this is because the adjacency list representation is the most suited to use DFS procedure on a given graph + +int sz_connect_comp = 0; //this will store the size of current connected component (problem-specific feature) + +void dfs(int v) +{ + sz_connect_comp++; //"useful feature" performed on this DFS, this can vary from problem to problem + visited[v] = true; + + for(vector::iterator it = graph[v].begin(); it != graph[v].end(); it++) + { + if(! visited[*it]) //note that *it represents the adjacent vertex itself + { + dfs(*it); + } + } +} + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n,m; + cin >> n >> m; + graph = vector > (n); //initialization of the graph + for(int i = 0; i < m; i++) + { + int u,v; + cin >> u >> v; + u--; + v--; + //these are added this way due to the friendship relation being mutual + graph.push_back(v); + graph[v].push_back(u); + } + int res = 0; // the number of fire escape routes + int ways = 1; // the number of ways to choose drill captains + visited = vector (n, 0); // initially mark all vertices as unvisited + for(int u = 0; u < n; u++) + { + //if the vertex was visited we skip it. + if(visited==true) + continue; + // if vertex was not visited it starts a new component + res++; // so we increase res + sz_connect_comp = 0; // init sz_connect_comp + dfs(u); // and calculate it through the dfs, marking visited vertices + // we multiply ways by sz_connect_comp modulo 1000000007 + ways = (long long)sz_connect_comp * ways % 1000000007; + } + printf("%d %d", res, ways); + + } + return 0; +} diff --git a/algorithms/graphs/dijkstra.cpp b/algorithms/graphs/dijkstra.cpp new file mode 100644 index 00000000..e41a8785 --- /dev/null +++ b/algorithms/graphs/dijkstra.cpp @@ -0,0 +1,89 @@ +// +// Dijkstra search algorithm implementation in C++ +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/graphs/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Nikunj Taneja +// Github: @underscoreorcus +// +#include +#include + +// Number of vertices in the graph +#define V 9 +int minDistance(int dist[], bool sptSet[]) +{ + // Initialize min value + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + + return min_index; +} + +void printSolution(int dist[], int n) +{ + printf("Vertex Distance from Source\n"); + for (int i = 0; i < V; i++) + printf("%d tt %d\n", i, dist[i]); +} + +void dijkstra(int graph[V][V], int src) +{ + int dist[V]; // The output array. dist[i] will hold the shortest + // distance from src to i + + bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest + // path tree or shortest distance from src to i is finalized + + // Initialize all distances as INFINITE and stpSet[] as false + for (int i = 0; i < V; i++) + dist[i] = INT_MAX, sptSet[i] = false; + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V-1; count++) + { + // Pick the minimum distance vertex from the set of vertices not + // yet processed. u is always equal to src in the first iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of the picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, there is an edge from + // u to v, and total weight of path from src to v through u is + // smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX + && dist[u]+graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + printSolution(dist, V); +} + +int main() +{ + /* Sample graph */ + int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, + {4, 0, 8, 0, 0, 0, 0, 11, 0}, + {0, 8, 0, 7, 0, 4, 0, 0, 2}, + {0, 0, 7, 0, 9, 14, 0, 0, 0}, + {0, 0, 0, 9, 0, 10, 0, 0, 0}, + {0, 0, 4, 14, 10, 0, 2, 0, 0}, + {0, 0, 0, 0, 0, 2, 0, 1, 6}, + {8, 11, 0, 0, 0, 0, 1, 0, 7}, + {0, 0, 2, 0, 0, 0, 6, 7, 0} + }; + dijkstra(graph, 0); + return 0; +} diff --git a/algorithms/graphs/dijkstra_list.cc b/algorithms/graphs/dijkstra_list.cc new file mode 100644 index 00000000..06a112ee --- /dev/null +++ b/algorithms/graphs/dijkstra_list.cc @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include +#include +using namespace std; +#define INF 999999 + +typedef pair pii; + +list adj[INF]; +int V; +vector previous(INF, -1); +int dijkstra(int src, int dest) { + priority_queue, greater > pq; + + vector dist(INF, INF); + previous.resize(V); + pq.push(make_pair(0, src)); + dist[src] = 0; + while(!pq.empty()) { + int u = pq.top().second; + pq.pop(); + + for(auto const& i : adj[u]) { + int v = i.first; + int w = i.second; + + if(dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + pq.push({dist[v], v}); + previous[v] = u; + } + } + } + + return dist[dest]; +} + +void dijShortPath(int v, list& path) { +/* example: +v = 6; +v = previous[6] (5) +v = previous[5] (2) +... +*/ + for(; v != -1; v = previous[v]) + path.push_front(v); +} + +int main() { +/* +nVertex nEdges +sorg dest +ver1 ver2 weight +... +*/ + cin >> V; + int e, sorg, dest; + cin >> e >> sorg >> dest; + int u, v, w; + for(int i = 0; i < e; i++) { + cin >> u >> v >> w; + adj[u].push_back(make_pair(v, w)); + } + cout << dijkstra(sorg, dest) << endl; + list path; + dijShortPath(dest, path); + for(auto const& i : path) + cout << i << ' '; + + return 0; +} diff --git a/algorithms/graphs/find_articulation_points.cpp b/algorithms/graphs/find_articulation_points.cpp new file mode 100755 index 00000000..cf6d772b --- /dev/null +++ b/algorithms/graphs/find_articulation_points.cpp @@ -0,0 +1,69 @@ +//this code can be used to find Articulation points in a Graph +#include +using namespace std; + +int timee;// a variable to keep track of the time at which a particular vertex is encounterd + +vector graph[100];//adjacency list for the graph (100 is the max number of vertices.. you can change as per your needs) +bool visited[100] , AP[100]; +//visited - bool array used in DFS to know whether the node is visited or not +//AP - bool array to tell whether ith vertex is a AP or NOT + +int disc[100] , low[100] , parent[100]; +//disc - discovery time of a vertex +//low - exit time of a source +//parent - array to tell the parent of ith vertex + +//finding all APs +void printAP2(int source){ + visited[source] = true; + disc[source] = timee++; + low[source] = disc[source]; + int child = 0; + for(auto i : graph[source]){ + if(!visited[i]){ + child++; + parent[i] = source; + printAP2(i); + low[source] = min(low[i] , low[source]); + + if(parent[source] == source){ + if(child > 1) AP[source] = true; + } + else{ + if(low[i] >= disc[source]) AP[source] = true; // IMP + } + } + else if(i != parent[source]) low[source] = min(low[i] , low[source]); + } +} + +//find and print all APs +void printAP(int n , int source){ + for(int i = 0 ; i < n ; i++) low[i] = INT_MAX; + parent[source] = source; //initializing source os source vertex to itself + printAP2(source); + for(int i = 0 ; i < n ; i++){ + if(!visited[i]){ + parent[i] = i; + printAP2(i); + } + } + for(int i = 0 ; i < n ; i++){ + if(AP[i]) cout << i << " "; + } + cout << endl; +} + +int main(){ + //n - no. of vertices , e - no. of edges + int n , e , u , v; + cin >> n >> e; + //inputting e edges + for(int i = 0 ; i < e ; i++){ + cin >> u >> v; + graph[u].push_back(v); + graph[v].push_back(u); + } + printAP(n , 0); +} diff --git a/algorithms/graphs/floyd_warshall.cpp b/algorithms/graphs/floyd_warshall.cpp new file mode 100644 index 00000000..74e6b0d3 --- /dev/null +++ b/algorithms/graphs/floyd_warshall.cpp @@ -0,0 +1,80 @@ +// +// Floyd Warshall algorithm implementation in C++ +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/graphs/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Nikunj Taneja +// Github: @underscoreorcus +// +#include + +#define V 4 // Number of vertices in the graph +#define INF 1e7 + +void printSolution(int dist[][V]); +void floydWarshall (int graph[][V]) +{ + int dist[V][V], i, j, k; + /* Initialize the solution matrix same as input graph matrix. Or + we can say the initial values of shortest distances are based + on shortest paths considering no intermediate vertex. */ + for (i = 0; i < V; i++) + for (j = 0; j < V; j++) + dist[i][j] = graph[i][j]; + /* Add all vertices one by one to the set of intermediate vertices. + ---> Before start of an iteration, we have shortest distances between all + pairs of vertices such that the shortest distances consider only the + vertices in set {0, 1, 2, .. k-1} as intermediate vertices. + ----> After the end of an iteration, vertex no. k is added to the set of + intermediate vertices and the set becomes {0, 1, 2, .. k} */ + for (k = 0; k < V; k++) + { + // Pick all vertices as source one by one + for (i = 0; i < V; i++) + { + // Pick all vertices as destination for the + // above picked source + for (j = 0; j < V; j++) + { + // If vertex k is on the shortest path from + // i to j, then update the value of dist[i][j] + if (dist[i][k] + dist[k][j] < dist[i][j]) + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + // Print the shortest distance matrix + printSolution(dist); +} + +void printSolution(int dist[][V]) +{ + printf ("The following matrix shows the shortest distances" + " between every pair of vertices \n"); + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { + if (dist[i][j] == INF) + printf("%7s", "INF"); + else + printf ("%7d", dist[i][j]); + } + printf("\n"); + } +} + +int main() +{ + // Sample graph + int graph[V][V] = { {0, 5, INF, 10}, + {INF, 0, 3, INF}, + {INF, INF, 0, 1}, + {INF, INF, INF, 0} + }; + floydWarshall(graph); + return 0; +} diff --git a/algorithms/graphs/grith.cpp b/algorithms/graphs/grith.cpp new file mode 100644 index 00000000..54483d21 --- /dev/null +++ b/algorithms/graphs/grith.cpp @@ -0,0 +1,64 @@ +#include + +using namespace std; + + +typedef vector vi; +typedef pair pi; + +#define int long long +#define F first +#define S second +#define PB push_back +#define MP make_pair +#define REP(i, a, b) for(int i =a;i < b; i++) + +const int MX = 2e5 + 3; +vi adj[MX]; +int mark[MX],dis[MX], ans; + +void DFS(int u, int par, int k); + +int32_t main() +{ + ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); + int n, m; + int u, v; + cin>>n>>m; + ans = m + 1; + REP(i, 0, m) + { + cin>>u>>v; + adj[v].PB(u); + adj[u].PB(v); + } + REP(i, 1, n+1) + { + dis[i]=0; + DFS(i, -1, mark[i]); + } + if(ans == m+1) cout<<-1; + else cout< +#include +#include +#include + +using namespace std; + +class Edge { + public: + int nbr; + int wt; +}; +vector> graph; + +void addEdge(int v1, int v2, int wt) +{ + Edge e1; + e1.nbr = v2; + e1.wt = wt; + graph[v1].push_back(e1); + + Edge e2; + e2.nbr = v1; + e2.wt = wt; + graph[v2].push_back(e2); +} + +void display() +{ + for(int v = 0; v < graph.size(); v++) + { + cout << v << " -> "; + for(int n = 0; n < graph[v].size(); n++) + { + Edge ne = graph[v][n]; + cout << "[" << ne.nbr << "-" << ne.wt << "], "; + } + cout << "." << endl; + } +} + +bool haspath(int s, int d, vector& visited) +{ + if(s == d) + { + return true; + } + + visited[s] = true; + for(int n = 0; n < graph[s].size(); n++) + { + Edge ne = graph[s][n]; + if(visited[ne.nbr] == false) + { + bool hpfntod = haspath(ne.nbr, d, visited); + if(hpfntod == true) + { + return true; + } + } + } + + return false; +} + +void printallpaths(int s, int d, vector& visited, + string psf, int dsf) +{ + if(s == d) + { + cout << psf << d << "@" << dsf << endl; + return; + } + visited[s] = true; + for(int n = 0; n < graph[s].size(); n++) + { + Edge ne = graph[s][n]; + if(visited[ne.nbr] == false) + { + printallpaths(ne.nbr, d, visited, + psf + to_string(s), + dsf + ne.wt); + } + } + visited[s] = false; +} +void hamiltonian(int s, vector& visited, string asf, int os) +{ + if(csf == graph.size()-1) + cout<()); // 0 + graph.push_back(vector()); // 1 + graph.push_back(vector()); // 2 + graph.push_back(vector()); // 3 + graph.push_back(vector()); // 4 + graph.push_back(vector()); // 5 + graph.push_back(vector()); // 6 + + addEdge(0, 1, 10); + addEdge(1, 2, 10); + addEdge(2, 3, 10); + addEdge(0, 3, 40); + addEdge(3, 4, 2); + addEdge(4, 5, 3); + addEdge(5, 6, 3); + addEdge(4, 6, 8); + + display(); + vector visited (7, false); + // cout << haspath(0, 6, visited) << endl; + printallpaths(0, 6, visited, "", 0); +} \ No newline at end of file diff --git a/algorithms/graphs/kosaraju.cpp b/algorithms/graphs/kosaraju.cpp new file mode 100644 index 00000000..62c7f5cf --- /dev/null +++ b/algorithms/graphs/kosaraju.cpp @@ -0,0 +1,83 @@ +#include +using namespace std; +void print(vector < list > adjlist,int i,bool vis[]) +{ //print strongly connected components + vis[i]=true; + cout< "; + list::iterator it; + for(it=adjlist[i].begin();it!=adjlist[i].end();it++) + { + if(!vis[*it]) + print(adjlist,*it,vis); + } + cout< fillstack(vector < list > adjlist,int i, stack order,bool vis[]) +{ + vis[i]=true; + list::iterator it; + for(it=adjlist[i].begin();it!=adjlist[i].end();it++) + { + if(vis[*it]==false) + fillstack(adjlist,*it,order,vis); + } + order.push(i); + //cout< > adjlist, int v) +{ int count=0; + bool vis[v]; + int i; + //mark all nodes as unvisited + for(i=0;i<=v;i++) + vis[i]=false; + stack order; + list::iterator it; + for(i=1;i<=v;i++) + { + if(vis[i]==false) + //fill stack in order of finish times using DFS + order = fillstack(adjlist,i,order,vis); + } + /*while(!order.empty()) + { + cout<>v>>e; + vector < list > adjlist(v+1); + for(i=0;i>v1>>v2; + adjlist[v1].push_back(v2); + adjlist[v2].push_back(v1); //for undirected graph + } + + int ans=kosaraju(adjlist,v); + cout< +using namespace std; + +const int MAX = 1e4 + 5; +int id[MAX] ; + + +int root(int x) +{ + while(id[x] != x) + { + id[x] = id[id[x]]; + x = id[x]; + } + return x; +} + +int main() +{ + int nodes, edges, x, y, weight; + int cost, minimumCost=0 ; + pair > Graph[MAX]; + + // initially all elements are in different sets + for(int i = 0;i < MAX;++i) + id[i] = i; + + + // input number of nodes and edges in graph + cin >> nodes >> edges; + for(int i = 0;i < edges;++i) + { + cin >> x >> y >> weight; + Graph[i] = make_pair(weight, make_pair(x, y)); + } + + // Sort the edges in the ascending order of weights + sort(Graph, Graph + edges); + + // find weight of minimum spanning tree + for(int i = 0;i < edges;++i) + { + // Selecting edges one by one in increasing order from the beginning + x = Graph[i].second.first; + y = Graph[i].second.second; + cost = Graph[i].first; + // Check if the selected edge is creating a cycle or not + if(root(x) != root(y)) + { + minimumCost += cost; + + // join sets of both elements + id[root(x)] = id[root(y)]; + } + } + + + cout << "Cost of minimum spanning tree is : " + << minimumCost << endl; + return 0; +} diff --git a/algorithms/graphs/kruskals_017.cpp b/algorithms/graphs/kruskals_017.cpp new file mode 100644 index 00000000..333b6f97 --- /dev/null +++ b/algorithms/graphs/kruskals_017.cpp @@ -0,0 +1,156 @@ +#include +using namespace std; + +// Creating shortcut for an integer pair +typedef pair iPair; + +// Structure to represent a graph +struct Graph +{ + int V, E; + vector< pair > edges; + + // Constructor + Graph(int V, int E) + { + this->V = V; + this->E = E; + } + + // Utility function to add an edge + void addEdge(int u, int v, int w) + { + edges.push_back({w, {u, v}}); + } + + // Function to find MST using Kruskal's + // MST algorithm + int kruskalMST(); +}; + +// To represent Disjoint Sets +struct DisjointSets +{ + int *parent, *rnk; + int n; + + // Constructor. + DisjointSets(int n) + { + // Allocate memory + this->n = n; + parent = new int[n+1]; + rnk = new int[n+1]; + + // Initially, all vertices are in + // different sets and have rank 0. + for (int i = 0; i <= n; i++) + { + rnk[i] = 0; + + //every element is parent of itself + parent[i] = i; + } + } + + // Find the parent of a node 'u' + // Path Compression + int find(int u) + { + /* Make the parent of the nodes in the path + from u--> parent[u] point to parent[u] */ + if (u != parent[u]) + parent[u] = find(parent[u]); + return parent[u]; + } + + // Union by rank + void merge(int x, int y) + { + x = find(x), y = find(y); + + /* Make tree with smaller height + a subtree of the other tree */ + if (rnk[x] > rnk[y]) + parent[y] = x; + else // If rnk[x] <= rnk[y] + parent[x] = y; + + if (rnk[x] == rnk[y]) + rnk[y]++; + } +}; + + /* Functions returns weight of the MST*/ + +int Graph::kruskalMST() +{ + int mst_wt = 0; // Initialize result + + // Sort edges in increasing order on basis of cost + sort(edges.begin(), edges.end()); + + // Create disjoint sets + DisjointSets ds(V); + + // Iterate through all sorted edges + vector< pair >::iterator it; + for (it=edges.begin(); it!=edges.end(); it++) + { + int u = it->second.first; + int v = it->second.second; + + int set_u = ds.find(u); + int set_v = ds.find(v); + + // Check if the selected edge is creating + // a cycle or not (Cycle is created if u + // and v belong to same set) + if (set_u != set_v) + { + // Current edge will be in the MST + // so print it + cout << u << " - " << v << endl; + + // Update MST weight + mst_wt += it->first; + + // Merge two sets + ds.merge(set_u, set_v); + } + } + + return mst_wt; +} + +// Driver program to test above functions +int main() +{ + /* Let us create above shown weighted + and unidrected graph */ + int V = 9, E = 14; + Graph g(V, E); + + // making above shown graph + g.addEdge(0, 1, 4); + g.addEdge(0, 7, 8); + g.addEdge(1, 2, 8); + g.addEdge(1, 7, 11); + g.addEdge(2, 3, 7); + g.addEdge(2, 8, 2); + g.addEdge(2, 5, 4); + g.addEdge(3, 4, 9); + g.addEdge(3, 5, 14); + g.addEdge(4, 5, 10); + g.addEdge(5, 6, 2); + g.addEdge(6, 7, 1); + g.addEdge(6, 8, 6); + g.addEdge(7, 8, 7); + + cout << "Edges of MST are \n"; + int mst_wt = g.kruskalMST(); + + cout << "\nWeight of MST is " << mst_wt; + + return 0; +} diff --git a/algorithms/graphs/kth-ancestor-of-a-tree-node.cpp b/algorithms/graphs/kth-ancestor-of-a-tree-node.cpp new file mode 100644 index 00000000..6123970e --- /dev/null +++ b/algorithms/graphs/kth-ancestor-of-a-tree-node.cpp @@ -0,0 +1,52 @@ +//Kth Ancestor of a treenode using Binary Lifting. If kth ancestor does not exist, return -1. Implemented in C++17 +// author : github.com/yadavnaman +#include +using namespace std; + +class TreeAncestor { + +public: + vector< vector >dp; // dp[i][node] : node's 2^i parent + int n; + TreeAncestor(int m, vector& parent) { + n = m; + dp.resize(20,vector (m,-1)); + for(int node = 0 ; node < parent.size(); ++node){ + dp[0][node] = parent[node]; + } + // 2^i parent + for(int i = 1; i< 20; ++i) { + for(int node = 0 ; node < parent.size(); ++node) { + int node_par = dp[i-1][node]; + if(node_par != -1){ + dp[i][node] = dp[i-1][node_par]; + } + } + } + + } + + int getKthAncestor(int node, int k) { + for(int i = 0; i < 20; ++i) { + if(k & (1<> m >> k; + vector par(m); + for(int i = 0; i < m; ++i){ + cin>>par[i]; + } + cin >> node; + TreeAncestor* obj = new TreeAncestor(m,par); + cout << obj->getKthAncestor(node,k) <<"\n"; +} \ No newline at end of file diff --git a/algorithms/graphs/prims_adjacency_list.cpp b/algorithms/graphs/prims_adjacency_list.cpp new file mode 100644 index 00000000..6c126d5f --- /dev/null +++ b/algorithms/graphs/prims_adjacency_list.cpp @@ -0,0 +1,108 @@ +// +// The following is an implementation of Prim's algorithm +// using adjacency list representation of a graph. The data structure +// min heap is used for this. There are, again, two implementations +// in this, the min heap code can be written differently in a class, or +// the priority_queue present in STL can be used. Here, it's the +// latter. +// Now, a priority_queue is essentially a max heap, but can be used +// as given below to form a min heap. The loop statements execute +// v+e times, in addition to log(v) time for adding to priority_queue. +// Overall, O(v+e)*O(log(v)) = O((e+v)*log(v)) +// e = O(v^2) for dense graphs, because e <= v*(v-1)/2 for any connected graph. +// And e = O(v), or, v = O(e) for sparsely connected graphs. +// Hence, O((e+v)*log(v)) = O(e*log(v)). +// The pop() and top() operations take O(log(v)) and O(1) time +// respectively. +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/graphs/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Pritam Negi +// Github: @pritamnegi +// + +#include +#define INF INT_MAX + +using namespace std; + +int main(){ + + cout << "Enter number of vertices of the graph" << endl; + int v; + cin >> v; + + vector > adj[v]; + int i, j; //Iterators + + cout << "Enter number of edges of the graph" << endl; + int e; + cin>>e; + + cout << "Enter the vertices and their edge weights in the following format :" << endl; + cout << "Vertex1 Vertex2 Weight" << endl; + cout << "PS : First vertex should be 0." << endl; + + for (i = 0; i < e; i ++){ + int v1,v2,w; + cin >> v1 >> v2 >> w; + adj[v1].push_back(make_pair(w,v2)); + adj[v2].push_back(make_pair(w,v1)); + } + + int mst[v]; + //Array to store MST + int keys[v]; + //Key values of every edge + bool included[v]; + //The corresponding vertex has already been included if true + + for (i = 0; i < v; i ++){ + mst[i] = -1; + keys[i] = INF; + //Set all key values to infinity + included[i] = false; + //None of the vertices have been included yet + } + + int selected = 0; + + priority_queue< pair , vector > , greater< pair > > Q; + //Priority queue as a minHeap + pair p; + //This is used to traverse through the vertices + + mst[0] = 0; + Q.push(make_pair(0,0)); + //To start MST with node 0, the root node + + while(!Q.empty()){ + + p = Q.top(); + selected = p.second; + //Edge with minimum weight is selected + Q.pop(); + + for(int i = 0;i < adj[selected].size(); i++ ){ + int next = adj[selected][i].second; + //This variable stores index of the adjacent vertices to 'selected' + int weight = adj[selected][i].first; + + if (!included[next] && keys[next] > weight){ + keys[next] = weight; + Q.push(adj[selected][i]); + mst[next] = selected; + } + } + } + + cout << "Minimum spanning tree has been generated." << endl; + + for(i = 1; i < v; i++){ + cout<< mst[i] <<" "; + } + return 0; +} diff --git a/algorithms/graphs/suffix_tree_ukkonen.cpp b/algorithms/graphs/suffix_tree_ukkonen.cpp new file mode 100644 index 00000000..d53679f3 --- /dev/null +++ b/algorithms/graphs/suffix_tree_ukkonen.cpp @@ -0,0 +1,82 @@ +#include + +using namespace std; + +#define fpos adla +const int inf = 1e9; +const int maxn = 1e4; +char s[maxn]; +map to[maxn]; +int len[maxn], fpos[maxn], link[maxn]; +int node, pos; +int sz = 1, n = 0; + +int make_node(int _pos, int _len) +{ + fpos[sz] = _pos; + len [sz] = _len; + return sz++; +} + +void go_edge() +{ + while(pos > len[to[node][s[n - pos]]]) + { + node = to[node][s[n - pos]]; + pos -= len[node]; + } +} + +void add_letter(int c) +{ + s[n++] = c; + pos++; + int last = 0; + while(pos > 0) + { + go_edge(); + int edge = s[n - pos]; + int &v = to[node][edge]; + int t = s[fpos[v] + pos - 1]; + if(v == 0) + { + v = make_node(n - pos, inf); + link[last] = node; + last = 0; + } + else if(t == c) + { + link[last] = node; + return; + } + else + { + int u = make_node(fpos[v], pos - 1); + to[u][c] = make_node(n - 1, inf); + to[u][t] = v; + fpos[v] += pos - 1; + len [v] -= pos - 1; + v = u; + link[last] = u; + last = u; + } + if(node == 0) + pos--; + else + node = link[node]; + } +} + +int main() +{ + len[0] = inf; + string s; + cin >> s; + int ans = 0; + for(int i = 0; i < s.size(); i++) + add_letter(s[i]); + for(int i = 1; i < sz; i++) + ans += min((int)s.size() - fpos[i], len[i]); + cout << ans << "\n"; +} + diff --git a/algorithms/graphs/topological sort.(matrix).cpp b/algorithms/graphs/topological sort.(matrix).cpp new file mode 100644 index 00000000..35b27cdd --- /dev/null +++ b/algorithms/graphs/topological sort.(matrix).cpp @@ -0,0 +1,61 @@ +#include +using namespace std; +class graph +{ + int v,adj[100][100],st[100],top; +public: + void read() + { + int i,j; + + cout<<"vertex"<>v; + for(i=0;i>adj[i][j]; + // adj[j][i]=adj[i][j]; + } + } + } + void topo(int u,int vis[]) + { + vis[u]=1; + int i; + for(i=0;i=0) + { + cout< +using namespace std; +void sortit(vector > adjlist,int i, stack sorted,int vis[]) +{ + vis[i]= 1; + list :: iterator it; + + for(it= adjlist[i].begin();it!=adjlist[i].end();it++) + { + if(vis[*it]==0) + { + sortit(adjlist,*it,sorted,vis); + } + + } + cout< > adjlist,int v) +{ + int i,vis[v]; + for(i=1;i<=v;i++) + vis[i]=0; + stack sorted; + for(i=1;i<=v;i++) + { + if(vis[i]==0) + sortit(adjlist,i,sorted,vis); + } + while(!sorted.empty()) + { + cout<< sorted.top(); + sorted.pop(); + } +} +int main() +{ + int v,e,v1,v2; + cin>>v>>e; + vector > adjlist(v+1); + for(int i=1;i<=v;i++) + { + cin>>v1>>v2; + adjlist[v1].push_back(v2); + } + topsort(adjlist,v); +} diff --git a/algorithms/graphs/topological_sort.cpp b/algorithms/graphs/topological_sort.cpp new file mode 100644 index 00000000..9038e90b --- /dev/null +++ b/algorithms/graphs/topological_sort.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; +stack pile; +vector adj[1000]; +void dfs(int cur,int vis[]) +{ + int i=0; + for(i=0;i>n>>e; + for(i=0;i>u>>v; + adj[u].push_back(v); + } + for(i=1;i<=n;i++) + { + if(vis[i]==0) + dfs(i,vis); + } + while(!pile.empty()) + { + cout< +using namespace std; +vector adj[10001]; +priority_queue,greater >q; +queuea; +bool visited[10001]; +int indegree[10001]; +int main() +{ + int n,m,u,v; + scanf("%d%d",&n,&m); + while(m--) + { + scanf("%d%d",&u,&v); + adj[u].push_back(v); + indegree[v]++; + } + for(int i=1;i<=n;i++) + if(!indegree[i]) + q.push(i); + int k=0; + while(!q.empty()) + { + int u=q.top(); + q.pop(); + a.push(u); + for(auto it:adj[u]) + { + indegree[it]--; + if(!indegree[it]) + q.push(it); + } + ++k; + } + if(k!=n) + printf("Sandro fails."); + else + { + while(!a.empty()) + { + printf("%d ",a.front()); + a.pop(); + } + } +} diff --git a/algorithms/greedy/minimumCoins.cpp b/algorithms/greedy/minimumCoins.cpp new file mode 100644 index 00000000..e231d251 --- /dev/null +++ b/algorithms/greedy/minimumCoins.cpp @@ -0,0 +1,41 @@ +// Given a value V and the list of available denomination of money, +// find minimum number of coins and/or notes needed to make the change. + +#include +using namespace std; + +// All denominations of Indian Currency +int deno[] = { 1, 2, 5, 10, 20, + 50, 100, 500, 1000 }; +int n = sizeof(deno) / sizeof(deno[0]); + +vector calculate(int V) +{ + sort(deno, deno + n); + vector ans; + + for (int i = n - 1; i >= 0; i--) { + + while (V >= deno[i]) { + V -= deno[i]; + ans.push_back(deno[i]); + } + } + return ans; + //for (int i = 0; i < ans.size(); i++) + //cout << ans[i] << " "; +} + +int main() +{ + int n; + cout<<"Enter the monitory value: "; + cin>>n; + cout << "Following is minimal number of change for " << n + << ": "; + vector ans = calculate(n); + for(auto i: ans) + cout< +using namespace std; + +int calculate(int a[], int n) +{ + if (n == 1) + return a[0]; + + int max_neg = INT_MIN; + int min_pos = INT_MAX; + int count_neg = 0, count_zero = 0; + int prod = 1; + for (int i = 0; i < n; i++) { + + + if (a[i] == 0) { + count_zero++; + continue; + } + + if (a[i] < 0) { + count_neg++; + max_neg = max(max_neg, a[i]); + } + + if (a[i] > 0) + min_pos = min(min_pos, a[i]); + + prod = prod * a[i]; + } + + if (count_zero == n || + (count_neg == 0 && count_zero > 0)) + return 0; + + if (count_neg == 0) + return min_pos; + + if (!(count_neg & 1) && count_neg != 0) { + prod = prod / max_neg; + } + + return prod; +} + +int main() +{ + int n; + cout<<"Enter size of array: "; + cin>>n; + int a[n]; + cout<<"\nEnter array elements: "; + for(int i=0;i>a[i]; + cout << "\nAnswer: "< + +using namespace std; + +void swap(int* a, int* b){ + int t = *a; + *a = *b; + *b = t; +} + +void swapc(char* a, char* b){ + char t = *a; + *a = *b; + *b = t; +} + +void heapify(int start[], int finish[], char status[], int n, int i){ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if (l < n && finish[l] > finish[largest]) + largest = l; + + if (r < n && finish[r] > finish[largest]) + largest = r; + + if (largest != i){ + swap(&finish[i], &finish[largest]); + swap(&start[i], &start[largest]); + swapc(&status[i], &status[largest]); + heapify(start, finish, status, n, largest); + } +} + +void sort(int start[], int finish[], char status[], int n){ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(start, finish, status, n, i); + + for (int i=n-1; i>=0; i--){ + swap(&finish[0], &finish[i]); + swap(&start[0], &start[i]); + swapc(&status[0], &status[i]); + heapify(start, finish, status, i, 0); + } +} + +int maxFinishTime(int finish[], int n){ + int max = 0; + for(int i=0;i max) + max = finish[i]; + return max; +} + +int status_check(int s[], int f[], char st[], int n) { + + //find the maximum finish time among all process + int N = maxFinishTime(f, n) + 1; + + //count stores whether status_check() is invoked, if yes count[i] = 1, else count[i] = 0 + int count[N]; + + //initialize count to 0 initially + for(int i=0;i=0;k--){ + if(count[k] == 1){ + lastStatusCheck = k; + break; + } + } + + if(pid[i] == 0){ + count[f[i]] = 1; + timeF = f[i]; + pid[i] = 1; + pid[j] = 1; + } + + else if(pid[j] == 0 && timeF != lastStatusCheck){ + count[f[j]] = 1; + timeF = f[j]; + pid[j] = 1; + } + } + + //overlap + else if(f[i] >= s[j] && s[i] != s[j]){ + //if status is S i.e. 'Sensitive' apply status_check() + if(timeF < f[i]){ + count[f[i]] = 1; + timeF = f[j]; + pid[i] = 1; + pid[j] = 1; + } + } + + //no overlap + else{ + if(timeF < f[i] && s[i] != s[j]){ + count[f[i]] = 1; + timeF = f[i]; + pid[i] = 1; + pid[j] = 1; + } + } + i++; + } + cout<>n; + int start[n]; + int finish[n]; + char status[n]; + for(int i=0;i>start[i] >> finish[i] >> status[i]; + } + + //sort in non-decreasing order of finish time + sort(start, finish, status, n); + + //check for conflict + int check = status_check(start, finish, status, n); + + cout<<"Number of times status_check() is invoked is %d"< + +using namespace std; +using namespace cv; + +int main() +{ + Mat RGBimage=("cat.jpg"); + Mat Greyimage(RGBimage.rows,RGBimage.cols,CV_8UC1); + for(int i=0;i(i,j)=(RGBimage.at(i,j)[0]+RGBimage.at(i,j)[1]+RGBimage.at(i,j)[2])/3; + } + } + imshow("RGBimage",RGBimage); + imshow("Greyimage",Greyimage); + waitKey(0); + return 0; +} diff --git a/algorithms/image-processing/blurImage.cpp b/algorithms/image-processing/blurImage.cpp new file mode 100644 index 00000000..5bf60524 --- /dev/null +++ b/algorithms/image-processing/blurImage.cpp @@ -0,0 +1,31 @@ +// Using OpenCV to blur an image. + +#include +#include +#include +#include +#include + +using namespace cv; +using namespace std; + +int main() +{ + Mat image = imread("jeep.jpg", CV_LOAD_IMAGE_UNCHANGED); + + // Check for no data + if (! image.data ) + { + cout << "Could not open or find the image.\n"; + return -1; // unsuccessful + } + + blur(image,image,Size(10,10)); + + namedWindow( "jeep", CV_WINDOW_AUTOSIZE ); + imshow( "jeep", image ); + + waitKey(0); + + return 0; +} diff --git a/algorithms/image-processing/createColoredImage.cpp b/algorithms/image-processing/createColoredImage.cpp new file mode 100644 index 00000000..25a33a2e --- /dev/null +++ b/algorithms/image-processing/createColoredImage.cpp @@ -0,0 +1,48 @@ +// Create a coloured image in C++ using OpenCV. + +#include "opencv2/highgui/highgui.hpp" +using namespace cv; +using namespace std; + +int main() +{ + // To create an image + // CV_8UC3 depicts : (3 channels,8 bit image depth + // Height = 500 pixels, Width = 1000 pixels + // (0, 0, 100) assigned for Blue, Green and Red + // plane respectively. + // So the image will appear red as the red + // component is set to 100. + Mat img(500, 1000, CV_8UC3, Scalar(0,0, 100)); + + // check whether the image is loaded or not + if (img.empty()) + { + cout << "\n Image not created. You" + " have done something wrong. \n"; + return -1; // Unsuccessful. + } + + // first argument: name of the window + // second argument: flag- types: + // WINDOW_NORMAL If this is set, the user can + // resize the window. + // WINDOW_AUTOSIZE If this is set, the window size + // is automatically adjusted to fit + // the displayed image, and you cannot + // change the window size manually. + // WINDOW_OPENGL If this is set, the window will be + // created with OpenGL support. + namedWindow("A_good_name", CV_WINDOW_AUTOSIZE); + + // first argument: name of the window + // second argument: image to be shown(Mat object) + imshow("A_good_name", img); + + waitKey(0); //wait infinite time for a keypress + + // destroy the window with the name, "MyWindow" + destroyWindow("A_good_name"); + + return 0; +} diff --git a/algorithms/image-processing/createGaussianFilter.cpp b/algorithms/image-processing/createGaussianFilter.cpp new file mode 100644 index 00000000..0e7ab6f9 --- /dev/null +++ b/algorithms/image-processing/createGaussianFilter.cpp @@ -0,0 +1,43 @@ +// Generate Gaussian filter + +#include +#include +#include +using namespace std; + +// Function to create Gaussian filter +void FilterCreation(double GKernel[][5]) +{ + // intialising standard deviation to 1.0 + double sigma = 1.0; + double r, s = 2.0 * sigma * sigma; + + // sum is for normalization + double sum = 0.0; + + // generating 5x5 kernel + for (int x = -2; x <= 2; x++) { + for (int y = -2; y <= 2; y++) { + r = sqrt(x * x + y * y); + GKernel[x + 2][y + 2] = (exp(-(r * r) / s)) / (M_PI * s); + sum += GKernel[x + 2][y + 2]; + } + } + + // normalising the Kernel + for (int i = 0; i < 5; ++i) + for (int j = 0; j < 5; ++j) + GKernel[i][j] /= sum; +} + +int main() +{ + double GKernel[5][5]; + FilterCreation(GKernel); + + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 5; ++j) + cout << GKernel[i][j] << "\t"; + cout << endl; + } +} diff --git a/algorithms/math/AverageCalc.cpp b/algorithms/math/AverageCalc.cpp new file mode 100644 index 00000000..c079f729 --- /dev/null +++ b/algorithms/math/AverageCalc.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int main() +{ + float a,b=0,c=0; + //This program will count the average of all the data, type "0" to show the average. + while(a!=0) + { + b=b+1; + cout << "Data " << b << "= "; + cin >> a; + c=c+a; + } + + float average=c/(b-1); + cout << " \n"; + cout << "Average= " << average << endl; + + system("pause"); + return 0; +} \ No newline at end of file diff --git a/algorithms/math/BITOBYT_OCT_LONG.cpp b/algorithms/math/BITOBYT_OCT_LONG.cpp new file mode 100644 index 00000000..8def5ee9 --- /dev/null +++ b/algorithms/math/BITOBYT_OCT_LONG.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +int main(){ +int t; +cin>>t; +while(t--){ +int n; +cin>>n; +int r = n%26; +int q = n/26; +if(r>=1&&r<=2) +cout<<(long long)pow(2,q)<<"\t"<<0<<"\t"<<0<<"\n"; +else if(r>2&&r<=10) +cout<<0<<"\t"<<(long long)pow(2,q)<<"\t"<<0<<"\n"; +else if(r>10&&r<=25) +cout<<0<<"\t"<<0<<"\t"<<(long long)pow(2,q)<<"\n"; +else if(r==0) +cout<<0<<"\t"<<0<<"\t"<<(long long)pow(2,q-1)<<"\n"; +} +return 0; +} diff --git a/algorithms/math/Binomial Function.cpp b/algorithms/math/Binomial Function.cpp new file mode 100644 index 00000000..3a042efd --- /dev/null +++ b/algorithms/math/Binomial Function.cpp @@ -0,0 +1,19 @@ +//Funcion factorial +unsigned long int factorial (unsigned long int valor) +{ + if (valor<=1) + return valor=1; + else + return valor=valor*factorial(valor-1); +} + +/*///////////////////////////////////////////////////////////////////////////////////////*/ +/*///////////////////////////////////////////////////////////////////////////////////////*/ + +//Funcion binomial(requiere la funcion factorial) +float numero_binomio (unsigned long int arriba,unsigned long int abajo) +{ + float respuesta; + respuesta = factorial(arriba) / (factorial(abajo) * factorial(arriba-abajo)); + return respuesta; +} diff --git a/algorithms/math/CHSERVE_OCT_LONG.cpp b/algorithms/math/CHSERVE_OCT_LONG.cpp new file mode 100644 index 00000000..3872442a --- /dev/null +++ b/algorithms/math/CHSERVE_OCT_LONG.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; +int main(){ +int t; +cin>>t; +while(t--){ +long long p1,p2,k; +cin>>p1>>p2>>k; +long long r = (p1+p2)%(2*k); +if(r>=0&&r=t; l--) + { + m[t][l]=m[t][l]/m[t][t]; + } + + //Divisores + for (k=0; k +#include +using namespace std; +vectorget_factors(vector&primes,int n) +{ + vectorans; + ans.clear(); + for(int i=0;i*i<=n;i++) + { + if(n%primes[i]==0) + { + ans.push_back(primes[i]); + while(n%primes[i]==0) + { + n=n/primes[i]; + } + + } + } + if(n!=1) + { + ans.push_back(n); + } + return ans; +} +vectorget_prime(vector&prime,int n) +{ + for(int i=3;i<=1000;i+=2) + { + prime[i]=1; + } + //mark all the even number as non prime + for(int i=3;i*i<=1000;i+=2) + { + if(prime[i]==1) + { + for(int j=i*i;j<=1000;j+=i) + { + prime[j]=0; + } + } + } + prime[0]=prime[1]=0; + prime[2]=1; + vectorfectors; + for(int i=2;i<=1000;i++) + { + if(prime[i]==1) + { + fectors.push_back(i); + } + } +return fectors; + +} +int32_t main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + //first task to genrate prime fectors and store it + vectorp(1000,0); + //now we have all prime number till n + int n; + cin>>n; + //enter n (the number you want to get prime fector) + vectorprimes=get_prime(p,n); + vectorans=get_factors(primes,n); + cout<<"Prime Factors are :"; + for(auto i:ans) + { + cout< +using namespace std; + +int checkPrimeNumber(int); + +int main() +{ + int n; + + cout << "Enter a positive integer: "; + cin >> n; + + if(checkPrimeNumber(n) == 0) + cout << n << " is a prime number."; + else + cout << n << " is not a prime number."; + return 0; +} +int checkPrimeNumber(int n) +{ + bool flag = false; + + for(int i = 2; i <= n/2; ++i) + { + if(n%i == 0) + { + flag = true; + break; + } + } + return flag; +} \ No newline at end of file diff --git a/algorithms/math/all_factors_of_a_numbe_r.cpp b/algorithms/math/all_factors_of_a_numbe_r.cpp new file mode 100644 index 00000000..c55a7e9b --- /dev/null +++ b/algorithms/math/all_factors_of_a_numbe_r.cpp @@ -0,0 +1,35 @@ +// +// All Factors of a number +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: divyanshu132 +// Github: @divyanshu132 +// +#include +#include +using namespace std; + +int main() +{ + int n=12; + + while(n%2==0) + { + cout<<"2 "; + n=n/2; + } + for(int i=3;i1) + cout< +#include +using namespace std; + + +string check_armstrong(long long number){ + long long sum_of_digits = 0; + long long value = number; + while(number){ + int unit = number % 10; + sum_of_digits += (unit*unit*unit); + number = number / 10; + } + return value == sum_of_digits?"\tIt is Armstrong Number":"\tNot A Armstrong Number"; +} + +int main(){ + cout< +long long long long int bin(long long long long int a, long long long long int b, long long long long int c); +using namespace std; +long long int main(void) +{ + long long long long int a, n; + long long long long int c = 1000000007, d; + scanf("%lld %lld", &a, &n); + d = bin(a, n, c); + prlong long intf("%lld", d); +} +long long long long int bin(long long long long int a, long long long long int b, long long long long int c) +{ + if (b == 0) + return 1; + long long long long int res = (long long long long int)pow(bin(a, b / 2, c), 2) % c; + if (b % 2) + return ((a % c) * res * res) % c; + else + return res * res; +} \ No newline at end of file diff --git a/algorithms/math/binfib.cpp b/algorithms/math/binfib.cpp new file mode 100644 index 00000000..14879996 --- /dev/null +++ b/algorithms/math/binfib.cpp @@ -0,0 +1,46 @@ +#include +void bin(long long int arr[][2],long long int brr[][2], long long int n); +void mul(long long int arr1[][2],long long int arr2[][2],long long int brr[][2]); +using namespace std; +int main(void) +{ + long long int b; + long long int mat[2][2]={{0,1},{1,1}},brr[2][2]; + scanf("%lld", &b); + bin(mat,brr,b); + long long int res=brr[1][0]; + printf("%lld\n", res); +} + +void bin(long long int arr[][2],long long int brr[][2],long long int b){ + long long int id[2][2]={{0,1},{1,1}}; + if(b==0){ + brr[0][0]=1; + brr[0][1]=0; + brr[1][0]=0; + brr[1][1]=1; + return; + } + bin(arr,brr,b/2); + mul(brr,brr,brr); + if(b%2) mul(id,brr,brr); +} + +void mul(long long int arr1[][2],long long int arr2[][2],long long int brr[][2]){ + long long int sum=0; + long long int trr[2][2]; + for(long long int i=0;i<2;i++){ + for(long long int j=0;j<2;j++){ + sum=0; + for(long long int k=0;k<2;k++){ + sum+=(arr1[i][k]*arr2[k][j]); + } + trr[i][j]=sum; + } + } + for(long long int i=0;i<2;i++){ + for(long long int j=0;j<2;j++){ + brr[i][j]=trr[i][j]; + } + } +} \ No newline at end of file diff --git a/algorithms/math/bshuffll.cpp b/algorithms/math/bshuffll.cpp new file mode 100644 index 00000000..2de72867 --- /dev/null +++ b/algorithms/math/bshuffll.cpp @@ -0,0 +1,41 @@ +// +// Bshuffll Implementation +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: shashank3395 +// Github: @shashank3395 +// +#include +#include + +using namespace std; + +int main() +{ + int n; + cin>>n; + if(n==1) + { cout<<1<<"\n"<<1;} + else if(n%2==0) + { + for(int i=1;i<=n;i++) + cout<=1;i--) + cout<=1;i--) + cout< +using namespace std; + + +int main() +{ + int n; + cin >> n; + + long long cat[100000]; + cat[0] = 1; + cout << cat[0]; + + for (int i = 1; i <= n; i++) + { + cat[i] = 2 * (4 * i + 1) * cat[i - 1] / (i + 2); + cout << cat[i] << endl; + } +} diff --git a/algorithms/math/catalan_number_recursive.cpp b/algorithms/math/catalan_number_recursive.cpp new file mode 100644 index 00000000..72bac476 --- /dev/null +++ b/algorithms/math/catalan_number_recursive.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; + + +int main() +{ + int n; + cin >> n; + + long long cat[100000]; + cat[0] = 1; + cout << cat[0]; + + for (int i = 1; i <= n; i++) + { + cat[i] = 0; + for (int j = 0; j < i; j++) + cat[i] += cat[j] * cat[i - j - 1]; + cout << cat[i] << endl; + } +} diff --git a/algorithms/math/chefres.cpp b/algorithms/math/chefres.cpp new file mode 100644 index 00000000..3000d9ec --- /dev/null +++ b/algorithms/math/chefres.cpp @@ -0,0 +1,48 @@ +#include +#include + +using namespace std; + +int main() +{ + int t,n,m; + cin>>t; + while(t--) + { + cin>>n>>m; + int a[n],b[n],c[n]={0},f; + for(int i=0;i>a[i]>>b[i]; + } + for(int j=0;j>f; + int flag1=0; + for(int k=0;k=a[k]&&f=0) + {cout< +using namespace std; + +void collatz(int n) { + while (n > 1) { + cout << n << " "; + if (n % 2 == 0) { + n = n / 2; + } else { + n = (3 * n) + 1; + } + } + cout << n << endl; +} +int main() { + int n; + cout << "Enter an integer n to compute the Collatz sequence: "; + cin >> n; + collatz(n); + return 0; +} diff --git a/algorithms/math/euclids_gcd.cpp b/algorithms/math/euclids_gcd.cpp new file mode 100644 index 00000000..850dbb5a --- /dev/null +++ b/algorithms/math/euclids_gcd.cpp @@ -0,0 +1,31 @@ +// +// C++ program to demonstrate Basic Euclidean Algorithm +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/math +// https://github.com/allalgorithms/cpp +// +// Contributed by: Bharat Reddy +// Github: @Bharat-Reddy +// +#include +using namespace std; + + +int gcd(int a, int b) +{ + if (a == 0) + return b; + return gcd(b % a, a); +} + +int main() +{ + int a,b; + cout<<"Enter 2 numbers : "; + cin>>a>>b; + int g_c_d = gcd(a,b); + cout<<"GCD is "< + +using namespace std; + +int phi(int n) //less efficient but easy to understand +{ + float result=n; + for(int f=2;f*f<=n;f++) + if(n%f==0) + { + while(n%f==0) + n/=f; + result*=(1.0-(1.0/(float)f)); + } + if(n>1) + result*=(1.0-(1.0/(float)n)); + return int(result); +} + +int phi2(int n) //more efficient because of reduced number of multiplications +{ + int result=n; + for(int f=2;f*f<=n;f++) + if(n%f==0) + { + while(n%f==0) + n/=f; + result-=result/f; + } + if(n>1) + result-=result/n; + return result; +} + +int main() +{ + cout<<"\nEnter a number : "; + int n; + cin>>n; + cout<<"\nCount of numbers from [1,n] that are relatively prime to n are : "< + +using namespace std; + +int gcd(int a, int b) +{ + return (b > 0 ? gcd(b, a%b) : a); +} + +unsigned int phi(unsigned int n) +{ + unsigned int result = 1; + for (int i = 2; i < n; ++i) + { + if (gcd(i, n) == 1) + { + result++; + } + } + + return result; +} + +int main() +{ + int n; + cin >> n; + assert(n <= 1000000); // Assertion to ensure execution time is reasonable ( < 1second) + + cout << "Value of Euler's totient function for n is " << phi(n) << endl; + + return 0; +} diff --git a/algorithms/math/eveodd.cpp b/algorithms/math/eveodd.cpp new file mode 100644 index 00000000..75513e2b --- /dev/null +++ b/algorithms/math/eveodd.cpp @@ -0,0 +1,12 @@ +#include +#include +using namespace std; +int main(){ +int n; +cout<<"Enter a number: "<>n; +if(n%2==0) +cout<<"number is even"< +using namespace std; + +int factorial(int n) { + if (n <= 0) { + return 1; + } else { + return n * factorial(n - 1); + } +} + +int main() { + int n; + cout << "Enter an integer n to compute its factorial: "; + cin >> n; + int r = factorial(n); + cout << n << "! = " << r << endl; + return 0; +} diff --git a/algorithms/math/factorial_loop.cpp b/algorithms/math/factorial_loop.cpp new file mode 100644 index 00000000..5ed5bf6d --- /dev/null +++ b/algorithms/math/factorial_loop.cpp @@ -0,0 +1,15 @@ +/* + @author Roman Korostenskyi + @date 08.10.2018 + + Simple factorial algorithm based on loop +*/ +int factorial_loop(int n) { + int output = 1; + + for (int i = n; i >= 1; i--) { + output *= i; + } + + return output; +} \ No newline at end of file diff --git a/algorithms/math/fibonacci.cpp b/algorithms/math/fibonacci.cpp new file mode 100644 index 00000000..f512abcd --- /dev/null +++ b/algorithms/math/fibonacci.cpp @@ -0,0 +1,32 @@ +#include //to get the input and print the output +#include + +using std::cin; +using std::cout; + +//returns fibonacci number for specified position +int64_t getFibonnaci(unsigned int input){ + //base case + if (input <= 1){ + return input; + } + + //recursively calls getFibonnaci function to get the previous fibonacci numbers until base case is reached + //all the previous fibonacci numbers are then added + //and returns the fibonacci number for current position + return getFibonnaci(input-1) + getFibonnaci(input-2); +} + + +int main(){ + int userInput; + + //gets user Input + cout << "Enter a number : \n"; + cin >> userInput; + + cout << "The fibonacci number for the sepcified position is: "; + cout << getFibonnaci(userInput); + + return 0; +} \ No newline at end of file diff --git a/algorithms/math/fibonacci_loop.cpp b/algorithms/math/fibonacci_loop.cpp new file mode 100644 index 00000000..caadc1ae --- /dev/null +++ b/algorithms/math/fibonacci_loop.cpp @@ -0,0 +1,23 @@ +/* + @author Roman Korostenskyi + @date 08.10.2018 + + Simple algorithm based on loop for calculating Fibonacci numbers +*/ + +unsigned long fibonacci(int n) { + if (n <= 1){ + return n; + } + + long previous = 0; + long current = 1; + + for (long i = 2; i <= n; i++){ + long new_current = previous + current; + previous = current; + current = new_current; + } + + return current; +} diff --git a/algorithms/math/gcd_of_array.cpp b/algorithms/math/gcd_of_array.cpp new file mode 100644 index 00000000..8211ebab --- /dev/null +++ b/algorithms/math/gcd_of_array.cpp @@ -0,0 +1,44 @@ +// +// C++ program to find GCD of an array of integers +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/math +// https://github.com/allalgorithms/cpp +// +// Contributed by: Bharat Reddy +// Github: @Bharat-Reddy +// +#include +using namespace std; + +int gcd(int a, int b) +{ + if (a == 0) + return b; + return gcd(b % a, a); +} + + +int findGCD(int arr[], int n) +{ + int result = arr[0]; + for (int i = 1; i < n; i++) + result = gcd(arr[i], result); + + return result; +} + +int main() +{ + int n; + cout<<"Enter size of array : "; + cin>>n; + int a[n]; + cout<<"Enter elements of array"<>a[i]; + cout << findGCD(a, n) << endl; + return 0; +} diff --git a/algorithms/math/hoax_no.cpp b/algorithms/math/hoax_no.cpp new file mode 100644 index 00000000..b37374e9 --- /dev/null +++ b/algorithms/math/hoax_no.cpp @@ -0,0 +1,87 @@ + +// CPP code to check if a number is a hoax +// number or not. +#include +using namespace std; +// Function to find distinct prime factors +// of given number n +vector primeFactors(int n) +{ + vector res; + if (n % 2 == 0) { + while (n % 2 == 0) + n = n / 2; + res.push_back(2); + } + + // n is odd at this point, since it is no + // longer divisible by 2. So we can test + // only for the odd numbers, whether they + // are factors of n + for (int i = 3; i <= sqrt(n); i = i + 2) { + + // Check if i is prime factor + if (n % i == 0) { + while (n % i == 0) + n = n / i; + res.push_back(i); + } + } + + // This condition is to handle the case + // when n is a prime number greater than 2 + if (n > 2) + res.push_back(n); + return res; +} + +// Function to calculate sum of digits of +// distinct prime factors of given number n +// and sum of digits of number n and compare +// the sums obtained +bool isHoax(int n) +{ + // Distinct prime factors of n are being + // stored in vector pf + vector pf = primeFactors(n); + + // If n is a prime number, it cannot be a + // hoax number + if (pf[0] == n) + return false; + + // Finding sum of digits of distinct prime + // factors of the number n + int all_pf_sum = 0; + for (int i = 0; i < pf.size(); i++) { + + // Finding sum of digits in current + // prime factor pf[i]. + int pf_sum; + for (pf_sum = 0; pf[i] > 0; + pf_sum += pf[i] % 10, pf[i] /= 10) + ; + + all_pf_sum += pf_sum; + } + + // Finding sum of digits of number n + int sum_n; + for (sum_n = 0; n > 0; sum_n += n % 10, + n /= 10) + ; + + // Comparing the two calculated sums + return sum_n == all_pf_sum; +} + +// Driver Method +int main() +{ + int n = 84; //Example input. This number is hoax number. + if (isHoax(n)) + cout << "A Hoax Number\n"; + else + cout << "Not a Hoax Number\n"; + return 0; +} diff --git a/algorithms/math/kadence.cpp b/algorithms/math/kadence.cpp new file mode 100644 index 00000000..edf9e85a --- /dev/null +++ b/algorithms/math/kadence.cpp @@ -0,0 +1,28 @@ +#include +#include +using namespace std; + +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 a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} \ No newline at end of file diff --git a/algorithms/math/kthpermutation.cpp b/algorithms/math/kthpermutation.cpp new file mode 100644 index 00000000..6063723a --- /dev/null +++ b/algorithms/math/kthpermutation.cpp @@ -0,0 +1,30 @@ +#include +#include +void shift(int arr[],int p[]); +void bin(int arr[],int res[],int b); +using namespace std; +int main(void){ + char arr[5]={'a','b','c','d','e'},rres[5]; + int p[5]={4,3,2,1,0},res[5],b=4; + bin(p,res,b); + for(int i=0;i<5;i++) rres[i]=arr[res[i]]; + for(int i=0;i<5;i++) printf("%c ",rres[i]); + printf("\n"); +} + +void bin(int arr[],int res[],int b){ + if(b==0) { + for(int i=0;i<5;i++) res[i]=arr[i]; + sort(res,res+5); + return; + } + bin(arr,res,b/2); + shift(res,res); + if(b%2) shift(arr,res); +} + +void shift(int arr[],int p[]){ + int brr[5]; + for(int i=0;i<5;i++) brr[i]=arr[p[i]]; + for(int i=0;i<5;i++) p[i]=brr[i]; +} \ No newline at end of file diff --git a/algorithms/math/lcm_of_array.cpp b/algorithms/math/lcm_of_array.cpp new file mode 100644 index 00000000..face395d --- /dev/null +++ b/algorithms/math/lcm_of_array.cpp @@ -0,0 +1,51 @@ +// +// C++ program to find LCM of n elements +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/math +// https://github.com/allalgorithms/cpp +// +// Contributed by: Bharat Reddy +// Github: @Bharat-Reddy +// + +#include +using namespace std; + +typedef long long int ll; + + +int gcd(int a, int b) +{ + if (b == 0) + return a; + return gcd(b, a % b); +} + +// Returns LCM of array elements +ll findlcm(int arr[], int n) +{ + + ll ans = arr[0]; + + for (int i = 1; i < n; i++) + ans = (((arr[i] * ans)) / + (gcd(arr[i], ans))); + + return ans; +} + +int main() +{ + int n; + cout<<"Enter size of array : "; + cin>>n; + int a[n]; + cout<<"Enter elements of array"<>a[i]; + printf("%lld\n", findlcm(a, n)); + return 0; +} diff --git a/algorithms/math/lucky_numbers.cpp b/algorithms/math/lucky_numbers.cpp new file mode 100644 index 00000000..6b74f47f --- /dev/null +++ b/algorithms/math/lucky_numbers.cpp @@ -0,0 +1,54 @@ +// +// Lucky Numbers Implementation in C++ +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/math +// https://github.com/allalgorithms/cpp +// +// Contributed by: Sathwik Matsa +// Github: @sathwikmatsa +// +#include +#include +#include + +using namespace std; + +// returns a vector of int containing lucky numbers in range [1,n] +vector lucky_numbers(int n){ + + vector seive; + + // store numbers from 1 to n in the vector + for(int i = 1; i<=n; i++){ + seive.push_back(i); + } + + int survivor = 1; + int delete_every = 2; + int index; + while(seive.size() >= delete_every){ + index = delete_every-1; + while(index < seive.size()){ + seive.erase(seive.begin()+index); + index+=(delete_every-1); + } + delete_every = survivor = (*(++find(seive.begin(), seive.end(), survivor))); + } + + return seive; +} + +int main(){ + int n; + cout << "Enter a number: "; + cin>>n; + vector luckyNumbers = lucky_numbers(n); + cout << "lucky numbers up to " << n << ":" <::iterator it = luckyNumbers.begin() ; it < luckyNumbers.end(); it++ ){ + cout << *it << " "; + } + cout< + +#define N 3 +using namespace std; + + +bool isMagicSquare(int mat[][N]) +{ + + int sum = 0; + for (int i = 0; i < N; i++) + sum = sum + mat[i][i]; + + + for (int i = 0; i < N; i++) { + + int rowSum = 0; + for (int j = 0; j < N; j++) + rowSum += mat[i][j]; + + + if (rowSum != sum) + return false; + } + + + for (int i = 0; i < N; i++) { + + int colSum = 0; + for (int j = 0; j < N; j++) + colSum += mat[j][i]; + + + if (sum != colSum) + return false; + } + + return true; +} + + +int main() +{ + int mat[3][N] ,i,k; + + for(i=0; i<3; i++) + { + for(k=0; k<3; k++) + cin>>mat[i][k]; + } + + if (isMagicSquare(mat)) + cout << "Magic Square"; + else + cout << "Not a magic Square"; + + return 0; +} diff --git a/algorithms/math/median_subarray.cpp b/algorithms/math/median_subarray.cpp new file mode 100644 index 00000000..710dc833 --- /dev/null +++ b/algorithms/math/median_subarray.cpp @@ -0,0 +1,134 @@ +// * Description : +// Given an array of integers nums and the length of subarrays +// print all medians of each subarrays +// * Example : +// Array : [5,2,2,7,3,7,9,0,2,3], Subarray length : 5 +// Should print : 3 3 7 7 3 3 +// The first subarray is [5, 2, 2, 7, 3], then the median is 3 +// * Complexity : +// O(N log K) time, O(N) space, N = array.size(), K = subarray.size() + +#include +#include +#include + +using namespace std; + +// Method : +// Firstly initialize two heaps, lower and upper such that +// abs(lower.size() - upper.size()) <= 1 && +// median >= lower[i] && median <= upper[i] +// The median is either the average of the two top values +// or the top value of the greatest heap. +// To add a value add it to the smallest heap and swap tops +// if lower and upper don't follow the first condition. +// To remove a value we find it, remove it and add the top of +// the other heap to the updated heap (sizes are now the same). +// We just remove and then add an item for each index of [0, N-k) +// to simulate a sliding window. +vector medianSubarray(vector& values, int k) { + // We use long long instead of int to avoid overflows + // median >= lower[i] && median <= upper[i] + multiset> lower; + multiset upper; + vector medians; + + // Initialize lower and upper + for (int i = 0; i < k; ++i) { + if (lower.size() <= upper.size()) + lower.insert(values[i]); + else + upper.insert(values[i]); + + // Swap values if heaps aren't balanced + if (!lower.empty() && !upper.empty() && + *lower.begin() > *upper.begin()) { + long long tmp = *lower.begin(); + lower.erase(lower.begin()); + lower.insert(*upper.begin()); + upper.erase(upper.begin()); + upper.insert(tmp); + } + } + +// To get the median inline +#define GET_MEDIAN (lower.size() == upper.size() ? \ + (*lower.begin() + (*upper.begin() - *lower.begin()) * .5) : \ + lower.size() > upper.size() ? *lower.begin() : *upper.begin()) + + medians.push_back(GET_MEDIAN); + + for (int i = 0; i < values.size() - k; ++i) { + // Remove the i item + bool removed = false; + if (!lower.empty() && values[i] <= *lower.begin()) { + // Remove it + auto target = lower.find(values[i]); + if (target != lower.end()) { + lower.erase(target); + removed = true; + + // Insert the top of the other heap to the updated heap + if (!upper.empty()) { + lower.insert(*upper.begin()); + upper.erase(upper.begin()); + } + } + } + + if (!removed) { + // Remove it + upper.erase(upper.find(values[i])); + + // Insert the top of the other heap to the updated heap + if (!lower.empty()) { + upper.insert(*lower.begin()); + lower.erase(lower.begin()); + } + } + + // Add the i + k item + if (lower.size() <= upper.size()) + lower.insert(values[i + k]); + else + upper.insert(values[i + k]); + + // Swap values if heaps aren't balanced + if (!lower.empty() && !upper.empty() && + *lower.begin() > *upper.begin()) { + long long tmp = *lower.begin(); + lower.erase(lower.begin()); + lower.insert(*upper.begin()); + upper.erase(upper.begin()); + upper.insert(tmp); + } + + medians.push_back(GET_MEDIAN); + } + + return medians; +} + +int main() { + vector>> dataset = { + {5, {5,2,2,7,3,7,9,0,2,3}}, + {3, {1,3,-1,-3,5,3,6,7}}, + {1, {1,2}}, + {2, {2147483647,2147483647}}, + }; + + // Should be : + // 3 3 7 7 3 3 + // 1 -1 -1 3 5 6 + // 1 2 + // 2.14748e+09 + for (auto test : dataset) { + auto y = medianSubarray(test.second, test.first); + for (double median : y) + cout << median << " "; + + cout << endl; + } + + return 0; +} diff --git a/algorithms/math/modular_exponentiation.cpp b/algorithms/math/modular_exponentiation.cpp new file mode 100644 index 00000000..c57a633d --- /dev/null +++ b/algorithms/math/modular_exponentiation.cpp @@ -0,0 +1,42 @@ +// Modular exponentiation implemented in C++ +// Given three numbers x, y and p, compute +// (power(x,y)) % p. where power(a,b) calculates a +// to power of b +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/math +// https://github.com/allalgorithms/cpp +// +// Contributed by: Rituparno Biswas +// Github: @roopbiswas +// +#include +using namespace std; + +typedef long long int ll; + +ll power(ll x, ll y, ll p) +{ + if(x==0) + return 0; + if(y==0) + return 1; + if (y%2==0) + { + ll g=power(x,y/2,p); + return (g*g)%p; + } + else + { + ll g=power(x,y/2,p); + return (x*(g*g)%p)%p; + } +} + +int main() +{ + ll x = 2,y = 5, p = 13; + printf("Power is %lld", power(x, y, p)); + return 0; +} diff --git a/algorithms/math/nth_fibonacci_using_goldenratio.cpp b/algorithms/math/nth_fibonacci_using_goldenratio.cpp new file mode 100644 index 00000000..f66c0761 --- /dev/null +++ b/algorithms/math/nth_fibonacci_using_goldenratio.cpp @@ -0,0 +1,50 @@ +// +// CPP program to find n-th Fibonacci number +// More documentation about the algorithm +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Mohbius +// Github: @mohbius +// +#include +#include +#include +using namespace std; + +// Approximate value of golden ratio +double PHI = 1.6180339; + +// Fibonacci numbers upto n = 5 +int f[6] = { 0, 1, 1, 2, 3, 5 }; + +// Function to find nth +// Fibonacci number +int fib (int n) +{ + // Fibonacci numbers for n < 6 + if (n < 6) + return f[n]; + + // Else start counting from + // 5th term + int t = 5, fn = 5; + + while (t < n) { + fn = round(fn * PHI); + t++; + } + + return fn; +} + +int main() +{ + std::cout << fib(9) << std::endl; // 34 + std::cout << fib(8) << std::endl; // 21 + std::cout << fib(7) << std::endl; // 13 + return 0; +} diff --git a/algorithms/math/pascals_triangle.cpp b/algorithms/math/pascals_triangle.cpp new file mode 100644 index 00000000..31bb6ce1 --- /dev/null +++ b/algorithms/math/pascals_triangle.cpp @@ -0,0 +1,39 @@ + +// Algorith in C++ for Pascal's Triangle of n Lines +#include +int binomialCoeff(int n, int k); + +// Function to print first n lines of Pascal's Triangle +void printPascal(int n) +{ + for (int line = 0; line < n; line++) + { + for (int i = 0; i <= line; i++) + printf("%d ", + binomialCoeff(line, i)); + printf("\n"); + } +} + + +int binomialCoeff(int n, int k) +{ + int res = 1; + if (k > n - k) + k = n - k; + for (int i = 0; i < k; ++i) + { + res *= (n - i); + res /= (i + 1); + } + + return res; +} + + +int main() +{ + int n = 7; + printPascal(n); + return 0; +} diff --git a/algorithms/math/prime.cpp b/algorithms/math/prime.cpp new file mode 100644 index 00000000..1e4a0734 --- /dev/null +++ b/algorithms/math/prime.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; +int main(){ + int n; + cin>>n; + //to check whether a number is prime or not + bool isPrime=true; + for(int i = 2 ;i <= n/2; i++){ + if( n%i == 0){ + isPrime=false; + break; + } + } + if(isPrime) cout<<"Number is Prime"< +using namespace std; + +int main() +{ + int n, i; + bool isPrime = true; + + cout << "Enter a positive integer: "; + cin >> n; + + for(i = 2; i <= n / 2; ++i) + { + if(n % i == 0) + { + isPrime = false; + break; + } + } + if (isPrime) + cout << "This is a prime number"; + else + cout << "This is not a prime number"; + + return 0; +} \ No newline at end of file diff --git a/algorithms/math/sieve_of_eratosthenes.cpp b/algorithms/math/sieve_of_eratosthenes.cpp new file mode 100644 index 00000000..dd955121 --- /dev/null +++ b/algorithms/math/sieve_of_eratosthenes.cpp @@ -0,0 +1,49 @@ +// this is a program to implement sieve algorithm to generate prime numbers. + +//https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes + +#include +#define ll long long +#define pb push_back +#define endl '\n' +#define pii pair +#define vi vector +#define all(a) (a).begin(),(a).end() +#define F first +#define S second +#define hell 1000000007 +#define lbnd lower_bound +#define ubnd upper_bound +#define bs binary_search +#define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); +using namespace std; +int prime[1000000]={0}; +void sieve(int n) +{ + for(int i=2;i<=n;i++) + { + if(prime[i]==0) + { + for(int j=2*i;j<=n;j+=i) + prime[j]=1; + } + } +} +int main() +{ + ios + + int x; + cin>>x; + + sieve(x); + + //now whichever i>1 has prime[i]==0 , is a prime. + + for(int i=2;i<=x;i++) + { + if(prime[i]==0) + cout< + +using namespace std; + +const int MAXPOLY = 200; +double EPSILON = 0.000001; + +class Point +{ + private: + public: + double x, y; +}; + +class Polygon +{ + private: + public: + Point p[MAXPOLY]; + int n; + + Polygon() + { + for (int i = 0; i < MAXPOLY; i++) + Point p[i];// = new Point(); + } +}; + +double area(Polygon p) +{ + double total = 0; + for (int i = 0; i < p.n; i++) + { + int j = (i + 1) % p.n; + total += (p.p[i].x * p.p[j].y) - (p.p[j].x * p.p[i].y); + } + return total / 2; +} + +int main(int argc, char **argv) +{ + Polygon p; + + cout << "Enter the number of points in Polygon: "; + cin >> p.n; + cout << "Enter the coordinates of each point: "; + for (int i = 0; i < p.n; i++) + { + cin >> p.p[i].x; + cin >> p.p[i].y; + } + + double a = area(p); + if (a > 0) + cout << "The Area of Polygon with " << (p.n) + << " points using Slicker Algorithm is : " << a; + else + cout << "The Area of Polygon with " << p.n + << " points using Slicker Algorithm is : " << (a * -1); +} diff --git a/algorithms/math/sphenic_n_o.cpp b/algorithms/math/sphenic_n_o.cpp new file mode 100644 index 00000000..874acfea --- /dev/null +++ b/algorithms/math/sphenic_n_o.cpp @@ -0,0 +1,86 @@ +//CODE ADAPTED FROM OTHER WEBSITE. +// C++ program to check whether a number is a +// Sphenic number or not +#include +using namespace std; + +const int MAX = 1000; + +// Create a vector to store least primes. +// Initialize all entries as 0. +vector least_pf(MAX, 0); + +// This function fills values in least_pf[]. +// such that the value of least_pf[i] stores +// smallest prime factor of i. +// This function is based on sieve of Eratosthenes +void leastPrimeFactor(int n) +{ + // Least prime factor for 1 is 1 + least_pf[1] = 1; + + // Store least prime factor for all other + // numbers. + for (int i = 2; i <= n; i++) + { + // least_pf[i] == 0 means i is prime + if (least_pf[i] == 0) + { + // Initializing prime number as its own + // least prime factor. + least_pf[i] = i; + + // Mark 'i' as a divisor for all its + // multiples that are not already marked + for (int j = 2*i; j <= n; j += i) + if (least_pf[j] == 0) + least_pf[j] = i; + } + } +} + +// Function returns true if n is a sphenic number and +// No otherwise +bool isSphenic(int n) +{ + // Stores three prime factors of n. We have at-most + // three elements in s. + set s; + + // Keep finding least prime factors until n becomes 1 + while (n > 1) + { + // Find least prime factor of current value of n. + int lpf = least_pf[n]; + + // We store current size of s to check if a prime + // factor repeats + int init_size = s.size(); + + // Insert least prime factor of current value of n + s.insert(lpf); + + // If either lpf repeats or number of lpfs becomes + // more than 3, then return false. + if (s.size() == init_size || s.size() > 3) + + // same prime divides the + // number more than once + return false; + + // Divide n by lpf + n /= lpf; + } + + // Return true if size of set is 3 + return (s.size() == 3); +} + +int main() +{ + leastPrimeFactor(MAX); + for (int i=1; i<100; i++) + if (isSphenic(i)) + cout << i << " "; + return 0; +} diff --git a/algorithms/math/squareroot.cpp b/algorithms/math/squareroot.cpp new file mode 100644 index 00000000..850da332 --- /dev/null +++ b/algorithms/math/squareroot.cpp @@ -0,0 +1,16 @@ +#include +#include +using namespace std; +int main() +{ + int t,n; + cin>>t; + while(t>0) + { + cin>>n; + int root; + root=sqrt(n); + cout< +using namespace std; + +int factorial(int begin, int end) +{ + int num = 1; + for (int i = begin; i <= end; i++) + num *= i; + + return num; +} + +int square(int n) +{ + return factorial(n + 1, 2 * n) / factorial(1, n); +} + +int main() +{ + int n; + cout << "Enter the number :"; + cin >> n; + cout << "The Sum of Square is " << square(n) << endl; + return 0; +} + diff --git a/algorithms/math/t_ermo_conv.cpp b/algorithms/math/t_ermo_conv.cpp new file mode 100644 index 00000000..493a5a5e --- /dev/null +++ b/algorithms/math/t_ermo_conv.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int main() +{ + float x; + // Convert temperature from Celsius to Fahrenheit, Reamur, and Kelvin + cout << "Temperature in Celsius = "; + cin >> x; + + float f,r,k; + f=1.8*x+32; + r=0.8*x; + k=273+x; + + cout << "Temperature in Fahrenheit= " << f << endl; + cout << "Temperature in Reamur = " << r << endl; + cout << "Temperature in Kelvin = " << k << endl; + + system("pause"); + return 0; +} \ No newline at end of file diff --git a/algorithms/matrix_linear.cpp b/algorithms/matrix_linear.cpp new file mode 100644 index 00000000..75ead31e --- /dev/null +++ b/algorithms/matrix_linear.cpp @@ -0,0 +1,38 @@ +// represent linear equation in form of matrix +#include +#include + +using namespace std; + +int main(void) +{ + char var[] = { 'x', 'y', 'z', 'w' }; + cout << "Enter the number of variables in the equations: "; + int n; + cin >> n; + cout << "\nEnter the coefficients of each variable for each equations"; + cout << "\nax + by + cz + ... = d"; + int mat[n][n]; + int constants[n][1]; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> mat[i][j]; + } + cin >> constants[i][0]; + } + + cout << "Matrix representation is: "; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cout << " " << mat[i][j]; + } + cout << " " << var[i]; + cout << " = " << constants[i][0]; + cout << "\n"; + } + return 0; +} diff --git a/algorithms/scheduling-algorithms/sjf.cpp b/algorithms/scheduling-algorithms/sjf.cpp new file mode 100644 index 00000000..136fddb2 --- /dev/null +++ b/algorithms/scheduling-algorithms/sjf.cpp @@ -0,0 +1,89 @@ + +// C++ program to implement Shortest Job first +#include +using namespace std; + +struct Process +{ + int pid; // Process ID + int bt; // Burst Time +}; + +// This function is used for sorting all +// processes in increasing order of burst +// time +bool comparison(Process a, Process b) +{ + return (a.bt < b.bt); +} + +// Function to find the waiting time for all +// processes +void findWaitingTime(Process proc[], int n, int wt[]) +{ + // waiting time for first process is 0 + wt[0] = 0; + + // calculating waiting time + for (int i = 1; i < n ; i++ ) + wt[i] = proc[i-1].bt + wt[i-1] ; +} + +// Function to calculate turn around time +void findTurnAroundTime(Process proc[], int n, + int wt[], int tat[]) +{ + // calculating turnaround time by adding + // bt[i] + wt[i] + for (int i = 0; i < n ; i++) + tat[i] = proc[i].bt + wt[i]; +} + +//Function to calculate average time +void findavgTime(Process proc[], int n) +{ + int wt[n], tat[n], total_wt = 0, total_tat = 0; + + // Function to find waiting time of all processes + findWaitingTime(proc, n, wt); + + // Function to find turn around time for all processes + findTurnAroundTime(proc, n, wt, tat); + + // Display processes along with all details + cout << "\nProcesses "<< " Burst time " + << " Waiting time " << " Turn around time\n"; + + // Calculate total waiting time and total turn + // around time + for (int i = 0; i < n; i++) + { + total_wt = total_wt + wt[i]; + total_tat = total_tat + tat[i]; + cout << " " << proc[i].pid << "\t\t" + << proc[i].bt << "\t " << wt[i] + << "\t\t " << tat[i] < 1): + + # Check if fibMm2 is a valid location + i = min(offset+fibMMm2, n-1) + + # If x is greater than the value at + # index fibMm2, cut the subarray array + # from offset to i + if (arr[i] < x): + fibM = fibMMm1 + fibMMm1 = fibMMm2 + fibMMm2 = fibM - fibMMm1 + offset = i + + # If x is greater than the value at + # index fibMm2, cut the subarray + # after i+1 + elif (arr[i] > x): + fibM = fibMMm2 + fibMMm1 = fibMMm1 - fibMMm2 + fibMMm2 = fibM - fibMMm1 + + # element found. return index + else : + return i + + # comparing the last element with x */ + if(fibMMm1 and arr[offset+1] == x): + return offset+1; + + # element not found. return -1 + return -1 + +# Driver Code +arr = [10, 22, 35, 40, 45, 50, + 80, 82, 85, 90, 100] +n = len(arr) +x = 85 +print("Found at index:", + fibMonaccianSearch(arr, x, n)) + +# This code is contributed by Pratik_yadav diff --git a/searches/binary_search.cpp b/algorithms/searches/binary_search.cpp similarity index 70% rename from searches/binary_search.cpp rename to algorithms/searches/binary_search.cpp index fae0d170..8c148ca7 100644 --- a/searches/binary_search.cpp +++ b/algorithms/searches/binary_search.cpp @@ -1,8 +1,15 @@ +// // Binary Search implemented in C++ -// Carlos Abraham Hernandez -// algorithms.abranhe.com/searches/binary-search -// repl.it/@abranhe/Binary-Search - +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/searches/binary-search +// https://github.com/allalgorithms/cpp +// https://repl.it/@abranhe/Binary-Search +// +// Contributed by: Carlos Abraham Hernandez +// Github: @abranhe +// #include using namespace std; @@ -29,16 +36,16 @@ int main(int argc, char const *argv[]) cin >> n; cout << "Enter array elements: "; int a[n]; - + for (int i = 0; i < n; ++i) { - cin>>a[i]; + cin>>a[i]; } cout << "Enter search key: "; - cin>>key; - + cin>>key; + int res = binary_search(a, 0, n-1, key); - + if(res != -1) cout<< key << " found at index " << res << endl; else diff --git a/algorithms/searches/binary_search_float.cpp b/algorithms/searches/binary_search_float.cpp new file mode 100644 index 00000000..dffe6a35 --- /dev/null +++ b/algorithms/searches/binary_search_float.cpp @@ -0,0 +1,48 @@ +#include +#define eps 1e-3 +using namespace std; + + + +int binary_search_float(double a[],int lo,int hi,double key) +{ + double res=-1; + while(hi>=lo) + { + int m = lo + (hi-lo) / 2; + if(a[m]-key >= eps){ + hi = m-1; + }else if(abs(a[m]-key) <= eps){ + res =m; + break; + }else{ + lo = m+1; + } + } + return res; +} + + +int main(){ + int n; + double key; + cout << "Enter size of array: "; + cin >> n; + cout << "Enter array elements: "; + double a[n]; + + for (int i = 0; i < n; ++i) + { + cin>>a[i]; + } + cout << "Enter search key: "; + cin>>key; + + double 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/algorithms/searches/exponential_search.cpp b/algorithms/searches/exponential_search.cpp new file mode 100644 index 00000000..e0419f32 --- /dev/null +++ b/algorithms/searches/exponential_search.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +int binarySearch(int arr[], int, int, int); + +int exponentialSearch(int arr[], int n, int x) +{ + + if (arr[0] == x) + return 0; + int i = 1; + while (i < n && arr[i] <= x) + i = i*2; + + + return binarySearch(arr, i/2, min(i, n), x); +} + + +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) + { + int mid = l + (r - l)/2; + + if (arr[mid] == x) + return mid; + + if (arr[mid] > x) + return binarySearch(arr, l, mid-1, x); + + return binarySearch(arr, mid+1, r, x); + } + + + return -1; +} + + +int main(void) +{ + int arr[] = {2, 3, 4, 10, 40}; + int n = sizeof(arr)/ sizeof(arr[0]); + int x = 10; + int result = exponentialSearch(arr, n, x); + (result == -1)? printf("Element is not present in array") + : printf("Element is present at index %d", + result); + return 0; +} diff --git a/algorithms/searches/interpolationSEARCH.cpp b/algorithms/searches/interpolationSEARCH.cpp new file mode 100644 index 00000000..6a8699b5 --- /dev/null +++ b/algorithms/searches/interpolationSEARCH.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; +int interpolationSearch(int arr[], int n, int x) +{ + // Find indexes of two corners + int lo = 0, hi = (n - 1); + + // Since array is sorted, an element present + // in array must be in range defined by corner + while (lo <= hi && x >= arr[lo] && x <= arr[hi]) + { + if (lo == hi) + { + if (arr[lo] == x) return lo; + return -1; + } + // Probing the position with keeping + // uniform distribution in mind. + int pos = lo + (((double)(hi - lo) / + (arr[hi] - arr[lo])) * (x - arr[lo])); + + // Condition of target found + if (arr[pos] == x) + return pos; + + // If x is larger, x is in upper part + if (arr[pos] < x) + lo = pos + 1; + + // If x is smaller, x is in the lower part + else + hi = pos - 1; + } + return -1; +} + +// Driver Code +int main() +{ + // Array of items on which search will + // be conducted. + int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47}; + int n = sizeof(arr)/sizeof(arr[0]); + + int x = 18; // Element to be searched + int index = interpolationSearch(arr, n, x); + + // If element was found + if (index != -1) + cout << "Element found at index " << index; + else + cout << "Element not found."; + return 0; +} diff --git a/algorithms/searches/interpolation_search.cpp b/algorithms/searches/interpolation_search.cpp new file mode 100644 index 00000000..3ef40b8a --- /dev/null +++ b/algorithms/searches/interpolation_search.cpp @@ -0,0 +1,61 @@ +// C++ program to implement interpolation search +#include +using namespace std; + +// If x is present in arr[0..n-1], then returns +// index of it, else returns -1. +int interpolationSearch(int arr[], int n, int x) +{ + // Find indexes of two corners + int lo = 0, hi = (n - 1); + + // Since array is sorted, an element present + // in array must be in range defined by corner + while (lo <= hi && x >= arr[lo] && x <= arr[hi]) + { + if (lo == hi) + { + if (arr[lo] == x) return lo; + return -1; + } + // Probing the position with keeping + // uniform distribution in mind. + int pos = lo + (((double)(hi - lo) / + (arr[hi] - arr[lo])) * (x - arr[lo])); + + // Condition of target found + if (arr[pos] == x) + return pos; + + // If x is larger, x is in upper part + if (arr[pos] < x) + lo = pos + 1; + + // If x is smaller, x is in the lower part + else + hi = pos - 1; + } + return -1; +} + +// Driver Code +int main() +{ + // Array of items on which search will + // be conducted. + int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47}; + int n = sizeof(arr)/sizeof(arr[0]); + + int x = 18; // Element to be searched + int index = interpolationSearch(arr, n, x); + + // If element was found + if (index != -1) + cout << "Element found at index " << index; + else + cout << "Element not found."; + return 0; +} + +// This code is contributed by Mukul Singh. diff --git a/algorithms/searches/jump_search.cpp b/algorithms/searches/jump_search.cpp new file mode 100644 index 00000000..ae62119a --- /dev/null +++ b/algorithms/searches/jump_search.cpp @@ -0,0 +1,70 @@ +// +// C++ program to implement Jump Search +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/searches/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Bharat Reddy +// Github: @Bharat-Reddy +// +#include +using namespace std; + +int jumpSearch(int arr[], int x, int n) +{ + // Finding block size to be jumped + int step = sqrt(n); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[min(step, n)-1] < x) + { + prev = step; + step += sqrt(n); + if (prev >= n) + return -1; + } + + // Doing a linear search for x in block + // beginning with prev. + while (arr[prev] < x) + { + prev++; + + // If we reached next block or end of + // array, element is not present. + if (prev == min(step, n)) + return -1; + } + // If element is found + if (arr[prev] == x) + return prev; + + return -1; +} + +// Driver program to test function +int main() +{ + int n,i; + cout<<"Eneter size of array : "; + cin>>n; + cout<<"Enter elements of array"<>a[i]; + sort(a,a+n); + cout<<"Enter key to be searched : "; + int key; + cin>>key; + + // Find the index of 'x' using Jump Search + int index = jumpSearch(a, key, n); + + // Print the index where 'x' is located + cout << "\nNumber " << key << " is at index " << index; + return 0; +} diff --git a/algorithms/searches/kth_largest.cpp b/algorithms/searches/kth_largest.cpp new file mode 100644 index 00000000..2d740a9e --- /dev/null +++ b/algorithms/searches/kth_largest.cpp @@ -0,0 +1,40 @@ +/* +k-th largest element in the array +Finding k-th largest element in the array with the lowest possible time complexity O(nlogn).*/ + +#include +#include +#include +using namespace std; + +int kthLargest(vector arr, int n, int k) +{ + priority_queue, greater> pq; + for (int i = 0; i < k; i++) + { + pq.push(arr[i]); + } + for (int i = k; i < n; i++) + { + if (arr[i] > pq.top()) + { + pq.pop(); + pq.push(arr[i]); + } + } + return pq.top(); +} + +int main() +{ + int n, k, s; + vector arr; + cin >> n; + for (int i = 0; i < n; i++) + { + cin >> s; + arr.push_back(s); + } + cin >> k; + cout << kthLargest(arr, n, k) << endl; +} diff --git a/searches/linear_search.cpp b/algorithms/searches/linear_search.cpp similarity index 69% rename from searches/linear_search.cpp rename to algorithms/searches/linear_search.cpp index 61d3ee91..8ea36504 100644 --- a/searches/linear_search.cpp +++ b/algorithms/searches/linear_search.cpp @@ -1,6 +1,14 @@ -// Binary Search implemented in C++ -//Author : Bharat Reddy - +// +// C++ program to implement Linear Search +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/searches/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Bharat Reddy +// Github: @Bharat-Reddy +// #include using namespace std; @@ -32,8 +40,8 @@ int main() cout< +#include +using namespace std; + +vector ar; + +int ternary_search(int l,int r, int x) +{ + if(r>=l) + { + int mid1 = l + (r-l)/3; + int mid2 = r - (r-l)/3; + if(ar[mid1] == x) + return mid1; + if(ar[mid2] == x) + return mid2; + if(xar[mid2]) + return ternary_search(mid2+1,r,x); + else + return ternary_search(mid1+1,mid2-1,x); + + } + return -1; +} + +int main(int argc, char const *argv[]) +{ + int n, key; + cout << "Enter size of array: "; + cin >> n; + cout << "Enter array elements: "; + + for (int i = 0; i < n; ++i) + { + int t; + cin>>t; + ar.push_back(t); + } + cout << "Enter search key: "; + cin>>key; + + int res = ternary_search(0, n-1, key); + + if(res != -1) + cout<< key << " found at index " << res << endl; + else + cout << key << " not found" << endl; + return 0; +} diff --git a/algorithms/searches/trie_data_structure_String_search.cpp b/algorithms/searches/trie_data_structure_String_search.cpp new file mode 100644 index 00000000..89621319 --- /dev/null +++ b/algorithms/searches/trie_data_structure_String_search.cpp @@ -0,0 +1,90 @@ +/* + +Author-Krishan singh karki +Algorithm name-trie tree for seaching a string in n number of string +this is trie tree data structure implementation in c++. We want to search +a string an array of string if string is present or not with trie data structure +.Trie data structure has less time complexity as compared to linear search for large +value of n. +*/ + +/* +HACKTOBERFEST +*/ + +#include +using namespace std; + +struct trie//creating structure name trie +{ + struct trie* m[26];//creating mapping for the 26 small latters alphabet + int end=0;//0 means not a leaf node and 1 means it is a leaf node + +}; +struct trie * BuildtrieTree(struct trie * root,string s, int start, int size){ + if(start==size&&root==NULL){//cheking if this is last char of string and that node does not exist already + struct trie *temp; + temp=(struct trie*)malloc(sizeof(struct trie));//dynamically allocating memory + temp->end=1; + root=temp; + } + else if(start==size){//cheking if this is last char of string but node exist already + + } + else if(root!=NULL){//cheking for this is not last char in string and node for that char does not exist + //cout<end=0; + root->m[s[start]-'a']=BuildtrieTree( root->m[s[start]-'a'], s, start+1, size );//recursivly calling child node + + } + else {// finally cheking for this is not last char but that char node exist already + struct trie *temp; + temp=(struct trie*)malloc(sizeof(struct trie)); + temp->end=0; + root=temp; + root->m[s[start]-'a']=BuildtrieTree( root->m[s[start]-'a'], s, start+1, size ); + + } + + return root; +} +void checkString(struct trie *root, string s, int start ,int size){ + if(start==size&&root->end==1){// if the start pointer has reached to the end and this is a leaf node + + cout<<"YES this string exist in the array of string "; + } + else if(root->m[s[start]-'a']!=NULL){//start pointer has not reached to the end and there are more + //char left in string to be searched + checkString(root->m[s[start]-'a'],s,start+1,size);//recursivly calling there child node + } + else{//start pointer has not reached to the end and no strings from all the string has meached to this string + cout<<"SORRY, this string does not exist in the array of string"; + } + +} +int main(){ + struct trie *root = NULL; + + //dynamcally alocating the first root node + root=(struct trie*)malloc(sizeof(struct trie)); + root->end=1; + + int num; + cout<<"Enter the number of strings you want to insert : "; + cin>>num; + + string s[num]; + cout<>s[i]; + + for(int i=0;i>s2; + + + checkString( root, s2, 0, s2.length()); + +} diff --git a/algorithms/sorting/3_way_quicksort.c b/algorithms/sorting/3_way_quicksort.c new file mode 100644 index 00000000..a9dbd1c9 --- /dev/null +++ b/algorithms/sorting/3_way_quicksort.c @@ -0,0 +1,81 @@ +#include +int common=0; +void swap (int *a,int *b) +{ + int temp; + temp=*a; + *a=*b; + *b=temp; + return; +} + +int partition(int *a,int start,int end) +{ + int i=0; + int pivot_index=0; + int pivot=a[end]; + if (start==end) + return pivot_index; + + for (i=0;i=end) + return; + + int pivot=partition(a,start,end); + int temp=common; + common=0; + quicksort(a,start,pivot-temp-1); + quicksort(a,pivot+1,end); +} + +void print(int *a,int n) +{ + int i=0; + for(i=0;i +#include +#include +using namespace std; + +void bucketSort(float arr[], int n) +{ + vector b[n]; + + for (int i=0; i +using namespace std; + +int getNextGap(int gap) +{ + gap = (gap*10)/13; + + if (gap < 1) + return 1; + return gap; +} + +void combSort(int a[], int n) +{ + + int gap = n; + + bool swapped = true; + + + while (gap != 1 || swapped == true) + { + + gap = getNextGap(gap); + + swapped = false; + + + for (int i=0; i a[i+gap]) + { + swap(a[i], a[i+gap]); + swapped = true; + } + } + } +} + + +int main() +{ + int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; + int n = sizeof(a)/sizeof(a[0]); + + combSort(a, n); + + printf("Sorted array: \n"); + for (int i=0; i +using namespace std; + +void cycleSort(int arr[], int n) +{ + int writes = 0; + + for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { + + int item = arr[cycle_start]; + + int pos = cycle_start; + for (int i = cycle_start + 1; i < n; i++) + if (arr[i] < item) + pos++; + + + if (pos == cycle_start) + continue; + + + while (item == arr[pos]) + pos += 1; + + + if (pos != cycle_start) { + swap(item, arr[pos]); + writes++; + } + + + while (pos != cycle_start) { + pos = cycle_start; + + + for (int i = cycle_start + 1; i < n; i++) + if (arr[i] < item) + pos += 1; + + + while (item == arr[pos]) + pos += 1; + + + if (item != arr[pos]) { + swap(item, arr[pos]); + writes++; + } + } + } +} + +int main() +{ + int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; + int n = sizeof(arr) / sizeof(arr[0]); + cycleSort(arr, n); + + cout << "After sort : " << endl; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} diff --git a/algorithms/sorting/PigeonholeSort.cpp b/algorithms/sorting/PigeonholeSort.cpp new file mode 100644 index 00000000..68339633 --- /dev/null +++ b/algorithms/sorting/PigeonholeSort.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +void pigeonholeSort(int arr[], int n) +{ + int min = arr[0], max = arr[0]; + for (int i = 1; i < n; i++) + { + if (arr[i] < min) + min = arr[i]; + if (arr[i] > max) + max = arr[i]; + } + int range = max - min + 1; // Find range + + vector holes[range]; + + for (int i = 0; i < n; i++) + holes[arr[i]-min].push_back(arr[i]); + + int index = 0; // index in sorted array + for (int i = 0; i < range; i++) + { + vector::iterator it; + for (it = holes[i].begin(); it != holes[i].end(); ++it) + arr[index++] = *it; + } +} + +int main() +{ + int arr[] = {8, 3, 2, 7, 4, 6, 8}; + int n = sizeof(arr)/sizeof(arr[0]); + + pigeonholeSort(arr, n); + + printf("Sorted order is : "); + for (int i = 0; i < n; i++) + printf("%d ", arr[i]); + + return 0; +} diff --git a/algorithms/sorting/bogo_sort.cpp b/algorithms/sorting/bogo_sort.cpp new file mode 100644 index 00000000..968faca6 --- /dev/null +++ b/algorithms/sorting/bogo_sort.cpp @@ -0,0 +1,47 @@ + + +#include +using namespace std; + + +bool isSorted(int a[], int n) +{ + while ( --n > 1 ) + if (a[n] < a[n-1]) + return false; + return true; +} + + +void shuffle(int a[], int n) +{ + for (int i=0; i < n; i++) + swap(a[i], a[rand()%n]); +} + + +void bogosort(int a[], int n) +{ + + while ( !isSorted(a, n) ) + shuffle(a, n); +} + + +void printArray(int a[], int n) +{ + for (int i=0; i + + +unsigned int readLength() { + + unsigned int length; + + std::cin >> length; + + return length; +} + +void readArray(int array[], unsigned int length) { + + for (int i = 0; i < length; i++) + std::cin >> array[i]; +} + + +void bubbleSortArray(int array[], unsigned int length) { + + bool changed; + + length -= 1; + + for (int i = 0; i < length; i++) { + + changed = false; + + for (int j = 0; j < length - i; j++) { + + if (array[j] > array[j + 1]) { + + std::swap(array[j], array[j+1]); + changed = true; + } + } + + if (changed == false) + return; + } +} + +void outputArray(int array[], unsigned int length) { + + for (int i = 0; i < length; i++) + std::cout << array[i] << " "; + + std::cout << '\n'; +} + +int main() { + + std::cout << "Input the total size : "; + + unsigned int length; + + length = readLength(); + + int array[length]; + + std::cout << "Input the number one-by-one : "; + + readArray(array, length); + + bubbleSortArray(array, length); + + std::cout << "Sorted array:" << std::endl; + + outputArray(array, length); + + return 0; +} \ No newline at end of file diff --git a/algorithms/sorting/bucket_sort.cpp b/algorithms/sorting/bucket_sort.cpp new file mode 100644 index 00000000..7643770d --- /dev/null +++ b/algorithms/sorting/bucket_sort.cpp @@ -0,0 +1,72 @@ +// +// C++ implementation of bucket sort. +// +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Simon Faillace Mullen +// Github: @macmullen +// +#include +#include +#include +#include + +// A utility function to print an array of size n. +// Implemented by Carlos Abraham Hernandez in bubble_sort.cpp +void print_array(int arr[], int n) +{ + for (size_t i = 0; i < n; i++) + { + std::cout << arr[i] << " "; + } + std::cout << std::endl; +} + +// Given an array "arr" of size "n", this function sorts its numbers +// using the algorithm of Bucket Sort. +void bucket_sort(int arr[], size_t n, int number_of_buckets) +{ + // Find the maximum element of the array + int* max = std::max_element(arr, arr+n); + // Calculate the divider value dividing the maximum element and number of buckets. + int divider = std::ceil(float(*max + 1) / float(number_of_buckets) ); + // Create the buckets array. + std::vector> buckets; + buckets.resize(number_of_buckets); + + // Place every number into a corresponding bucket. + for (size_t i = 0; i < n; i++) + { + int j = floor(arr[i] / divider); + buckets[j].push_back(arr[i]); + } + + // Sort every bucket. + int index = 0; + for (size_t i = 0; i < number_of_buckets; i++) + { + sort(buckets[i].begin(), buckets[i].end()); + // Place the sorted numbers into the original array. + for(int number : buckets[i]) + { + arr[index] = number; + index++; + } + } +} + +int main() +{ + int arr[] = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14}; + int n = sizeof(arr)/sizeof(arr[0]); + std::cout << "Unsorted array: "; + print_array(arr, n); + bucket_sort(arr, n, 10); + std::cout << "Sorted array: "; + print_array(arr, n); + return 0; +} \ No newline at end of file diff --git a/algorithms/sorting/counting_sort.cpp b/algorithms/sorting/counting_sort.cpp new file mode 100644 index 00000000..b869b69e --- /dev/null +++ b/algorithms/sorting/counting_sort.cpp @@ -0,0 +1,57 @@ +#include + +using namespace std; + +// A function implementing Counter sort. +void CounterSort(int a[], int n, int r, int lower) +{ + int i, j = 0, counter[r] = {0}; + // Counting the number occurrence of each element. + for(i=0; i 0) + goto flag; + + i++; + } +} + +int main() +{ + int n, i, range, ulimit, llimit; + cout<<"\nEnter the number of data element to be sorted: "; + cin>>n; + + cout<<"\nEnter the lower and upper limit of the data to be entered: "; + cin>>llimit>>ulimit; + + // Range of the input data. + range = ulimit-llimit+1; + + int arr[n]; + for(i = 0; i < n; i++) + { + cout<<"Enter element "<>arr[i]; + } + + CounterSort(arr, n, range, llimit); + + // Printing the sorted data. + cout<<"\nSorted Data "; + for (i = 0; i < n; i++) + cout<<"->"< +#include +#include + +using namespace std; + +class cSort +{ +public: + void doIt( vector s ) + { + sq = s; display(); c_sort(); + cout << "writes: " << wr << endl; display(); + } +private: + void display() + { + copy( sq.begin(), sq.end(), ostream_iterator( std::cout, " " ) ); + cout << endl; + } + void c_sort() + { + wr = 0; + unsigned it, p, vlen = static_cast( sq.size() ); + for( unsigned c = 0; c < vlen - 1; c++ ) + { + it = sq[c]; + p = c; + for( unsigned d = c + 1; d < vlen; d++ ) + if( sq[d] < it ) p++; + + if( c == p ) continue; + + doSwap( p, it ); + + while( c != p ) + { + p = c; + for( unsigned e = c + 1; e < vlen; e++ ) + if( sq[e] < it ) p++; + + doSwap( p, it ); + } + } + } + void doSwap( unsigned& p, unsigned& it ) + { + while( sq[p] == it ) p++; + swap( it, sq[p] ); + wr++; + } + vector sq; + unsigned wr; +}; + +int main(int argc, char ** argv) +{ + srand( static_cast( time( NULL ) ) ); + vector s; + for( int x = 0; x < 20; x++ ) + s.push_back( rand() % 100 + 21 ); + + cSort c; c.doIt( s ); + return 0; +} diff --git a/algorithms/sorting/gnome_sort.cpp b/algorithms/sorting/gnome_sort.cpp new file mode 100644 index 00000000..4ed05e5c --- /dev/null +++ b/algorithms/sorting/gnome_sort.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +void gnomeSort(int arr[], int n) +{ + int index = 0; + + while (index < n) { + if (index == 0) + index++; + if (arr[index] >= arr[index - 1]) + index++; + else { + swap(arr[index], arr[index - 1]); + index--; + } + } + return; +} + +void printArray(int arr[], int n) +{ + cout << "Sorted sequence after Gnome sort: "; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + cout << "\n"; +} + +int main() +{ + int arr[] = { 34, 2, 10, -9 }; + int n = sizeof(arr) / sizeof(arr[0]); + + gnomeSort(arr, n); + printArray(arr, n); + + return (0); +} diff --git a/algorithms/sorting/heap_sort.cpp b/algorithms/sorting/heap_sort.cpp new file mode 100644 index 00000000..02c8d580 --- /dev/null +++ b/algorithms/sorting/heap_sort.cpp @@ -0,0 +1,75 @@ +// +// HeapSorted Implementation (based on CLRS Introduction to Algoithms). +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/sorting +// https://github.com/allalgorithms/cpp +// +// Contributed by: Swapnil Rustagi +// Github: @Swapnilr1 +// +#include +#include +using namespace std; + +void MaxHeapify(vector&, int, int, int); +void BuildMaxHeap(vector&, int, int, int); +void heapSort(vector&, int, int); + +int main() +{ + vector A = {9,4,5,6,5,3,2,10,200,1}; // Random test data + cout << "UNSORTED:" << endl; + for(int i=0; i& A, int low, int i, int HeapSize) +{ + int largest; + int l = 2*(i)+1; //LEFT(i) + int r = 2*(i)+ 1 + 1; // RIGHT(i) + if (l< HeapSize && A[low+l]>A[low+i]) + { + largest = low+l; + } + else largest = low+i; + if (r< HeapSize && A[low+r]>A[largest]) + { + largest = low+r; + } + if (largest != (low+i)) + { + int temp = A[i+low]; + A[i+low] = A[largest]; + A[largest] = temp; + MaxHeapify(A, low, largest-low, HeapSize ); + } +} + +void BuildMaxHeap(vector& A, int low, int high, int HeapSize) +{ + for (int i=(high-low+1)/2-1; i>=0; i--) + { + MaxHeapify(A,low, i, HeapSize); + } +} + +void heapSort(vector& A, int low, int high) +{ + int HeapSize = high-low+1; + BuildMaxHeap(A, low, high, HeapSize); + for (int i=high; i>low; i--) + { + int temp = A[i]; + A[i] = A[low]; + A[low] = temp; + HeapSize--; + MaxHeapify(A,low, 0, HeapSize); + } +} diff --git a/algorithms/sorting/heap_sort_without_vectors.cpp b/algorithms/sorting/heap_sort_without_vectors.cpp new file mode 100644 index 00000000..9cf042db --- /dev/null +++ b/algorithms/sorting/heap_sort_without_vectors.cpp @@ -0,0 +1,64 @@ +// +// C++ program for implementation of Heap Sort +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/ +// https://github.com/allalgorithms/cpp +// +// Contributed by: Kaushlendra Pratap +// Github: @kaushl1998 +// +#include + +using namespace std; +void heapify(int arr[], int n, int i) +{ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + + if (l < n && arr[l] > arr[largest]) + largest = l; + + if (r < n && arr[r] > arr[largest]) + largest = r; + + if (largest != i) + { + swap(arr[i], arr[largest]); + + heapify(arr, n, largest); + } +} + +void heapSort(int arr[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + for (int i=n-1; i>=0; i--) + { + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} + +void printArray(int arr[], int n) +{ + for (int i=0; i +using namespace std; + +/* Function to sort an array using insertion sort*/ +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +/* Driver code */ +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} + +// This is code is contributed by rathbhupendra diff --git a/sorting/merge_sort.cpp b/algorithms/sorting/merge_sort.cpp similarity index 64% rename from sorting/merge_sort.cpp rename to algorithms/sorting/merge_sort.cpp index 4c86dd3c..a841877a 100644 --- a/sorting/merge_sort.cpp +++ b/algorithms/sorting/merge_sort.cpp @@ -1,12 +1,15 @@ -//**************************************** +// // C++ implementation of merge sort // -// Author: Carlos Abraham Hernandez -// abraham@abranhe.com -//**************************************** - -#include -#include +// The All ▲lgorithms Project +// +// https://allalgorithms.com/sorting +// https://github.com/allalgorithms/cpp +// +// Contributed by: Carlos Abraham Hernandez +// Github: @abranhe (abraham@abranhe.com) +// +#include // Merge the two half into a sorted data. void merge(int arr[], int l, int m, int r) @@ -16,8 +19,8 @@ void merge(int arr[], int l, int m, int r) int n2 = r - m; /* create temp arrays */ - int L[n1], R[n2]; - + int* L = new int[n1]; + int* R = new int[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; @@ -60,34 +63,37 @@ void merge(int arr[], int l, int m, int r) j++; k++; } + delete[] L; + delete[] R; } /* l is for left index and r is right index of the sub-array of arr to be sorted */ -void mergeSort(int arr[], int l, int r) +void merge_sort(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h - int m = l+(r-l)/2; + int m = l + (r - l) / 2; // Sort first and second halves - mergeSort(arr, l, m); - mergeSort(arr, m+1, r); + merge_sort(arr, l, m); + merge_sort(arr, m + 1, r); merge(arr, l, m, r); } } /* UTILITY FUNCTIONS */ -/* Function to print an array */ -void printArray(int A[], int size) +// A utility function to print an array of size n +void print_array(int arr[], int n) { - int i; - for (i=0; i < size; i++) - printf("%d ", A[i]); - printf("\n"); + for (size_t i = 0; i < n; i++) + { + std::cout << arr[i] << " "; + } + std::cout << std::endl; } /* Driver program to test above functions */ @@ -95,13 +101,10 @@ int main() { int arr[] = {12, 11, 13, 5, 6, 7}; int arr_size = sizeof(arr)/sizeof(arr[0]); - - printf("Given array is \n"); - printArray(arr, arr_size); - - mergeSort(arr, 0, arr_size - 1); - - printf("\nSorted array is \n"); - printArray(arr, arr_size); + std::cout << "Unsorted array:" << std::endl; + print_array(arr, arr_size); + merge_sort(arr, 0, arr_size - 1); + std::cout << "Sorted array:" << std::endl; + print_array(arr, arr_size); return 0; } diff --git a/algorithms/sorting/quick_sort.cpp b/algorithms/sorting/quick_sort.cpp new file mode 100644 index 00000000..4e97d86b --- /dev/null +++ b/algorithms/sorting/quick_sort.cpp @@ -0,0 +1,66 @@ +// +// C++ implementation of quick sort +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/sorting +// https://github.com/allalgorithms/cpp +// +// Contributed by: Nikunj Taneja +// Github: @underscoreorcus +// +#include +#include + +void quick_sort(std::vector&, size_t, size_t); +int partition(std::vector&, size_t, size_t); + +void quick_sort(std::vector& arr, size_t start, size_t end) +{ + if(start < end) + { + int pivot = partition(arr, start, end); + quick_sort(arr, start, pivot); + quick_sort(arr, pivot + 1, end); + } +} + + +int partition(std::vector& arr, size_t start, size_t end) +{ + int x = arr[start]; + int i = start; + for(size_t j = start + 1; j < end; j++) + { + if(arr[j]<=x) + { + i=i+1; + std::swap(arr[i], arr[j]); + } + } + std::swap(arr[i], arr[start]); + return i; +} + + +void print_vector(std::vector& arr) +{ + for (size_t i = 0; i < arr.size(); i++) + { + std::cout << arr[i] << " "; + } + std::cout << std::endl; +} + + +int main() +{ + std::vector arr = {10,9,8,7,6,5,4,3,2,1}; + int start = 0; + int end = arr.size(); + std::cout << "Unsorted array:" << std::endl; + print_vector(arr); + quick_sort(arr, start, end); + std::cout << "Sorted array:" << std::endl; + print_vector(arr); +} diff --git a/algorithms/sorting/radix_sort.cpp b/algorithms/sorting/radix_sort.cpp new file mode 100644 index 00000000..65cdf05f --- /dev/null +++ b/algorithms/sorting/radix_sort.cpp @@ -0,0 +1,73 @@ +// C++ implementation of Radix Sort +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = {0}; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[ (arr[i]/exp)%10 ]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) + { + output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; + count[ (arr[i]/exp)%10 ]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; m/exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver program to test above functions +int main() +{ + int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(arr)/sizeof(arr[0]); + radixsort(arr, n); + print(arr, n); + return 0; +} \ No newline at end of file diff --git a/algorithms/sorting/rank_sort.cpp b/algorithms/sorting/rank_sort.cpp new file mode 100644 index 00000000..387c4bb4 --- /dev/null +++ b/algorithms/sorting/rank_sort.cpp @@ -0,0 +1,54 @@ + +#include +#include +using namespace std; + + void rankSort(int A[], int low, int high) + { + int R[high-low+1]; + for(int i=0; i= A[j]) + R[i-low]++; + + else + R[j-low]++; + } + } + + int U[high-low+1]; + for(int i=0;i>n; + int houses[n]; + cout<<"enter the entries"<>houses[i]; + } + + rankSort(houses,0,n-1); + for(int i=0;i + +// Swap elements +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} + +// Implement selection sort +void selectionSort(int arr[], int n) +{ + int i, j, min_id; + for (i = 0; i < n-1; i++) + { + min_id=i; + for (j = i+1; j < n; j++) + if (arr[min_id] > arr[j]) + min_id=j; + swap(&arr[i], &arr[min_id]); + } +} + +// Function to print elements +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// test +int main() +{ + int arr[] = {46, 24, 33, 10, 2, 81, 50}; + int n = sizeof(arr)/sizeof(arr[0]); + printf("Unsorted array: \n"); + printArray(arr, n); + selectionSort(arr, n); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} diff --git a/algorithms/sorting/shaker_sort.cpp b/algorithms/sorting/shaker_sort.cpp new file mode 100644 index 00000000..f65f3d8e --- /dev/null +++ b/algorithms/sorting/shaker_sort.cpp @@ -0,0 +1,61 @@ +#include + +using namespace std; + +// A function to swap values using call by reference. +void swap(int *a, int *b) +{ + int temp; + temp = *a; + *a = *b; + *b = temp; +} + +// A function implementing shaker sort. +void ShakerSort(int a[], int n) +{ + int i, j, k; + for(i = 0; i < n;) + { + // First phase for ascending highest value to the highest unsorted index. + for(j = i+1; j < n; j++) + { + if(a[j] < a[j-1]) + swap(&a[j], &a[j-1]); + } + // Decrementing highest index. + n--; + + // Second phase for descending lowest value to the lowest unsorted index. + for(k = n-1; k > i; k--) + { + if(a[k] < a[k-1]) + swap(&a[k], &a[k-1]); + } + // Incrementing lowest index. + i++; + } +} + +int main() +{ + int n, i; + cout<<"\nEnter the number of data element to be sorted: "; + cin>>n; + + int arr[n]; + for(i = 0; i < n; i++) + { + cout<<"Enter element "<>arr[i]; + } + + ShakerSort(arr, n); + + // Printing the sorted data. + cout<<"\nSorted Data "; + for (i = 0; i < n; i++) + cout<<"->"< + +using namespace std; + +// A function implementing Shell sort. +void ShellSort(int a[], int n) +{ + int i, j, k, temp; + // Gap 'i' between index of the element to be compared, initially n/2. + for(i = n/2; i > 0; i = i/2) + { + for(j = i; j < n; j++) + { + for(k = j-i; k >= 0; k = k-i) + { + // If value at higher index is greater, then break the loop. + if(a[k+i] >= a[k]) + break; + // Switch the values otherwise. + else + { + temp = a[k]; + a[k] = a[k+i]; + a[k+i] = temp; + } + } + } + } +} +int main() +{ + int n, i; + cout<<"\nEnter the number of data element to be sorted: "; + cin>>n; + + int arr[n]; + for(i = 0; i < n; i++) + { + cout<<"Enter element "<>arr[i]; + } + + ShellSort(arr, n); + + // Printing the sorted data. + cout<<"\nSorted Data "; + for (i = 0; i < n; i++) + cout<<"->"< +#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; + +// A function implementing stooge sort. +void StoogeSort(int a[],int start, int end) +{ + int temp; + // Further breaking the array if the Subpart's length is more than 2. + if(end-start+1 > 2) + { + temp = (end-start+1)/3; + StoogeSort(a, start, end-temp); + StoogeSort(a, start+temp, end); + StoogeSort(a, start, end-temp); + } + + // swapping the element at start and end. + if(a[end] < a[start]) + { + temp = a[start]; + a[start] = a[end]; + a[end] = temp; + } +} + +int main() +{ + int n, i; + cout<<"\nEnter the number of data element to be sorted: "; + cin>>n; + + int arr[n]; + for(i = 0; i < n; i++) + { + cout<<"Enter element "<>arr[i]; + } + + StoogeSort(arr, 0, n-1); + + // Printing the sorted data. + cout<<"\nSorted Data "; + for (i = 0; i < n; i++) + cout<<"->"< +using namespace std; + +struct Node +{ + int key; + struct Node *left, *right; +}; + +struct Node *newNode(int item) +{ + struct Node *temp = new Node; + temp->key = item; + temp->left = temp->right = NULL; + return temp; +} + +void storeSorted(Node *root, int arr[], int &i) +{ + if (root != NULL) + { + storeSorted(root->left, arr, i); + arr[i++] = root->key; + storeSorted(root->right, arr, i); + } +} + +Node* insert(Node* node, int key) +{ + if (node == NULL) return newNode(key); + + if (key < node->key){ + node->left = insert(node->left, key); + }else if (key > node->key) { + node->right = insert(node->right, key); + } + + return node; +} + +void treeSort(int arr[], int n) +{ + struct Node *root = NULL; + + root = insert(root, arr[0]); + for (int i=1; i +#include +#include +using namespace std; +#define root 0 +const int N = 100001, K = 256; + +int sz; +struct tree { + int nx[K], suff; + bool flag; +} t[N]; +int q[N], endq, stq; +short tmp; +int n, i, j, tmp_pos, x; +string s; +int main() +{ + freopen("console2.in", "r", stdin); + freopen("console2.out", "w", stdout); + ios_base :: sync_with_stdio(0); + cin >> n; + getline (cin, s); + for (i = 1; i <= n; ++i) { + getline (cin, s); + tmp_pos = 0; + for (j = 0; j < (int)s.size(); ++j) { + tmp = int(s[j]) - 32; + if (t[tmp_pos].nx[tmp] == 0) + t[tmp_pos].nx[tmp] = ++sz; + tmp_pos = t[tmp_pos].nx[tmp]; + } + t[tmp_pos].flag = 1; + } + q[endq++] = 0; + t[0].suff = 0; + while (stq != endq) { + x = q[stq++]; + if (x != 0) { + for (i = 0; i < K; ++i) { + if (t[x].nx[i] == 0) { + t[x].nx[i] = t[t[x].suff].nx[i]; + } else { + t[t[x].nx[i]].suff = t[t[x].suff].nx[i]; + q[endq++] = t[x].nx[i]; + if(t[t[t[x].nx[i]].suff].flag == 1) + t[t[x].nx[i]].flag = 1; + } + } + } else { + for (i = 0; i < K; ++i) { + if (t[x].nx[i] == 0) { + t[x].nx[i] = 0; + } else { + t[t[x].nx[i]].suff = 0; + q[endq++] = t[x].nx[i]; + if (t[t[t[x].nx[i]].suff].flag == 1) + t[t[x].nx[i]].flag = 1; + } + } + } + } + while (getline (cin, s)) { + tmp_pos = 0; + bool flag = 0; + for (i = 0; i < (int)s.size(); ++i) { + tmp = int(s[i]) - 32; + tmp_pos = t[tmp_pos].nx[tmp]; + if (t[tmp_pos].flag) { + flag = 1; + break; + } + } + if (flag) + cout << s << "\n"; + } + return 0; + +} diff --git a/algorithms/strings/adding_two_string.cpp b/algorithms/strings/adding_two_string.cpp new file mode 100644 index 00000000..1d4fc3cc --- /dev/null +++ b/algorithms/strings/adding_two_string.cpp @@ -0,0 +1,59 @@ +/* +Program : To add 2 string + +this Program is Contributed by github@b419007 +*/ + +#include +using namespace std; + +int Len(string &str1, string &str2) +{ + int len1 = str1.size(); + int len2 = str2.size(); + if (len1 < len2) + { + for (int i = 0 ; i < len2 - len1 ; i++) + str1 = '0' + str1; + return len2; + } + else if (len1 > len2) + { + for (int i = 0 ; i < len1 - len2 ; i++) + str2 = '0' + str2; + } + return len1; +} + +string add( string a, string b ) +{ + string result; + int len = Len(a, b); + + int carry = 0; + for (int i = len-1 ; i >= 0 ; i--) + { + int aBit = a.at(i) - '0'; + int bBit = b.at(i) - '0'; + int sum = (aBit ^ bBit ^ carry)+'0'; + + result = (char)sum + result; + carry = (aBit & bBit) | (bBit & carry) | (aBit & carry); + } + + if (carry) + result = '1' + result; + + return result; +} + +int main() +{ + string str1,str2; + cout<<"Enter the string 1 :"; + cin>>str1; + cout<<"Enter the string 2 :"; + cin>>str2; + cout << "Sum is " << add(str1, str2); + return 0; +} diff --git a/algorithms/strings/anagram_check.cpp b/algorithms/strings/anagram_check.cpp new file mode 100644 index 00000000..13d38364 --- /dev/null +++ b/algorithms/strings/anagram_check.cpp @@ -0,0 +1,101 @@ +// +// C/C++ program to check whether two strings are anagrams +// of each other +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// + +#include +#include + +/* Function prototype for string a given string using + quick sort */ +void quickSort(char *arr, int si, int ei); + +/* function to check whether two strings are anagram of + each other */ +bool areAnagram(char *str1, char *str2) +{ + // Get lenghts of both strings + int n1 = strlen(str1); + int n2 = strlen(str2); + + // If length of both strings is not same, then they + // cannot be anagram + if (n1 != n2) + return false; + + // Sort both strings + quickSort(str1, 0, n1 - 1); + quickSort(str2, 0, n2 - 1); + + // Compare sorted strings + for (int i = 0; i < n1; i++) + if (str1[i] != str2[i]) + return false; + + return true; +} + +// Following functions (exchange and partition are needed +// for quickSort) +void exchange(char *a, char *b) +{ + char temp; + temp = *a; + *a = *b; + *b = temp; +} + +int partition(char A[], int si, int ei) +{ + char x = A[ei]; + int i = (si - 1); + int j; + + for (j = si; j <= ei - 1; j++) + { + if (A[j] <= x) + { + i++; + exchange(&A[i], &A[j]); + } + } + exchange(&A[i + 1], &A[ei]); + return (i + 1); +} + +/* Implementation of Quick Sort +A[] --> Array to be sorted +si --> Starting index +ei --> Ending index +*/ +void quickSort(char A[], int si, int ei) +{ + int pi; /* Partitioning index */ + if (si < ei) + { + pi = partition(A, si, ei); + quickSort(A, si, pi - 1); + quickSort(A, pi + 1, ei); + } +} + +/* Driver program to test to print printDups*/ +int main() +{ + char str1[] = ""; //String 1 + char str2[] = ""; //String 2 + if (areAnagram(str1, str2)) + printf("The two strings are anagram of each other"); + else + printf("The two strings are not anagram of each other"); + + return 0; +} diff --git a/algorithms/strings/divide_string_in_n_equal_parts.cpp b/algorithms/strings/divide_string_in_n_equal_parts.cpp new file mode 100644 index 00000000..83e423fb --- /dev/null +++ b/algorithms/strings/divide_string_in_n_equal_parts.cpp @@ -0,0 +1,53 @@ +// C++ program to divide a string +// in n equal parts +#include +#include + +using namespace std; + +class string_division +{ + +// Function to print n equal parts of str +public: +void divide_String(char str[], int n) +{ + + int str_size = strlen(str); + int i; + int part_size; + + // Check if string can be divided in + // n equal parts + if (str_size % n != 0) + { + cout<<"Invalid Input: String size"; + cout<<" is not divisible by n"; + return; + } + + // Calculate the size of parts to + // find the division points + part_size = str_size / n; + for (i = 0; i< str_size; i++) + { + if (i % part_size == 0) + cout< + +void computeLPSArray(char* pat, int M, int* lps); + +// Prints occurrences of txt[] in pat[] +void KMPSearch(char* pat, char* txt) +{ + int M = strlen(pat); + int N = strlen(txt); + + // create lps[] that will hold the longest prefix suffix + // values for pattern + int lps[M]; + + // Preprocess the pattern (calculate lps[] array) + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt[] + int j = 0; // index for pat[] + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } + + if (j == M) { + printf("Found pattern at index %d ", i - j); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && pat[j] != txt[i]) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } +} + +// Fills lps[] for given patttern pat[0..M-1] +void computeLPSArray(char* pat, int M, int* lps) +{ + // length of the previous longest prefix suffix + int len = 0; + + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + int i = 1; + while (i < M) { + if (pat[i] == pat[len]) { + len++; + lps[i] = len; + i++; + } + else // (pat[i] != pat[len]) + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; + + // Also, note that we do not increment + // i here + } + else // if (len == 0) + { + lps[i] = 0; + i++; + } + } + } +} + +// Driver program to test above function +int main() +{ + char txt[] = "ABABDABACDABABCABAB"; + char pat[] = "ABABCABAB"; + KMPSearch(pat, txt); + return 0; +} diff --git a/algorithms/strings/lexicographic_ranking.cpp b/algorithms/strings/lexicographic_ranking.cpp new file mode 100644 index 00000000..06aee17c --- /dev/null +++ b/algorithms/strings/lexicographic_ranking.cpp @@ -0,0 +1,64 @@ +// +// Lexicographic ranking algorithm Implementation +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +#include + +// A utility function to find factorial of n +int fact(int n) +{ + return (n <= 1) ? 1 : n * fact(n - 1); +} + +// A utility function to count smaller characters on right +// of arr[low] +int findSmallerInRight(char *str, int low, int high) +{ + int countRight = 0, i; + + for (i = low + 1; i <= high; ++i) + if (str[i] < str[low]) + ++countRight; + + return countRight; +} + +// A function to find rank of a string in all permutations +// of characters +int findRank(char *str) +{ + int len = strlen(str); + int mul = fact(len); + int rank = 1; + int countRight; + + int i; + for (i = 0; i < len; ++i) + { + mul /= len - i; + + // count number of chars smaller than str[i] + // fron str[i+1] to str[len-1] + countRight = findSmallerInRight(str, i, len - 1); + + rank += countRight * mul; + } + + return rank; +} + +// Driver program to test above function +int main() +{ + char str[] = ""; //Enter string here + printf("%d", findRank(str)); + return 0; +} diff --git a/algorithms/strings/lexicographically_kth_ smallest_suffix.cpp b/algorithms/strings/lexicographically_kth_ smallest_suffix.cpp new file mode 100644 index 00000000..867cb24c --- /dev/null +++ b/algorithms/strings/lexicographically_kth_ smallest_suffix.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; +#define ll long long + +//Print the lexicographically kth smallest suffix of the string S. + +int main() +{ + ll int i,j,k; + string s; + cin>>s>>k; + string s1[s.size()]; + for(i=0;i +#include + +// A utility function to print a substring str[low..high] +void printSubStr(char *str, int low, int high) +{ + for (int i = low; i <= high; ++i) + printf("%c", str[i]); +} + +// This function prints the longest palindrome substring +// of str[]. +// It also returns the length of the longest palindrome +int longestPalSubstr(char *str) +{ + int n = strlen(str); // get length of input string + + // table[i][j] will be false if substring str[i..j] + // is not palindrome. + // Else table[i][j] will be true + bool table[n][n]; + memset(table, 0, sizeof(table)); + + // All substrings of length 1 are palindromes + int maxLength = 1; + for (int i = 0; i < n; ++i) + table[i][i] = true; + + // check for sub-string of length 2. + int start = 0; + for (int i = 0; i < n - 1; ++i) + { + if (str[i] == str[i + 1]) + { + table[i][i + 1] = true; + start = i; + maxLength = 2; + } + } + + // Check for lengths greater than 2. k is length + // of substring + for (int k = 3; k <= n; ++k) + { + // Fix the starting index + for (int i = 0; i < n - k + 1; ++i) + { + // Get the ending index of substring from + // starting index i and length k + int j = i + k - 1; + + // checking for sub-string from ith index to + // jth index iff str[i+1] to str[j-1] is a + // palindrome + if (table[i + 1][j - 1] && str[i] == str[j]) + { + table[i][j] = true; + + if (k > maxLength) + { + start = i; + maxLength = k; + } + } + } + } + + printf("Longest palindrome substring is: "); + printSubStr(str, start, start + maxLength - 1); + + return maxLength; // return length of LPS +} + +// Driver program to test above functions +int main() +{ + char str[] = ""; //Enter string here + printf("\nLength is: %d\n", longestPalSubstr(str)); + return 0; +} diff --git a/algorithms/strings/naive_search.cpp b/algorithms/strings/naive_search.cpp new file mode 100644 index 00000000..51584bb0 --- /dev/null +++ b/algorithms/strings/naive_search.cpp @@ -0,0 +1,53 @@ +// +// C program for A modified Naive Pattern Searching +// algorithm that is optimized for the cases when all +// characters of pattern are different +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +#include + +/* A modified Naive Pettern Searching algorithn that is optimized + for the cases when all characters of pattern are different */ +void search(char pat[], char txt[]) +{ + int M = strlen(pat); + int N = strlen(txt); + int i = 0; + + while (i <= N - M) + { + int j; + + /* For current index i, check for pattern match */ + for (j = 0; j < M; j++) + if (txt[i + j] != pat[j]) + break; + + if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] + { + printf("Pattern found at index %d \n", i); + i = i + M; + } + else if (j == 0) + i = i + 1; + else + i = i + j; // slide the pattern by j + } +} + +/* Driver program to test above function */ +int main() +{ + char txt[] = ""; //Enter the entire string here + char pat[] = ""; //Enter the string to be searched here + search(pat, txt); + return 0; +} diff --git a/algorithms/strings/palindrome_check.cpp b/algorithms/strings/palindrome_check.cpp new file mode 100644 index 00000000..42ed0418 --- /dev/null +++ b/algorithms/strings/palindrome_check.cpp @@ -0,0 +1,40 @@ +// +// C/C++ program to check whether the given string is a palindrome +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Sankalp Godghate +// Github: @sankalp24 +// +#include +using namespace std; +// A function to check if a string str is palindrome +void isPalindrome(string str) +{ + // Start from leftmost and rightmost corners of str + int l = 0; + int h = str.size() - 1; + + // Keep comparing characters while they are same + while (h > l) + { + if (str[l++] != str[h--]) + { + cout<>str; + isPalindrome(str); + return 0; +} diff --git a/algorithms/strings/pangram_check.cpp b/algorithms/strings/pangram_check.cpp new file mode 100644 index 00000000..f0ff70e7 --- /dev/null +++ b/algorithms/strings/pangram_check.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; + +bool checkPangram(string s) { + int arr[26] = {0}; + for(int i = 0;i < s.length();i++) { + if (s[i]!=' ') { + arr[(int)s[i] - 97] = 1; + } + } + for (int i = 0;i < 26;i++) + if (arr[i]==0) + return false; + return true; +} + +int main() +{ + string s = "The quick brown fox jumps over the lazy dog"; + if (checkPangram(s)) + cout << "Given string is Pangram"; + else + cout << "Given string is not Pangram"; + return 0; +} diff --git a/algorithms/strings/permutations_of_string.cpp b/algorithms/strings/permutations_of_string.cpp new file mode 100644 index 00000000..40546409 --- /dev/null +++ b/algorithms/strings/permutations_of_string.cpp @@ -0,0 +1,81 @@ +// +// C program to print all permutations with repetition +// of characters +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +#include +#include + +/* Following function is used by the library qsort() function + to sort an array of chars */ +int compare(const void *a, const void *b); + +/* The main function that recursively prints all repeated + permutations of the given string. It uses data[] to store all + permutations one by one */ +void allLexicographicRecur(char *str, char *data, int last, int index) +{ + int i, len = strlen(str); + + // One by one fix all characters at the given index and recur for + // the/ subsequent indexes + for (i = 0; i < len; i++) + { + // Fix the ith character at index and if this is not the last + // index then recursively call for higher indexes + data[index] = str[i]; + + // If this is the last index then print the string stored in + // data[] + if (index == last) + printf("%s\n", data); + else // Recur for higher indexes + allLexicographicRecur(str, data, last, index + 1); + } +} + +/* This function sorts input string, allocate memory for data (needed + for allLexicographicRecur()) and calls allLexicographicRecur() for + printing all permutations */ +void allLexicographic(char *str) +{ + int len = strlen(str); + + // Create a temp array that will be used by allLexicographicRecur() + char *data = (char *)malloc(sizeof(char) * (len + 1)); + data[len] = '\0'; + + // Sort the input string so that we get all output strings in + // lexicographically sorted order + qsort(str, len, sizeof(char), compare); + + // Now print all permutaions + allLexicographicRecur(str, data, len - 1, 0); + + // Free data to avoid memory leak + free(data); +} + +// Needed for library function qsort() +int compare(const void *a, const void *b) +{ + return (*(char *)a - *(char *)b); +} + +// Driver program to test above functions +int main() +{ + char str[] = ""; //Enter character array + printf("All permutations with repetition of %s are: \n", + str); + allLexicographic(str); + return 0; +} diff --git a/algorithms/strings/print_duplicate_string.cpp b/algorithms/strings/print_duplicate_string.cpp new file mode 100644 index 00000000..46eacf66 --- /dev/null +++ b/algorithms/strings/print_duplicate_string.cpp @@ -0,0 +1,47 @@ +// +// C++ program to count all duplicates from string using hashing +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +#include +#define NO_OF_CHARS 256 + +/* Fills count array with frequency of characters */ +void fillCharCounts(char *str, int *count) +{ + int i; + for (i = 0; *(str + i); i++) + count[*(str + i)]++; +} + +/* Print duplicates present in the passed string */ +void printDups(char *str) +{ + // Create an array of size 256 and fill count of every character in it + int *count = (int *)calloc(NO_OF_CHARS, sizeof(int)); + fillCharCounts(str, count); + + // Print characters having count more than 0 + int i; + for (i = 0; i < NO_OF_CHARS; i++) + if (count[i] > 1) + printf("%c, count = %d \n", i, count[i]); + + free(count); +} + +/* Driver program to test to pront printDups*/ +int main() +{ + char str[] = ""; //Enter string here + printDups(str); + getchar(); + return 0; +} diff --git a/algorithms/strings/rabin_carp.cpp b/algorithms/strings/rabin_carp.cpp new file mode 100644 index 00000000..8a853caa --- /dev/null +++ b/algorithms/strings/rabin_carp.cpp @@ -0,0 +1,71 @@ +/** + * C++ Program to Implement Rabin-Karp Algorithm + */ + +#include +#include +#include +#include + +using namespace std; +#define d 256 + +/** + * Ssearch a substring in a string + */ + +void search(char *pat, char *txt, int q) +{ + int M = strlen(pat); + int N = strlen(txt); + int i, j; + int p = 0; + int t = 0; + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) + { + p = (d * p + pat[i]) % q; + t = (d * t + txt[i]) % q; + } + + for (i = 0; i <= N - M; i++) + { + if (p == t) + { + for (j = 0; j < M; j++) + { + if (txt[i + j] != pat[j]) + break; + } + + if (j == M) + { + cout << "Pattern found at index: " << i << endl; + } + } + + if (i < N - M) + + { + t = (d * (t - txt[i] * h) + txt[i + M]) % q; + + if (t < 0) + t = (t + q); + } + } +} + +int main() +{ + + char *txt = "This is a sample Testcase"; + char *pat = "sam"; + int q = 101; + + search(pat, txt, q); + return 0; +} diff --git a/algorithms/strings/rabin_karp.cpp b/algorithms/strings/rabin_karp.cpp new file mode 100644 index 00000000..d12a1259 --- /dev/null +++ b/algorithms/strings/rabin_karp.cpp @@ -0,0 +1,87 @@ +// +// Following program is a C implementation of Rabin Karp +// Algorithm given in the CLRS book +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +#include + +// d is the number of characters in the input alphabet +#define d 256 + +/* pat -> pattern + txt -> text + q -> A prime number +*/ +void search(char pat[], char txt[], int q) +{ + int M = strlen(pat); + int N = strlen(txt); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; + + // The value of h would be "pow(d, M-1)%q" + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + // Calculate the hash value of pattern and first + // window of text + for (i = 0; i < M; i++) + { + p = (d * p + pat[i]) % q; + t = (d * t + txt[i]) % q; + } + + // Slide the pattern over text one by one + for (i = 0; i <= N - M; i++) + { + + // Check the hash values of current window of text + // and pattern. If the hash values match then only + // check for characters on by one + if (p == t) + { + /* Check for characters one by one */ + for (j = 0; j < M; j++) + { + if (txt[i + j] != pat[j]) + break; + } + + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] + if (j == M) + printf("Pattern found at index %d \n", i); + } + + // Calculate hash value for next window of text: Remove + // leading digit, add trailing digit + if (i < N - M) + { + t = (d * (t - txt[i] * h) + txt[i + M]) % q; + + // We might get negative value of t, converting it + // to positive + if (t < 0) + t = (t + q); + } + } +} + +/* Driver program to test above function */ +int main() +{ + char txt[] = ""; //Enter the entire text here + char pat[] = ""; //Enter the string to be searched here + int q = 101; // A prime number + search(pat, txt, q); + return 0; +} diff --git a/algorithms/strings/remove_adjacent_duplicates.cpp b/algorithms/strings/remove_adjacent_duplicates.cpp new file mode 100644 index 00000000..e28ead88 --- /dev/null +++ b/algorithms/strings/remove_adjacent_duplicates.cpp @@ -0,0 +1,75 @@ +// +// C/C++ program to remove all adjacent duplicates from a string +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +#include +using namespace std; + +// Recursively removes adjacent duplicates from str and returns +// new string. las_removed is a pointer to last_removed character +char *removeUtil(char *str, char *last_removed) +{ + // If length of string is 1 or 0 + if (str[0] == '\0' || str[1] == '\0') + return str; + + // Remove leftmost same characters and recur for remaining + // string + if (str[0] == str[1]) + { + *last_removed = str[0]; + while (str[1] && str[0] == str[1]) + str++; + str++; + return removeUtil(str, last_removed); + } + + // At this point, the first character is definiotely different + // from its adjacent. Ignore first character and recursively + // remove characters from remaining string + char *rem_str = removeUtil(str + 1, last_removed); + + // Check if the first character of the rem_string matches with + // the first character of the original string + if (rem_str[0] && rem_str[0] == str[0]) + { + *last_removed = str[0]; + return (rem_str + 1); // Remove first character + } + + // If remaining string becomes empty and last removed character + // is same as first character of original string. This is needed + // for a string like "acbbcddc" + if (rem_str[0] == '\0' && *last_removed == str[0]) + return rem_str; + + // If the two first characters of str and rem_str don't match, + // append first character of str before the first character of + // rem_str. + rem_str--; + rem_str[0] = str[0]; + return rem_str; +} + +char *remove(char *str) +{ + char last_removed = '\0'; + return removeUtil(str, &last_removed); +} + +// Driver program to test above functions +int main() +{ + char str1[] = ""; //Enter string + cout << remove(str1) << endl; + + return 0; +} diff --git a/algorithms/strings/remove_duplicates.cpp b/algorithms/strings/remove_duplicates.cpp new file mode 100644 index 00000000..4a56d437 --- /dev/null +++ b/algorithms/strings/remove_duplicates.cpp @@ -0,0 +1,48 @@ +// +// CPP program to remove duplicate character +// from character array and print in sorted +// order +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include +using namespace std; + +char *removeDuplicate(char str[], int n) +{ + // Used as index in the modified string + int index = 0; + + // Traverse through all characters + for (int i = 0; i < n; i++) + { + + // Check if str[i] is present before it + int j; + for (j = 0; j < i; j++) + if (str[i] == str[j]) + break; + + // If not present, then add it to + // result. + if (j == i) + str[index++] = str[i]; + } + + return str; +} + +// Driver code +int main() +{ + char str[] = ""; //Enter string here + int n = sizeof(str) / sizeof(str[0]); + cout << removeDuplicate(str, n); + return 0; +} diff --git a/algorithms/strings/reverse_string.cpp b/algorithms/strings/reverse_string.cpp new file mode 100644 index 00000000..f2eeb14e --- /dev/null +++ b/algorithms/strings/reverse_string.cpp @@ -0,0 +1,66 @@ +// +// Reverse String in C++ +// +// The All ▲lgorithms Project +// +// https://allalgorithms.com/strings +// https://github.com/allalgorithms/cpp +// +// Contributed by: Tushar Kanakagiri +// Github: @tusharkanakagiri +// +#include + +/* function prototype for utility function to + reverse a string from begin to end */ +void reverse(char *begin, char *end); + +/*Function to reverse words*/ +void reverseWords(char *s) +{ + char *word_begin = s; + char *temp = s; /* temp is for word boundry */ + + /*STEP 1 of the above algorithm */ + while (*temp) + { + temp++; + if (*temp == '\0') + { + reverse(word_begin, temp - 1); + } + else if (*temp == ' ') + { + reverse(word_begin, temp - 1); + word_begin = temp + 1; + } + } /* End of while */ + + /*STEP 2 of the above algorithm */ + reverse(s, temp - 1); +} + +/* UTILITY FUNCTIONS */ +/*Function to reverse any sequence starting with pointer + begin and ending with pointer end */ +void reverse(char *begin, char *end) +{ + char temp; + while (begin < end) + { + temp = *begin; + *begin++ = *end; + *end-- = temp; + } +} + +/* Driver function to test above functions */ +int main() +{ + char s[] = ""; //Enter string here + char *temp = s; + reverseWords(s); + printf("%s", s); + getchar(); + return 0; +} diff --git a/algorithms/strings/vowel_counter.cpp b/algorithms/strings/vowel_counter.cpp new file mode 100644 index 00000000..4dca0389 --- /dev/null +++ b/algorithms/strings/vowel_counter.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +int main() { + string s; + int cnt; + cout << "Enter the string: "; + cin >> s; + + cnt = 0; + for ( char ch : s ) { + switch ( ch ) { + case 'a': + case 'e': + case 'i': + case 'o': + case 'u': + cnt++; + break; + default: + break; + } + } + + cout << "The string has " << cnt << " vowels.\n"; + + return 0; +} diff --git a/algorithms/strings/z_algorithm.cpp b/algorithms/strings/z_algorithm.cpp new file mode 100644 index 00000000..2d5e69b9 --- /dev/null +++ b/algorithms/strings/z_algorithm.cpp @@ -0,0 +1,81 @@ +/** + * C++ Program to Implement Z-Algorithm + */ + +#include +#include +#include + +using namespace std; + +bool zAlgorithm(string pattern, string target) +{ + string s = pattern + '$' + target; + int n = s.length(); + vector z(n, 0); + int goal = pattern.length(); + int r = 0, l = 0, i; + + for (int k = 1; k < n; k++) + { + if (k > r) + { + for (i = k; i < n && s[i] == s[i - k]; i++) + ; + if (i > k) + { + z[k] = i - k; + l = k; + r = i - 1; + } + } + else + { + int kt = k - l, b = r - k + 1; + + if (z[kt] > b) + { + for (i = r + 1; i < n && s[i] == s[i - k]; i++) + ; + z[k] = i - k; + l = k; + r = i - 1; + } + } + + if (z[k] == goal) + return true; + } + + return false; +} + +int main() +{ + string tar = "This is a sample Testcase"; + string pat = "case"; + + if (zAlgorithm(pat, tar)) + { + cout << "'" << pat << "' found in string '" << tar << "'" << endl; + } + + else + { + cout << "'" << pat << "' not found in string '" << tar << "'" << endl; + } + + pat = "Kavya"; + + if (zAlgorithm(pat, tar)) + { + cout << "'" << pat << "' found in string '" << tar << "'" << endl; + } + + else + { + cout << "'" << pat << "' not found in string '" << tar << "'" << endl; + } + + return 0; +} diff --git a/data-structures/Inbuilt_Pair.cpp b/data-structures/Inbuilt_Pair.cpp new file mode 100644 index 00000000..e86a32e4 --- /dev/null +++ b/data-structures/Inbuilt_Pair.cpp @@ -0,0 +1,28 @@ +/* +Pair is a container class in CPP defined in header file. It consists of two elements. + +You can access the first element as 'first' and second element as 'second'. They both can be of any data type. (This class is made using templates) + +We can use the pair class where we need to store two properties like when finding diameter of a binary tree. + +This is the inbuilt version, we can create our own version too. + +*/ +#include +using namespace std; + +int main() { + + pair p ; + + p.first = 100; + p.second = 'G' ; + + cout << p.first << " " ; + cout << p.second << endl ; + + return 0; + +} + + diff --git a/data-structures/IncrementLL.cpp b/data-structures/IncrementLL.cpp new file mode 100644 index 00000000..7cbf14dc --- /dev/null +++ b/data-structures/IncrementLL.cpp @@ -0,0 +1,127 @@ +#include +using namespace std; + +/* + +Increment Linked List by 1 + +This program increments the list by 1. The program takes input with one space and when entered -1 at the end, it stops taking more inputs +For example + +Input: +3 1 -1 + +Output: +3 2 + +Input2: +9 9 -1 + +Output2: +1 0 0 + +Idea is to reverse a LL, made some calculations and reverse it again to obtain the answer. + +*/ + +class Node { + public: + int data; + Node *next; + + Node(int data) { + this->data = data; + this->next = NULL; + } +}; + +Node* takeInput() { + Node* head = NULL; + Node* prev = NULL; + int d; + cin >> d; + + while(d != -1) { + Node* newnode = new Node(d); + if(head == NULL) { + head = newnode; + prev = head; + } + else { + prev->next = newnode; + prev = newnode; + } + cin >> d; + } + return head; +} + +Node* reverseLL(Node* head) { + Node* curr = head; + Node* prev = NULL; + while(curr != NULL) { + if(prev == NULL) { + prev = curr; + curr = curr->next; + prev->next = NULL; + } + else { + Node* var = curr; + curr = curr->next; + var->next = prev; + prev = var; + } + } + return prev; +} + +void print(Node* head) { + Node* temp = head; + while(temp != NULL) { + cout<data<<" "; + temp = temp->next; + } +} + +int main() { + Node* head = takeInput(); + Node *newHead = NULL; + newHead = reverseLL(head); + + bool carry = false; + + Node *temp = newHead; + Node *prev = NULL; + int digit = temp->data + 1; + while(temp!= NULL) { + if(carry) { + int data = temp->data + 1; + if(data >= 10) { + temp->data = (data%10); + carry = true; + } + else { + temp->data = data; + carry = false; + break; + } + } + else if(digit>=10) { + temp->data = (digit%10); + carry = true; + } + else if(digit<10) { + temp->data = temp->data + 1; + break; + } + prev = temp; + temp = temp->next; + } + if(carry) { + Node* newNode = new Node(1); + prev->next = newNode; + newNode->next = NULL; + } + head = reverseLL(newHead); + print(head); +} diff --git a/data-structures/Priority_Queues/CheckMaxHeap.cpp b/data-structures/Priority_Queues/CheckMaxHeap.cpp new file mode 100644 index 00000000..bb362175 --- /dev/null +++ b/data-structures/Priority_Queues/CheckMaxHeap.cpp @@ -0,0 +1,63 @@ +/* + +Problem: +Given an array of integers, check whether it represents max-heap or not. +Return true or false. + + +*/ + + +#include +using namespace std; + +bool checkMaxHeap(int arr[], int n){ + + int loopSize = ((n-1)-1)/2; + int j = 0; + while(j <= loopSize) { + int parent = j; + int left = (2*parent)+1; + int right = (2*parent)+2; + + bool ok = false; + if(left < n) { + if(arr[left] <= arr[parent]) + ok = true; + else { + return false; + } + } + + if(right < n) { + if(arr[right] <= arr[parent]) + ok = true; + else { + return false; + } + } + j++; + } + return true; +} + +int main() { + int n; + cin>>n; + int *arr = new int[n]; + for(int i=0; i> arr[i]; + } + bool ans = checkMaxHeap(arr, n); + if(ans){ + cout << "true" << endl; + } + else{ + cout << "false" << endl; + } + + delete [] arr; +} + + + diff --git a/data-structures/Priority_Queues/kthLargestUsingPriorityQueue.cpp b/data-structures/Priority_Queues/kthLargestUsingPriorityQueue.cpp new file mode 100644 index 00000000..582d0118 --- /dev/null +++ b/data-structures/Priority_Queues/kthLargestUsingPriorityQueue.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +/* + +Given an array A of random integers and an integer k, find and return the kth largest element in the array. + +*/ + +int kthLargest (vector arr, int n, int k){ + + priority_queue, greater> pq; + + for(int i = 0; i < k; i++) { + pq.push(arr[i]); + } + + for(int i = k; i < n; i++) { + int val = pq.top(); + if(arr[i] > val) { + pq.pop(); + pq.push(arr[i]); + } + } + + return pq.top(); + +} + +int main() { + int n, k, s; + vector arr; + cin >> n; + + for (int i = 0; i < n; i++) { + cin >> s; + arr.push_back(s); + } + + cin >> k; + cout << kthLargest(arr, n, k) << endl; +} + +// Time complexity of this solution is O(nlogn). diff --git a/data-structures/avl.cpp b/data-structures/avl.cpp new file mode 100644 index 00000000..3be62efe --- /dev/null +++ b/data-structures/avl.cpp @@ -0,0 +1,175 @@ +#include +#include +using namespace std; + +struct node +{ + int data, height; + node *left, *right; +}; + +class avl +{ + node* root=NULL; +public: + int height(node* root){ + if(root) + return root->height; + return 0; + } + node* rotateLeft(node* root){ + node* newroot = root->right; + root->right = newroot->left; + newroot->left = root; + return newroot; + } + node* rotateRight(node* root){ + node* newroot = root->left; + root->left = newroot->right; + newroot->right = root; + return newroot; + } + void insert(int x){ + this->root = insert(this->root, x); + } + node* insert(node* root, int x){ + if(root==NULL){ + root = new node; + root->data = x; + root->height = 1; + root->left = NULL; + root->right = NULL; + return root; + } + if(x < root->data) + root->left = insert(root->left,x); + else if(x > root->data) + root->right = insert(root->right,x); + else + return root; + + int lh = height(root->left), rh = height(root->right); + root->height = 1 + max(lh,rh); + + lh -= rh; + if(lh>1){ + if(x > root->left->data) + root->left = rotateLeft(root->left); + return rotateRight(root); + } + else if(lh<-1){ + if(x < root->right->data) + root->right = rotateRight(root->right); + return rotateLeft(root); + } + return root; + } + int minValue(node* root){ + while(root->left) + root = root->left; + return root->data; + } + void remove(int x){ + this->root = remove(this->root, x); + } + node* remove(node* root, int x){ + if(root == NULL) + return NULL; + if(x < root->data) + root->left = remove(root->left, x); + else if(x > root->data) + root->right = remove(root->right, x); + else{ + if(root->left == NULL && root->right == NULL){ + delete root; + return NULL; + } + else if(root->right == NULL){ + node* temp = root; + root = root->left; + delete temp; + return root; + } + else if(root->left == NULL){ + node* temp = root; + root = root->right; + delete temp; + return root; + } + else{ + root->data = minValue(root->right); + root->right = remove(root->right, root->data); + } + } + + int lh = height(root->left), rh = height(root->right); + root->height = 1 + max(lh,rh); + + lh -= rh; + if(lh>1){ + if(x > root->left->data) + root->left = rotateLeft(root->left); + return rotateRight(root); + } + else if(lh<-1){ + if(x < root->right->data) + root->right = rotateRight(root->right); + return rotateLeft(root); + } + return root; + } + void printLevel(){ + printLevel(this->root); + } + void printLevel(node* root){ + if(root){ + queue q; + q.push(root); + q.push(NULL); + node* temp; + while(!q.empty()){ + temp = q.front(); + q.pop(); + if(temp){ + cout << temp->data << " "; + if(temp->left) + q.push(temp->left); + if(temp->right) + q.push(temp->right); + } + else if(q.front()){ + cout << endl; + q.push(NULL); + } + } + } + } + void print(){ + print(this->root); + } + void print(node* root){ + if(root){ + print(root->left); + cout << root->data << " "; + print(root->right); + } + } +}; + +int main() +{ + avl a; + a.insert(5); + a.insert(6); + a.insert(7); + a.insert(8); + a.insert(9); + a.insert(4); + a.printLevel(); + a.remove(7); + a.remove(5); + cout << endl; + a.printLevel(); + + return 0; +} \ No newline at end of file diff --git a/data-structures/binaryTreeMinTimeBurn.cpp b/data-structures/binaryTreeMinTimeBurn.cpp new file mode 100644 index 00000000..a039c389 --- /dev/null +++ b/data-structures/binaryTreeMinTimeBurn.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +class Node{ +public: + int data; + Node *left, *right; + Node(int x){ + this->data = x; + this->left = this->right = NULL; + } +}; + + +pair minTime(Node* node, int *result){ + if(node->left == NULL && node->right == NULL) + return {0,1}; + cout << "Node " << node->data << endl; + pair ansl={0,-1},ansr={0,-1}; + if(node->left) + ansl = minTime(node->left,result); + if(node->right) + ansr = minTime(node->right,result); + if(ansl.second == -1) + return {ansr.first+1,ansr.second+1}; + if(ansr.second == -1) + return {ansl.first+1,ansl.second+1}; + if(ansl.firstleft = new Node(1); + root->right = new Node(2); + root->left->left = new Node(3); + root->left->right = new Node(4); + root->right->left = new Node(5); + root->right->right = new Node(6); + root->left->left->left = new Node(10); + root->left->right->left = new Node(9); + root->right->right->left = new Node(7); + root->right->right->right = new Node(8); + + cout << "Exec Start" << endl; + int *result = new int; + minTime(root,result); + cout << *result << endl; + + return 0; +} \ No newline at end of file diff --git a/data-structures/linkedList.cpp b/data-structures/linkedList.cpp new file mode 100644 index 00000000..33ef17bc --- /dev/null +++ b/data-structures/linkedList.cpp @@ -0,0 +1,56 @@ +#include + +using namespace std; + +class Node { +public: + int data; + Node* next; + + Node(int data) { + this->data = data; + this->next = NULL; + } +}; + +class LinkedList { +public: + Node* head; + + LinkedList() { + this->head = NULL; + } + + void addNode(int data) { + Node* newNode = new Node(data); + if (this->head == NULL) { + this->head = newNode; + return; + } + Node* currentNode = this->head; + while (currentNode->next != NULL) { + currentNode = currentNode->next; + } + currentNode->next = newNode; + } + + void printList() { + Node* currentNode = this->head; + while (currentNode != NULL) { + cout << currentNode->data << " "; + currentNode = currentNode->next; + } + cout << endl; + } +}; + +int main() { + LinkedList list; + list.addNode(1); + list.addNode(2); + list.addNode(3); + list.addNode(4); + list.addNode(5); + list.printList(); + return 0; +} \ No newline at end of file diff --git a/dynamic-programming/edit-distance.cpp b/dynamic-programming/edit-distance.cpp deleted file mode 100644 index 09190183..00000000 --- a/dynamic-programming/edit-distance.cpp +++ /dev/null @@ -1,60 +0,0 @@ - -// A Dynamic Programming based C++ program to find minimum -// number operations to convert str1 to str2 -#include -using namespace std; - -// Utility function to find the minimum of three numbers -int min(int x, int y, int z) -{ - return min(min(x, y), z); -} - -int editDistDP(string str1, string str2, int m, int n) -{ - // Create a table to store results of 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 first string is empty, only option is to - // isnert all characters of second string - if (i==0) - dp[i][j] = j; // Min. operations = j - - // If second string is empty, only option is to - // remove all characters of second string - else if (j==0) - dp[i][j] = i; // Min. operations = i - - // If last characters are same, ignore last char - // and recur for remaining string - else if (str1[i-1] == str2[j-1]) - dp[i][j] = dp[i-1][j-1]; - - // If the last character is different, consider all - // possibilities and find the minimum - 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]; -} - -// Driver program -int main() -{ - // your code goes here - string str1 = "sunday"; - string str2 = "saturday"; - - cout << editDistDP(str1, str2, str1.length(), str2.length()); - - return 0; -} diff --git a/dynamic-programming/knapsack.cpp b/dynamic-programming/knapsack.cpp deleted file mode 100644 index dc0c188a..00000000 --- a/dynamic-programming/knapsack.cpp +++ /dev/null @@ -1,39 +0,0 @@ - -// A Dynamic Programming based solution for 0-1 Knapsack problem -#include - -// A utility function that returns maximum of two integers -int max(int a, int b) { return (a > b)? a : b; } - -// Returns the maximum value that can be put in a knapsack of capacity W -int knapSack(int W, int wt[], int val[], int n) -{ - int i, w; - int K[n+1][W+1]; - - // Build table K[][] in bottom up manner - for (i = 0; i <= n; i++) - { - for (w = 0; w <= W; w++) - { - if (i==0 || w==0) - K[i][w] = 0; - else if (wt[i-1] <= w) - K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); - else - K[i][w] = K[i-1][w]; - } - } - - return K[n][W]; -} - -int main() -{ - int val[] = {60, 100, 120}; - int wt[] = {10, 20, 30}; - int W = 50; - int n = sizeof(val)/sizeof(val[0]); - cout << knapSack(W, wt, val, n); - return 0; -} diff --git a/dynamic-programming/lcs.cpp b/dynamic-programming/lcs.cpp deleted file mode 100644 index bad7d889..00000000 --- a/dynamic-programming/lcs.cpp +++ /dev/null @@ -1,52 +0,0 @@ - -/* Dynamic Programming C/C++ implementation of LCS problem */ -#include - -int max(int a, int b); - -/* Returns length of LCS for X[0..m-1], Y[0..n-1] */ -int lcs( char *X, char *Y, int m, int n ) -{ - int L[m+1][n+1]; - int i, j; - - /* Following steps build L[m+1][n+1] in bottom up fashion. Note - that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ - for (i=0; i<=m; i++) - { - for (j=0; j<=n; j++) - { - if (i == 0 || j == 0) - L[i][j] = 0; - - else if (X[i-1] == Y[j-1]) - L[i][j] = L[i-1][j-1] + 1; - - else - L[i][j] = max(L[i-1][j], L[i][j-1]); - } - } - - /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ - return L[m][n]; -} - -/* Utility function to get max of 2 integers */ -int max(int a, int b) -{ - return (a > b)? a : b; -} - -/* Driver program to test above function */ -int main() -{ - char X[] = "AGGTAB"; - char Y[] = "GXTXAYB"; - - int m = strlen(X); - int n = strlen(Y); - - cout << "Length of LCS is " << lcs( X, Y, m, n ) ; - - return 0; -} diff --git a/dynamic-programming/longest_path.cpp b/dynamic-programming/longest_path.cpp deleted file mode 100644 index 7d458d73..00000000 --- a/dynamic-programming/longest_path.cpp +++ /dev/null @@ -1,70 +0,0 @@ - -#include -#define n 3 -using namespace std; - -// Returns length of the longest path beginning with mat[i][j]. -// This function mainly uses lookup table dp[n][n] -int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]) -{ - // Base case - if (i<0 || i>=n || j<0 || j>=n) - return 0; - - // If this subproblem is already solved - if (dp[i][j] != -1) - return dp[i][j]; - - // Since all numbers are unique and in range from 1 to n*n, - // there is atmost one possible direction from any cell - if (j0 && (mat[i][j] +1 == mat[i][j-1])) - return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp); - - if (i>0 && (mat[i][j] +1 == mat[i-1][j])) - return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp); - - if (i -using namespace std; - -int printCountDP(int dist) -{ - int count[dist+1]; - - // Initialize base values. There is one way to cover 0 and 1 - // distances and two ways to cover 2 distance - count[0] = 1, count[1] = 1, count[2] = 2; - - // Fill the count array in bottom up manner - for (int i=3; i<=dist; i++) - count[i] = count[i-1] + count[i-2] + count[i-3]; - - return count[dist]; -} - -// driver program -int main() -{ - int dist = 4; - cout << printCountDP(dist); - return 0; -} diff --git a/graphs/bellman_ford.cpp b/graphs/bellman_ford.cpp deleted file mode 100644 index 340cc6a4..00000000 --- a/graphs/bellman_ford.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include - -struct Edge -{ - int src, dest, weight; -}; - -struct Graph -{ - // V-> Number of vertices, E-> Number of edges - int V, E; - // graph is represented as an array of edges. - struct Edge* edge; -}; - -struct Graph* createGraph(int V, int E) -{ - struct Graph* graph = new Graph; - graph->V = V; - graph->E = E; - graph->edge = new Edge[E]; - return graph; -} - -void printArr(int dist[], int n) -{ - printf("Vertex Distance from Source\n"); - for (int i = 0; i < n; ++i) - printf("%d \t\t %d\n", i, dist[i]); -} - -void BellmanFord(struct Graph* graph, int src) -{ - int V = graph->V; - int E = graph->E; - int dist[V]; - - // Step 1: Initialize distances from src to all other vertices - // as INFINITE - for (int i = 0; i < V; i++) - dist[i] = INT_MAX; - dist[src] = 0; - - // Step 2: Relax all edges |V| - 1 times. A simple shortest - // path from src to any other vertex can have at-most |V| - 1 - // edges - for (int i = 1; i <= V-1; i++) - { - for (int j = 0; j < E; j++) - { - int u = graph->edge[j].src; - int v = graph->edge[j].dest; - int weight = graph->edge[j].weight; - if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) - dist[v] = dist[u] + weight; - } - } - - // Step 3: check for negative-weight cycles. The above step - // guarantees shortest distances if graph doesn't contain - // negative weight cycle. If we get a shorter path, then there - // is a cycle. - for (int i = 0; i < E; i++) - { - int u = graph->edge[i].src; - int v = graph->edge[i].dest; - int weight = graph->edge[i].weight; - if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) - printf("Graph contains negative weight cycle"); - } - printArr(dist, V); - return; -} -int main() -{ - /* Sample graph */ - int V = 5; - int E = 8; - struct Graph* graph = createGraph(V, E); - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - graph->edge[0].weight = -1; - graph->edge[1].src = 0; - graph->edge[1].dest = 2; - graph->edge[1].weight = 4; - graph->edge[2].src = 1; - graph->edge[2].dest = 2; - graph->edge[2].weight = 3; - graph->edge[3].src = 1; - graph->edge[3].dest = 3; - graph->edge[3].weight = 2; - graph->edge[4].src = 1; - graph->edge[4].dest = 4; - graph->edge[4].weight = 2; - graph->edge[5].src = 3; - graph->edge[5].dest = 2; - graph->edge[5].weight = 5; - graph->edge[6].src = 3; - graph->edge[6].dest = 1; - graph->edge[6].weight = 1; - graph->edge[7].src = 4; - graph->edge[7].dest = 3; - graph->edge[7].weight = -3; - BellmanFord(graph, 0); - return 0; -} diff --git a/graphs/bfs.cpp b/graphs/bfs.cpp deleted file mode 100644 index a2480464..00000000 --- a/graphs/bfs.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#include -#include - -using namespace std; - -class Graph -{ - int V; // No. of vertices - - // Pointer to an array containing adjacency - // lists - list *adj; -public: - Graph(int V); // Constructor - - // function to add an edge to graph - void addEdge(int v, int w); - - // prints BFS traversal from a given source s - void BFS(int s); -}; - -Graph::Graph(int V) -{ - this->V = V; - adj = new list[V]; -} - -void Graph::addEdge(int v, int w) -{ - adj[v].push_back(w); // Add w to v’s list. -} - -void Graph::BFS(int s) -{ - // Mark all the vertices as not visited - bool *visited = new bool[V]; - for(int i = 0; i < V; i++) - visited[i] = false; - - // Create a queue for BFS - list queue; - - // Mark the current node as visited and enqueue it - visited[s] = true; - queue.push_back(s); - - // 'i' will be used to get all adjacent - // vertices of a vertex - list::iterator i; - - while(!queue.empty()) - { - // Dequeue a vertex from queue and print it - s = queue.front(); - cout << s << " "; - queue.pop_front(); - - // Get all adjacent vertices of the dequeued - // vertex s. If a adjacent has not been visited, - // then mark it visited and enqueue it - for (i = adj[s].begin(); i != adj[s].end(); ++i) - { - if (!visited[*i]) - { - visited[*i] = true; - queue.push_back(*i); - } - } - } -} - -int main() -{ - // Sample graph - Graph g(4); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 2); - g.addEdge(2, 0); - g.addEdge(2, 3); - g.addEdge(3, 3); - cout << "Following is Breadth First Traversal " - << "(starting from vertex 2) \n"; - g.BFS(2); - return 0; -} diff --git a/graphs/dfs.cpp b/graphs/dfs.cpp deleted file mode 100644 index e4b5c69e..00000000 --- a/graphs/dfs.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include -#include -using namespace std; - -// Graph class represents a directed graph -// using adjacency list representation -class Graph -{ - int V; - list *adj; - void DFSUtil(int v, bool visited[]); -public: - Graph(int V); - void addEdge(int v, int w); - void DFS(int v); -}; - -Graph::Graph(int V) -{ - this->V = V; - adj = new list[V]; -} - -void Graph::addEdge(int v, int w) -{ - adj[v].push_back(w); // Add w to v’s list. -} - -void Graph::DFSUtil(int v, bool visited[]) -{ - visited[v] = true; - cout << v << " "; - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - DFSUtil(*i, visited); -} -void Graph::DFS(int v) -{ - bool *visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - DFSUtil(v, visited); -} - -int main() -{ - Graph g(4); - g.addEdge(0, 1); - g.addEdge(0, 2); - g.addEdge(1, 2); - g.addEdge(2, 0); - g.addEdge(2, 3); - g.addEdge(3, 3); - cout << "Following is Depth First Traversal (starting from vertex 2)\n"; - g.DFS(2); - return 0; -} diff --git a/graphs/dijkstra.cpp b/graphs/dijkstra.cpp deleted file mode 100644 index 571850fb..00000000 --- a/graphs/dijkstra.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include -#include - -// Number of vertices in the graph -#define V 9 -int minDistance(int dist[], bool sptSet[]) -{ - // Initialize min value - int min = INT_MAX, min_index; - - for (int v = 0; v < V; v++) - if (sptSet[v] == false && dist[v] <= min) - min = dist[v], min_index = v; - - return min_index; -} - -void printSolution(int dist[], int n) -{ - printf("Vertex Distance from Source\n"); - for (int i = 0; i < V; i++) - printf("%d tt %d\n", i, dist[i]); -} - -void dijkstra(int graph[V][V], int src) -{ - int dist[V]; // The output array. dist[i] will hold the shortest - // distance from src to i - - bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest - // path tree or shortest distance from src to i is finalized - - // Initialize all distances as INFINITE and stpSet[] as false - for (int i = 0; i < V; i++) - dist[i] = INT_MAX, sptSet[i] = false; - - // Distance of source vertex from itself is always 0 - dist[src] = 0; - - // Find shortest path for all vertices - for (int count = 0; count < V-1; count++) - { - // Pick the minimum distance vertex from the set of vertices not - // yet processed. u is always equal to src in the first iteration. - int u = minDistance(dist, sptSet); - - // Mark the picked vertex as processed - sptSet[u] = true; - - // Update dist value of the adjacent vertices of the picked vertex. - for (int v = 0; v < V; v++) - - // Update dist[v] only if is not in sptSet, there is an edge from - // u to v, and total weight of path from src to v through u is - // smaller than current value of dist[v] - if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX - && dist[u]+graph[u][v] < dist[v]) - dist[v] = dist[u] + graph[u][v]; - } - printSolution(dist, V); -} - -int main() -{ - /* Sample graph */ - int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, - {4, 0, 8, 0, 0, 0, 0, 11, 0}, - {0, 8, 0, 7, 0, 4, 0, 0, 2}, - {0, 0, 7, 0, 9, 14, 0, 0, 0}, - {0, 0, 0, 9, 0, 10, 0, 0, 0}, - {0, 0, 4, 14, 10, 0, 2, 0, 0}, - {0, 0, 0, 0, 0, 2, 0, 1, 6}, - {8, 11, 0, 0, 0, 0, 1, 0, 7}, - {0, 0, 2, 0, 0, 0, 6, 7, 0} - }; - dijkstra(graph, 0); - return 0; -} diff --git a/graphs/floyd_warshall.cpp b/graphs/floyd_warshall.cpp deleted file mode 100644 index 2c326d10..00000000 --- a/graphs/floyd_warshall.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include - -#define V 4 // Number of vertices in the graph -#define INF 1e7 - -void printSolution(int dist[][V]); -void floydWarshall (int graph[][V]) -{ - int dist[V][V], i, j, k; - /* Initialize the solution matrix same as input graph matrix. Or - we can say the initial values of shortest distances are based - on shortest paths considering no intermediate vertex. */ - for (i = 0; i < V; i++) - for (j = 0; j < V; j++) - dist[i][j] = graph[i][j]; - /* Add all vertices one by one to the set of intermediate vertices. - ---> Before start of an iteration, we have shortest distances between all - pairs of vertices such that the shortest distances consider only the - vertices in set {0, 1, 2, .. k-1} as intermediate vertices. - ----> After the end of an iteration, vertex no. k is added to the set of - intermediate vertices and the set becomes {0, 1, 2, .. k} */ - for (k = 0; k < V; k++) - { - // Pick all vertices as source one by one - for (i = 0; i < V; i++) - { - // Pick all vertices as destination for the - // above picked source - for (j = 0; j < V; j++) - { - // If vertex k is on the shortest path from - // i to j, then update the value of dist[i][j] - if (dist[i][k] + dist[k][j] < dist[i][j]) - dist[i][j] = dist[i][k] + dist[k][j]; - } - } - } - // Print the shortest distance matrix - printSolution(dist); -} - -void printSolution(int dist[][V]) -{ - printf ("The following matrix shows the shortest distances" - " between every pair of vertices \n"); - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { - if (dist[i][j] == INF) - printf("%7s", "INF"); - else - printf ("%7d", dist[i][j]); - } - printf("\n"); - } -} - -int main() -{ - // Sample graph - int graph[V][V] = { {0, 5, INF, 10}, - {INF, 0, 3, INF}, - {INF, INF, 0, 1}, - {INF, INF, INF, 0} - }; - floydWarshall(graph); - return 0; -} diff --git a/LICENSE b/license similarity index 86% rename from LICENSE rename to license index 3ced2b5e..559a12bf 100644 --- a/LICENSE +++ b/license @@ -1,6 +1,7 @@ MIT License -Copyright (c) 2018 Abraham Hernandez (abraham@abranhe.com) +Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) +Copyright (c) 2018 Carlos Abraham (abranhe.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +19,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/math/euclids_gcd_algo.cpp b/math/euclids_gcd_algo.cpp deleted file mode 100644 index 4ef51686..00000000 --- a/math/euclids_gcd_algo.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// C++ program to demonstrate Basic Euclidean Algorithm -// Author Bharat Reddy - -#include -using namespace std; - - -int gcd(int a, int b) -{ - if (a == 0) - return b; - return gcd(b % a, a); -} - -int main() -{ - int a,b; - cout<<"Enter 2 numbers : "; - cin>>a>>b; - int g_c_d = gcd(a,b); - cout<<"GCD is < -using namespace std; - -int gcd(int a, int b) -{ - if (a == 0) - return b; - return gcd(b % a, a); -} - - -int findGCD(int arr[], int n) -{ - int result = arr[0]; - for (int i = 1; i < n; i++) - result = gcd(arr[i], result); - - return result; -} - -int main() -{ - int n; - cout<<"Enter size of array : "; - cin>>n; - int a[n]; - cout<<"Enter elements of array"<>a[i]; - cout << findGCD(a, n) << endl; - return 0; -} \ No newline at end of file diff --git a/math/lcm_of_array.cpp b/math/lcm_of_array.cpp deleted file mode 100644 index a59439fb..00000000 --- a/math/lcm_of_array.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// C++ program to find LCM of n elements -// Author Bharat Reddy - -#include -using namespace std; - -typedef long long int ll; - - -int gcd(int a, int b) -{ - if (b == 0) - return a; - return gcd(b, a % b); -} - -// Returns LCM of array elements -ll findlcm(int arr[], int n) -{ - - ll ans = arr[0]; - - for (int i = 1; i < n; i++) - ans = (((arr[i] * ans)) / - (gcd(arr[i], ans))); - - return ans; -} - -int main() -{ - int n; - cout<<"Enter size of array : "; - cin>>n; - int a[n]; - cout<<"Enter elements of array"<>a[i]; - printf("%lld\n", findlcm(a, n)); - return 0; -} \ No newline at end of file diff --git a/math/lucky_numbers.cpp b/math/lucky_numbers.cpp deleted file mode 100644 index 351f43f5..00000000 --- a/math/lucky_numbers.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// Lucky number implementation -// Carlos Abraham Hernandez -// algorithms.abranhe.com/math/lucky-numbers - -#include -#define bool int - -/* Returns 1 if n is a lucky no. ohterwise returns 0*/ -bool isLucky(int n) -{ - static int counter = 2; - - /*variable next_position is just for readability of - the program we can remove it and use n only */ - int next_position = n; - if(counter > n) - return 1; - if(n%counter == 0) - return 0; - - /*calculate next position of input no*/ - next_position -= next_position/counter; - - counter++; - return isLucky(next_position); -} - -/*Driver function to test above function*/ -int main() -{ - int x = 7; - if( isLucky(x) ) - printf("%d is a lucky number.", x); - else - printf("%d is not a lucky number.", x); - getchar(); -} diff --git a/readme.md b/readme.md new file mode 100644 index 00000000..dd64172d --- /dev/null +++ b/readme.md @@ -0,0 +1,416 @@ +We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) + +
+
+
+
+
+ Algorithms Logo +
+
+
+
+
+
+ +

+ What is an algorithm?    + Contributing    + Stickers & T-Shirts +

+ + +

+ + Twitter +    + + Instagram +    + + Github +    +

+ +
+

+ Huge collection of All ▲lgorithms implemented in multiple languages +

+
+ + + + + + +
+ +## See + +- [What is an algorithm](#what-is-an-algorithm) +- [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) +- [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) +- [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) +- [Twitter](https://twitter.com/AllAlgorithms) +- [Instagram](https://instagram.com/AllAlgorithms) +- [Algorithms Categories](#categories) +- [Maintainers](#maintainers) +- [License](#license) + + +## What is an algorithm? + +Informally, an algorithm is any well-defined computational procedure that takes +some value, or set of values, as input and produces some value, or set of values, as +output. An algorithm is thus a sequence of computational steps that transform the +input into the output. + +An algorithm should have three important characteristics to be considered valid: + +- **It should be finite**: If your algorithm never ends trying to solve the problem +it was designed to solve then it is useless +- **It should have well defined instructions**: Each step of the algorithm has to +be precisely defined; the instructions should be unambiguously specified for each case. +- **It should be effective**: The algorithm should solve the problem it was designed +to solve. And it should be possible to demonstrate that the algorithm converges with +just a paper and pencil. + +## Categories + +> Structure of The All ▲lgoritms project + +- [Artificial Intelligence](#artificial-intelligence) +- [Backtracking](#backtracking) +- [Bit Manipulation](#bit-manipulation) +- [Cellular Automaton](#cellular-automaton) +- [Ciphers](#ciphers) +- [Computational Geometry](#computational-geometry) +- [Cryptography](#cryptography) +- [Data Structures](#data-structures) +- [Divide and conquer](#divide-and-conquer) +- [Dynamic Programming](#dynamic-programming) +- [Gaming Theory](#gaming-theory) +- [Graphs](#graphs) +- [Greedy Algorithms](#greedy-algorithms) +- [Math](#math) +- [Networking](#networking) +- [Numerical Analysis](#numerical-analysis) +- [Operating system](#operating-system) +- [Randomized Algorithms](#randomized-algorithms) +- [Searches](#searches) +- [Selections Algorithms](#selections-algorithms) +- [Sorting](#sorting) +- [Strings](#strings) +- [Online Challenges](#online-challenges) +- [Others](#others) + +## [Artificial Intelligence](artificial-intelligence) + +- [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) +- [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) +- [Linear Regression](https://allalgorithms.com/docs/linear-regression) +- [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) +- [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) +- [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) +- [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) +- [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) +- [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) +- [Decision Tree](https://allalgorithms.com/docs/decision-tree) +- [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) +- [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) +- [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) +- [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) +- [Image Processing](https://allalgorithms.com/docs/image-processing) +- [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) +- [K Means](https://allalgorithms.com/docs/k-means) +- [Minimax](https://allalgorithms.com/docs/minimax) +- [Native Bayes](https://allalgorithms.com/docs/native-bayes) +- [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) +- [Neutral Network](https://allalgorithms.com/docs/neutral-network) +- [Perceptron](https://allalgorithms.com/docs/perceptron) +- [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) +- [Q Learing](https://allalgorithms.com/docs/q-learning) +- [Random Forests](https://allalgorithms.com/docs/random-forest) +- [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) + +## [Backtracking](backtracking) + +- [Algorithm X](backtracking/algorithm-x) +- [Crossword Puzzle](backtracking/crossword-Puzzle) +- [Knight Tour](backtracking/knight-tour) +- [M Coloring Problem](backtracking/m-coloring-problem) +- [N Queen](backtracking/n-queen) +- [Number of ways in Maze](backtracking/number-of-ways-in-maze) +- [Partitions of set](backtracking/partitions-of-set) +- [Permutation of Strings](backtracking/permutation-of-strings) +- [Powerset](backtracking/powerset) +- [Rat in maze](backtracking/rat-in-maze) +- [Subset Sum](backtracking/subset-sum) +- [Sudoku Solve](backtracking/sudoku-solve) + +## [Bit Manipulation](bit-manipulation) + +- [Addition using bits](bit-manipulation/adding-using-bits) +- [Bit divisor](bit-manipulation/bit-divisor) +- [Byte swapper](bit-manipulation/byte-swapper) +- [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) +- [Count set bits](bit-manipulation/count-set-bits) +- [Flip bits](bit-manipulation/flip-bits) +- [Hamming distance](bit-manipulation/hamming-distace) +- [Invert bit](bit-manipulation/invert-bit) +- [Lonely integer](bit-manipulation/lonely-integer) +- [Magic Number](bit-manipulation/magic-number) +- [Maximum XOR Value](bit-manipulation/maximun-xor-value) +- [Power of 2](bit-manipulation/power-of-2) +- [Subset Generation](bit-manipulation/subset-generation) +- [Sum binary numbers](bit-manipulation/sum-binary-numbers) +- [Sum equals XOR](bit-manipulation/sum-equals-xor) +- [Thrice unique number](bit-manipulation/thrice-unique-number) +- [Twice unique number](bit-manipulation/twice-unique-number) +- [XOR Swap](bit-manipulation/xor-swap) + +## [Cellular Automaton](cellular-automaton) + +- [Brians Brain](cellular-automaton/brians-brain) +- [Conways Game of life](cellular-automaton/conways-game-of-life) +- [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) +- [Generic Algorithm](cellular-automaton/generic-algorithm) +- [Langtons Ant](cellular-automaton/langtons-ant) +- [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) +- [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) + +## [Computational Geometry](computational-geometry) + +- [2D Line intersection](computational-geometry/) +- [2D Separating Axis test](computational-geometry/) +- [Area of polygon](computational-geometry/) +- [Area of triangle](computational-geometry/) +- [Axis aligned bounding box collision](computational-geometry/) +- [Bresenham Line](computational-geometry/) +- [Chans Algorithm](computational-geometry/) +- [Cohen Sutherland Lineclip](computational-geometry/) +- [Distance between points](computational-geometry/) +- [Graham Scan](computational-geometry/) +- [Halfplane intersection](computational-geometry/) +- [Jarvis March](computational-geometry/) +- [Quickull](computational-geometry/) +- [Sphere tetrahedron intersection](computational-geometry/) +- [Sutherland Hodgeman clipping](computational-geometry/) + +## [Cryptography](cryptography) + +- [Affine Cipher](cryptography/) +- [Atbash Cipher](cryptography/) +- [Autokey Cipher](cryptography/) +- [Baconian Cipher](cryptography/) +- [Caesar Cipher](cryptography/) +- [Colummnar Cipher](cryptography/) +- [Vigenere Cipher](cryptography/) + +## [Data Structures](data-structures) + +- [Bag](data-structures/bag/) +- [Hashes](data-structures/hashes/) +- [Linked List](data-structures/linked-list/) +- [List](data-structures/list/) +- [Queue](data-structures/queue/) +- [Stack](data-structures/stack/) +- [Tree](data-structures/tree/) + +## [Divide and conquer](divide-and-conquer) + +- [Strassen Matrix Manipulation](divide-and-conquer/) +- [Closest Pair of Point](divide-and-conquer/) +- [Inversion Count](divide-and-conquer/) +- [Karatsuba Multiplication](divide-and-conquer/) +- [Maximum Contiguous subsequence sum](divide-and-conquer/) +- [Merge Sort using divide and conquer](divide-and-conquer/) +- [Quick Sort using divide and conquer](divide-and-conquer/) +- [Tournament Method to find min max](divide-and-conquer/) +- [Warnock Algorithm](divide-and-conquer/) +- [X Power Y](divide-and-conquer/) + +## [Dynamic Programming](dynamic-programming) + +- [Array Median](dynamic-programming) +- [Optima Binary Search Tree](dynamic-programming) +- [Binomial Coefficient](dynamic-programming) + +## [Gaming Theory](gaming-theory) + +- [Nim Next Best Move Game](gaming-theory/) +- [Nim Win Loss Game](gaming-theory/) +- [Grundy Numbers Kayle Game](gaming-theory/) + +## [Graphs](graphs) + +- [Bipartite Check](graphs/) +- [Adjacency Lists graphs representation](graphs/) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) + +## [Greedy Algorithms](greedy-algorithms) + +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) + +## [Math](math) + +- [2 Sum](math/) +- [Add Polynomials](math/) +- [Amicable Numbers](math/) +- [Armstrong Numbers](math/) +- [Automorphic Numbers](math/) +- [Average Stream Numbers](math/) +- [Babylonian Method](math/) +- [Binomial Coefficient](math/) +- [Catalan Number](math/) +- [Check is Square](math/) +- [Convolution](math/) +- [Coprime Numbers](math/) +- [Count Digits](math/) +- [Count Trailing Zeroes](math/) +- [Decoding of String](math/) +- [Delannoy Number](math/) +- [Derangements](math/) +- [DFA Division](math/) +- [Diophantine](math/) +- [Divided Differences](math/) +- [Euler Totient](math/) +- [Exponentiation Power](math/) +- [Factorial](math/factorial) +- [Fast Fourier transform](math/) +- [Fast inverse (sqrt) Square Root](math/) + +## [Networking](networking) + +- [Packet Sniffer](networking/) +- [Determine Endianess](networking/) +- [Validate IP](networking/) + +## [Numerical Analysis](numerical-analysis) + +- [Integral](numerical-analysis/integral) +- [Monte Carlo](numerical-analysis/monte-carlo) +- [Runge Kutt](numerical-analysis/runge-kutt) + +## [Operating system](operating-system) + +- [Currency](operating-system/) +- [Deadlocks](operating-system/) +- [Memory Management](operating-system/) +- [Scheduling](operating-system/) +- [Shell](operating-system/) + +## [Randomized Algorithms](randomized-algorithms) + +- [Birthday Paradox](randomized-algorithms) +- [Karger Minimum Cut Algorithm](randomized-algorithms) +- [Kth Smallest Element Algorithm](randomized-algorithms) +- [Random from Stream](randomized-algorithms) +- [Random Node Linked list](randomized-algorithms) +- [Randomized Quicksort](randomized-algorithms) +- [Reservoir Sampling](randomized-algorithms) +- [Shuffle an Array](randomized-algorithms) + +## [Searches](searches) + +- [Binary Search](searches) +- [Exponential Search](searches) +- [Fibonacci Search](searches) +- [Fuzzy Search](searches) +- [Interpolation Search](searches) +- [Jump Search](searches) +- [Linear Search](searches) +- [Ternay Search](searches) + +## [Selections Algorithms](selections-algorithms) + +- [Median of Medians](selections-algorithms) +- [Quick Select](selections-algorithms) + +## [Sorting](sorting) + +- [Bead Sort](sorting/) +- [Bogo Sort](sorting/) +- [Bubble Sort](sorting/) +- [Bucket Sort](sorting/) +- [Circle Sort](sorting/) +- [Comb Sort](sorting/) +- [Counting Sort](sorting/) +- [Cycle Sort](sorting/) +- [Flash Sort](sorting/) +- [Gnome Sort](sorting/) +- [Heap Sort](sorting/) +- [Insertion Sort](sorting/) +- [Intro Sort](sorting/) +- [Median Sort](sorting/) +- [Merge Sort](sorting/) +- [Pipeonhole Sort](sorting/) +- [Quick Sort](sorting/) +- [Radix Sort](sorting/) +- [Selection Sort](sorting/) +- [Shaker Sort](sorting/) +- [Shell Sort](sorting/) +- [Sleep Sort](sorting/) +- [Stooge Sort](sorting/) +- [Topological Sort](sorting/) +- [Tree Sort](sorting/) + +## [Strings](strings) + +- [Aho Corasick Algorithm](strings) +- [Anagram Search](strings) +- [Arithmetic on large numbers](strings) +- [Boyer Moore Algorithm](strings) +- [Finite Automata](strings) +- [Kasai Algorithm](strings) +- [Kmp Algorithm](strings) +- [Levenshteing Distance](strings) +- [Lipogram Checker](strings) + +## [Online Challenges](online-challenges) + +- [Coderbyte](online-challenges/coderbyte) +- [Code Chef](online-challenges/code-chef) +- [Code Eval](online-challenges/code-eval) +- [Hackerearth](online-challenges/hackerearth) +- [Hackerrank](online-challenges/hackerrank) +- [LeetCode](online-challenges/leetcode) +- [Project Euler](online-challenges/project-euler) +- [Rosalind](online-challenges/rosalind) +- [SPOJ](online-challenges/spoj) +- [Top Coder](online-challenges/top-coder)` + +## [Others](others) + +- [Average](others/) +- [Biggest of n numbers](others/) +- [Biggest Suffix](others/) +- [Fifteen Puzzle](others/) +- [Jaccard Similarity](others/) +- [Jose Phus Problem](others/) +- [Lapindrom Checker](others/) +- [Leap Year](others/) +- [Magic Square](others/) +- [Majority Element](others/) +- [Minimum subarray size with degree](others/) +- [No operator addition](others/) +- [Paint fill](others/) +- [Split list](others/) +- [Tokenizer](others/) +- [Unique number](others/) + +## License + +This work is released under MIT License. + +To the extent possible under law, [Abraham Hernandez (@abranhe)](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. + +
+ + + +
+
\ No newline at end of file diff --git a/searches/jump_search.cpp b/searches/jump_search.cpp deleted file mode 100644 index 203bd78e..00000000 --- a/searches/jump_search.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// C++ program to implement Jump Search -//Author Bharat Reddy - -#include -using namespace std; - -int jumpSearch(int arr[], int x, int n) -{ - // Finding block size to be jumped - int step = sqrt(n); - - // Finding the block where element is - // present (if it is present) - int prev = 0; - while (arr[min(step, n)-1] < x) - { - prev = step; - step += sqrt(n); - if (prev >= n) - return -1; - } - - // Doing a linear search for x in block - // beginning with prev. - while (arr[prev] < x) - { - prev++; - - // If we reached next block or end of - // array, element is not present. - if (prev == min(step, n)) - return -1; - } - // If element is found - if (arr[prev] == x) - return prev; - - return -1; -} - -// Driver program to test function -int main() -{ - int n,i; - cout<<"Eneter size of array : "; - cin>>n; - cout<<"Enter elements of array"<>a[i]; - sort(a,a+n); - cout<<"Enter key to be searched : "; - int key; - cin>>key; - - // Find the index of 'x' using Jump Search - int index = jumpSearch(a, key, n); - - // Print the index where 'x' is located - cout << "\nNumber " << key << " is at index " << index; - return 0; -} \ No newline at end of file diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp deleted file mode 100644 index 3fb6af54..00000000 --- a/sorting/bubble_sort.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// C++ implementation of bubble sort -// -// Author: Carlos Abraham Hernandez - -#include - -// Swap elements -void swap(int *x, int *y) -{ - int temp = *x; - *x = *y; - *y = temp; -} - -// Implement bubble sort -void bubbleSort(int arr[], int n) -{ - int i, j; - for (i = 0; i < n-1; i++) - // last i elements are already in place - for (j = 0; j < n-i-1; j++) - if (arr[j] > arr[j+1]) - swap(&arr[j], &arr[j+1]); -} - -// Function to print elements -void printArray(int arr[], int size) -{ - int i; - for (i=0; i < size; i++) - printf("%d ", arr[i]); - printf("\n"); -} - -// test -int main() -{ - int arr[] = {46, 24, 33, 10, 2, 81, 50}; - int n = sizeof(arr)/sizeof(arr[0]); - printf("Unsorted array: \n"); - printArray(arr, n); - bubbleSort(arr, n); - printf("Sorted array: \n"); - printArray(arr, n); - return 0; -} diff --git a/sorting/insertionSort.cpp b/sorting/insertionSort.cpp deleted file mode 100644 index 6543970d..00000000 --- a/sorting/insertionSort.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// C++ implementation of insertion sort -// -// Author: Andres Langberg - - -#include - -/* Function to sort an array using insertion sort*/ -void insertionSort(int arr[], int n) -{ - int i, key, j; - for (i = 1; i < n; i++) - { - key = arr[i]; - j = i-1; - - /* Move elements of arr[0..i-1], that are - greater than key, to one position ahead - of their current position */ - while (j >= 0 && arr[j] > key) - { - arr[j+1] = arr[j]; - j = j-1; - } - arr[j+1] = key; - } -} - -// A utility function to print an array of size n -void printArray(int arr[], int n) -{ - int i; - for (i=0; i < n; i++) - printf("%d ", arr[i]); - printf("\n"); -} - - - -/* Driver program to test insertion sort */ -int main() -{ - int arr[] = {12, 11, 13, 5, 6}; - int n = sizeof(arr)/sizeof(arr[0]); - - insertionSort(arr, n); - printArray(arr, n); - - return 0; -} diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp deleted file mode 100644 index 3e72d734..00000000 --- a/sorting/quick_sort.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include -#include -using namespace std; - -void quickSort(vector&,int,int); -int partition(vector&, int,int); - -int main() -{ - vector A = {10,9,8,7,6,5,4,3,2,1}; - int start = 0; - int end = (int)A.size(); - cout << "Before:" << endl; - for(auto value : A) - cout << value <<" "; - cout << endl; - quickSort(A, start, end); - cout << "After: " << endl; - for(auto value : A) - cout << value <<" "; - cout << endl; -} - -void quickSort(vector& A, int start,int end) -{ - int pivot; - if(start < end) - { - pivot=partition(A, start, end); - quickSort(A, start, pivot); - quickSort(A, pivot+1, end); - } -} - - -int partition(vector& A, int start,int end) -{ - int x = A[start]; - int i = start; - int j; - for(j = start+1; j < end; j++) - { - if(A[j]<=x) - { - i=i+1; - swap(A[i],A[j]); - } - } - swap(A[i],A[start]); - return i; -} diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 00000000..e69de29b