diff --git a/0-1 knapsack.cpp/0-1 knapsack.cpp b/0-1 knapsack.cpp/0-1 knapsack.cpp new file mode 100644 index 0000000..12459c2 --- /dev/null +++ b/0-1 knapsack.cpp/0-1 knapsack.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +// 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) +{ + + // Base Case + if (n == 0 || W == 0) + return 0; + + // If weight of the nth item is more + // than Knapsack capacity W, then + // this item cannot be included + // in the optimal solution + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + // Return the maximum of two cases: + // (1) nth item included + // (2) not included + else + return max( + val[n - 1] + + knapSack(W - wt[n - 1], + wt, val, n - 1), + knapSack(W, wt, val, n - 1)); +} + +// Driver code +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; +} + +// This diff --git a/A star algorithm/AStar.cpp b/A star algorithm/AStar.cpp new file mode 100644 index 0000000..fedf945 --- /dev/null +++ b/A star algorithm/AStar.cpp @@ -0,0 +1,636 @@ +#include +using namespace std; + +#define ROW 9 +#define COL 10 + +// Creating a shortcut for int, int pair type +typedef pair Pair; + +// Creating a shortcut for pair> type +typedef pair > pPair; + +// A structure to hold the necessary parameters +struct cell { + // Row and Column index of its parent + // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 + int parent_i, parent_j; + // f = g + h + double f, g, h; +}; + +// A Utility Function to check whether given cell (row, col) +// is a valid cell or not. +bool isValid(int row, int col) +{ + // Returns true if row number and column number + // is in range + return (row >= 0) && (row < ROW) && (col >= 0) + && (col < COL); +} + +// A Utility Function to check whether the given cell is +// blocked or not +bool isUnBlocked(int grid[][COL], int row, int col) +{ + // Returns true if the cell is not blocked else false + if (grid[row][col] == 1) + return (true); + else + return (false); +} + +// A Utility Function to check whether destination cell has +// been reached or not +bool isDestination(int row, int col, Pair dest) +{ + if (row == dest.first && col == dest.second) + return (true); + else + return (false); +} + +// A Utility Function to calculate the 'h' heuristics. +double calculateHValue(int row, int col, Pair dest) +{ + // Return using the distance formula + return ((double)sqrt( + (row - dest.first) * (row - dest.first) + + (col - dest.second) * (col - dest.second))); +} + +// A Utility Function to trace the path from the source +// to destination +void tracePath(cell cellDetails[][COL], Pair dest) +{ + printf("\nThe Path is "); + int row = dest.first; + int col = dest.second; + + stack Path; + + while (!(cellDetails[row][col].parent_i == row + && cellDetails[row][col].parent_j == col)) { + Path.push(make_pair(row, col)); + int temp_row = cellDetails[row][col].parent_i; + int temp_col = cellDetails[row][col].parent_j; + row = temp_row; + col = temp_col; + } + + Path.push(make_pair(row, col)); + while (!Path.empty()) { + pair p = Path.top(); + Path.pop(); + printf("-> (%d,%d) ", p.first, p.second); + } + + return; +} + +// A Function to find the shortest path between +// a given source cell to a destination cell according +// to A* Search Algorithm +void aStarSearch(int grid[][COL], Pair src, Pair dest) +{ + // If the source is out of range + if (isValid(src.first, src.second) == false) { + printf("Source is invalid\n"); + return; + } + + // If the destination is out of range + if (isValid(dest.first, dest.second) == false) { + printf("Destination is invalid\n"); + return; + } + + // Either the source or the destination is blocked + if (isUnBlocked(grid, src.first, src.second) == false + || isUnBlocked(grid, dest.first, dest.second) + == false) { + printf("Source or the destination is blocked\n"); + return; + } + + // If the destination cell is the same as source cell + if (isDestination(src.first, src.second, dest) + == true) { + printf("We are already at the destination\n"); + return; + } + + // Create a closed list and initialise it to false which + // means that no cell has been included yet This closed + // list is implemented as a boolean 2D array + bool closedList[ROW][COL]; + memset(closedList, false, sizeof(closedList)); + + // Declare a 2D array of structure to hold the details + // of that cell + cell cellDetails[ROW][COL]; + + int i, j; + + for (i = 0; i < ROW; i++) { + for (j = 0; j < COL; j++) { + cellDetails[i][j].f = FLT_MAX; + cellDetails[i][j].g = FLT_MAX; + cellDetails[i][j].h = FLT_MAX; + cellDetails[i][j].parent_i = -1; + cellDetails[i][j].parent_j = -1; + } + } + + // Initialising the parameters of the starting node + i = src.first, j = src.second; + cellDetails[i][j].f = 0.0; + cellDetails[i][j].g = 0.0; + cellDetails[i][j].h = 0.0; + cellDetails[i][j].parent_i = i; + cellDetails[i][j].parent_j = j; + + /* + Create an open list having information as- + > + where f = g + h, + and i, j are the row and column index of that cell + Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 + This open list is implemented as a set of pair of + pair.*/ + set openList; + + // Put the starting cell on the open list and set its + // 'f' as 0 + openList.insert(make_pair(0.0, make_pair(i, j))); + + // We set this boolean value as false as initially + // the destination is not reached. + bool foundDest = false; + + while (!openList.empty()) { + pPair p = *openList.begin(); + + // Remove this vertex from the open list + openList.erase(openList.begin()); + + // Add this vertex to the closed list + i = p.second.first; + j = p.second.second; + closedList[i][j] = true; + + /* + Generating all the 8 successor of this cell + + N.W N N.E + \ | / + \ | / + W----Cell----E + / | \ + / | \ + S.W S S.E + + Cell-->Popped Cell (i, j) + N --> North (i-1, j) + S --> South (i+1, j) + E --> East (i, j+1) + W --> West (i, j-1) + N.E--> North-East (i-1, j+1) + N.W--> North-West (i-1, j-1) + S.E--> South-East (i+1, j+1) + S.W--> South-West (i+1, j-1)*/ + + // To store the 'g', 'h' and 'f' of the 8 successors + double gNew, hNew, fNew; + + //----------- 1st Successor (North) ------------ + + // Only process this cell if this is a valid one + if (isValid(i - 1, j) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i - 1, j, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i - 1][j].parent_i = i; + cellDetails[i - 1][j].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i - 1][j] == false + && isUnBlocked(grid, i - 1, j) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i - 1, j, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i - 1][j].f == FLT_MAX + || cellDetails[i - 1][j].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i - 1, j))); + + // Update the details of this cell + cellDetails[i - 1][j].f = fNew; + cellDetails[i - 1][j].g = gNew; + cellDetails[i - 1][j].h = hNew; + cellDetails[i - 1][j].parent_i = i; + cellDetails[i - 1][j].parent_j = j; + } + } + } + + //----------- 2nd Successor (South) ------------ + + // Only process this cell if this is a valid one + if (isValid(i + 1, j) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i + 1, j, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i + 1][j].parent_i = i; + cellDetails[i + 1][j].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i + 1][j] == false + && isUnBlocked(grid, i + 1, j) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i + 1, j, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i + 1][j].f == FLT_MAX + || cellDetails[i + 1][j].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i + 1, j))); + // Update the details of this cell + cellDetails[i + 1][j].f = fNew; + cellDetails[i + 1][j].g = gNew; + cellDetails[i + 1][j].h = hNew; + cellDetails[i + 1][j].parent_i = i; + cellDetails[i + 1][j].parent_j = j; + } + } + } + + //----------- 3rd Successor (East) ------------ + + // Only process this cell if this is a valid one + if (isValid(i, j + 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i, j + 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i][j + 1].parent_i = i; + cellDetails[i][j + 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i][j + 1] == false + && isUnBlocked(grid, i, j + 1) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i, j + 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i][j + 1].f == FLT_MAX + || cellDetails[i][j + 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i, j + 1))); + + // Update the details of this cell + cellDetails[i][j + 1].f = fNew; + cellDetails[i][j + 1].g = gNew; + cellDetails[i][j + 1].h = hNew; + cellDetails[i][j + 1].parent_i = i; + cellDetails[i][j + 1].parent_j = j; + } + } + } + + //----------- 4th Successor (West) ------------ + + // Only process this cell if this is a valid one + if (isValid(i, j - 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i, j - 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i][j - 1].parent_i = i; + cellDetails[i][j - 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i][j - 1] == false + && isUnBlocked(grid, i, j - 1) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i, j - 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i][j - 1].f == FLT_MAX + || cellDetails[i][j - 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i, j - 1))); + + // Update the details of this cell + cellDetails[i][j - 1].f = fNew; + cellDetails[i][j - 1].g = gNew; + cellDetails[i][j - 1].h = hNew; + cellDetails[i][j - 1].parent_i = i; + cellDetails[i][j - 1].parent_j = j; + } + } + } + + //----------- 5th Successor (North-East) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i - 1, j + 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i - 1, j + 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i - 1][j + 1].parent_i = i; + cellDetails[i - 1][j + 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i - 1][j + 1] == false + && isUnBlocked(grid, i - 1, j + 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i - 1, j + 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i - 1][j + 1].f == FLT_MAX + || cellDetails[i - 1][j + 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i - 1, j + 1))); + + // Update the details of this cell + cellDetails[i - 1][j + 1].f = fNew; + cellDetails[i - 1][j + 1].g = gNew; + cellDetails[i - 1][j + 1].h = hNew; + cellDetails[i - 1][j + 1].parent_i = i; + cellDetails[i - 1][j + 1].parent_j = j; + } + } + } + + //----------- 6th Successor (North-West) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i - 1, j - 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i - 1, j - 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i - 1][j - 1].parent_i = i; + cellDetails[i - 1][j - 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i - 1][j - 1] == false + && isUnBlocked(grid, i - 1, j - 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i - 1, j - 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i - 1][j - 1].f == FLT_MAX + || cellDetails[i - 1][j - 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i - 1, j - 1))); + // Update the details of this cell + cellDetails[i - 1][j - 1].f = fNew; + cellDetails[i - 1][j - 1].g = gNew; + cellDetails[i - 1][j - 1].h = hNew; + cellDetails[i - 1][j - 1].parent_i = i; + cellDetails[i - 1][j - 1].parent_j = j; + } + } + } + + //----------- 7th Successor (South-East) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i + 1, j + 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i + 1, j + 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i + 1][j + 1].parent_i = i; + cellDetails[i + 1][j + 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i + 1][j + 1] == false + && isUnBlocked(grid, i + 1, j + 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i + 1, j + 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i + 1][j + 1].f == FLT_MAX + || cellDetails[i + 1][j + 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i + 1, j + 1))); + + // Update the details of this cell + cellDetails[i + 1][j + 1].f = fNew; + cellDetails[i + 1][j + 1].g = gNew; + cellDetails[i + 1][j + 1].h = hNew; + cellDetails[i + 1][j + 1].parent_i = i; + cellDetails[i + 1][j + 1].parent_j = j; + } + } + } + + //----------- 8th Successor (South-West) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i + 1, j - 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i + 1, j - 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i + 1][j - 1].parent_i = i; + cellDetails[i + 1][j - 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i + 1][j - 1] == false + && isUnBlocked(grid, i + 1, j - 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i + 1, j - 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i + 1][j - 1].f == FLT_MAX + || cellDetails[i + 1][j - 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i + 1, j - 1))); + + // Update the details of this cell + cellDetails[i + 1][j - 1].f = fNew; + cellDetails[i + 1][j - 1].g = gNew; + cellDetails[i + 1][j - 1].h = hNew; + cellDetails[i + 1][j - 1].parent_i = i; + cellDetails[i + 1][j - 1].parent_j = j; + } + } + } + } + + // When the destination cell is not found and the open + // list is empty, then we conclude that we failed to + // reach the destination cell. This may happen when the + // there is no way to destination cell (due to + // blockages) + if (foundDest == false) + printf("Failed to find the Destination Cell\n"); + + return; +} + +// Driver program to test above function +int main() +{ + /* Description of the Grid- + 1--> The cell is not blocked + 0--> The cell is blocked */ + int grid[ROW][COL] + = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, + { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, + { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, + { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } }; + + // Source is the left-most bottom-most corner + Pair src = make_pair(8, 0); + + // Destination is the left-most top-most corner + Pair dest = make_pair(0, 0); + + aStarSearch(grid, src, dest); + + return (0); +} diff --git a/A star algorithm/Astar.java b/A star algorithm/Astar.java new file mode 100644 index 0000000..ca7dcfd --- /dev/null +++ b/A star algorithm/Astar.java @@ -0,0 +1,141 @@ +public class Node implements Comparable { + // Id for readability of result purposes + private static int idCounter = 0; + public int id; + + // Parent in the path + public Node parent = null; + + public List neighbors; + + // Evaluation functions + public double f = Double.MAX_VALUE; + public double g = Double.MAX_VALUE; + // Hardcoded heuristic + public double h; + + Node(double h){ + this.h = h; + this.id = idCounter++; + this.neighbors = new ArrayList<>(); + } + + @Override + public int compareTo(Node n) { + return Double.compare(this.f, n.f); + } + + public static class Edge { + Edge(int weight, Node node){ + this.weight = weight; + this.node = node; + } + + public int weight; + public Node node; + } + + public void addBranch(int weight, Node node){ + Edge newEdge = new Edge(weight, node); + neighbors.add(newEdge); + } + + public double calculateHeuristic(Node target){ + return this.h; + } +} + + + +public static Node aStar(Node start, Node target){ + PriorityQueue closedList = new PriorityQueue<>(); + PriorityQueue openList = new PriorityQueue<>(); + + start.f = start.g + start.calculateHeuristic(target); + openList.add(start); + + while(!openList.isEmpty()){ + Node n = openList.peek(); + if(n == target){ + return n; + } + + for(Node.Edge edge : n.neighbors){ + Node m = edge.node; + double totalWeight = n.g + edge.weight; + + if(!openList.contains(m) && !closedList.contains(m)){ + m.parent = n; + m.g = totalWeight; + m.f = m.g + m.calculateHeuristic(target); + openList.add(m); + } else { + if(totalWeight < m.g){ + m.parent = n; + m.g = totalWeight; + m.f = m.g + m.calculateHeuristic(target); + + if(closedList.contains(m)){ + closedList.remove(m); + openList.add(m); + } + } + } + } + + openList.remove(n); + closedList.add(n); + } + return null; +} + +public static void printPath(Node target){ + Node n = target; + + if(n==null) + return; + + List ids = new ArrayList<>(); + + while(n.parent != null){ + ids.add(n.id); + n = n.parent; + } + ids.add(n.id); + Collections.reverse(ids); + + for(int id : ids){ + System.out.print(id + " "); + } + System.out.println(""); +} + + +public static void main(String[] args) { + Node head = new Node(3); + head.g = 0; + + Node n1 = new Node(2); + Node n2 = new Node(2); + Node n3 = new Node(2); + + head.addBranch(1, n1); + head.addBranch(5, n2); + head.addBranch(2, n3); + n3.addBranch(1, n2); + + Node n4 = new Node(1); + Node n5 = new Node(1); + Node target = new Node(0); + + n1.addBranch(7, n4); + n2.addBranch(4, n5); + n3.addBranch(6, n4); + + n4.addBranch(3, target); + n5.addBranch(1, n4); + n5.addBranch(3, target); + + Node res = aStar(head, target); + printPath(res); +} diff --git a/Armstrong Number/Amrstrong.py b/Armstrong Number/Amrstrong.py new file mode 100644 index 0000000..137ae54 --- /dev/null +++ b/Armstrong Number/Amrstrong.py @@ -0,0 +1,12 @@ +sum=0 +def check_ArmstrongNumber(num): + global sum + if (num!=0): + sum+=pow(num%10,3) + check_ArmstrongNumber(num//10) + return sum +num=int(input("Enter a number:")) +if (check_ArmstrongNumber(num) == num): + print("It's an Armstrong Number.") +else: + print("Not an Armstrong Number.") \ No newline at end of file diff --git a/Armstrong Number/Armstrong.java b/Armstrong Number/Armstrong.java new file mode 100644 index 0000000..204cd93 --- /dev/null +++ b/Armstrong Number/Armstrong.java @@ -0,0 +1,44 @@ +import java.util.Scanner; +import java.lang.Math; +public class ArmstsrongNumberExample { + //function to check if the number is Armstrong or not + static boolean isArmstrong(int n) { + int temp, digits=0, last=0, sum=0; + //assigning n into a temp variable + temp=n; + //loop execute until the condition becomes false + while(temp>0) { + temp = temp/10; + digits++; + } + temp = n; + while(temp>0) { + //determines the last digit from the number + last = temp % 10; + //calculates the power of a number up to digit times and add the resultant to the sum variable + sum += (Math.pow(last, digits)); + //removes the last digit + temp = temp/10; + } + //compares the sum with n + if(n==sum) + //returns if sum and n are equal + return true; + //returns false if sum and n are not equal + else return false; +} +//driver code +public static void main(String args[]) { + int num; + Scanner sc= new Scanner(System.in); + System.out.print("Enter the limit: "); + //reads the limit from the user + num=sc.nextInt(); + System.out.println("Armstrong Number up to "+ num + " are: "); + for(int i=0; i<=num; i++) + //function calling + if(isArmstrong(i)) + //prints the armstrong numbers + System.out.print(i+ ", "); + } +} diff --git a/Armstrong Number/armstrong_number.js b/Armstrong Number/armstrong_number.js new file mode 100644 index 0000000..bfdbd18 --- /dev/null +++ b/Armstrong Number/armstrong_number.js @@ -0,0 +1,23 @@ +// program to check an Armstrong number of three digits + +let sum = 0; +const number = prompt('Enter a three-digit positive integer: '); + +// create a temporary variable +let temp = number; +while (temp > 0) { + // finding the one's digit + let remainder = temp % 10; + + sum += remainder * remainder * remainder; + + // removing last digit from the number + temp = parseInt(temp / 10); // convert float into integer +} +// check the condition +if (sum == number) { + console.log(`${number} is an Armstrong number`); +} +else { + console.log(`${number} is not an Armstrong number.`); +} diff --git a/Bellman Ford algorithm/bellmanFord.java b/Bellman Ford algorithm/bellmanFord.java new file mode 100644 index 0000000..3320d87 --- /dev/null +++ b/Bellman Ford algorithm/bellmanFord.java @@ -0,0 +1,17 @@ +class Solution { + + public int networkDelayTime(int[][] times, int N, int K) { + int[] dist = new int[N]; + for (int i = 0; i < dist.length; i++) + dist[i] = (int)1e9; + dist[K - 1] = 0; + for (int i = 0; i < N; i++) { + for (int[] time: times) { + if (dist[time[0] - 1] + time[2] < dist[time[1] - 1]) { + dist[time[1] - 1] = dist[time[0] - 1] + time[2]; + } + } + } + if (Arrays.stream(dist).anyMatch(i -> i == (int)1e9)) return -1; + return Arrays.stream(dist).max().orElse(-1); + } diff --git a/Binary Insertion Sort/Binary-Insertion-Sort.py b/Binary Insertion Sort/Binary-Insertion-Sort.py new file mode 100644 index 0000000..4b008b1 --- /dev/null +++ b/Binary Insertion Sort/Binary-Insertion-Sort.py @@ -0,0 +1,38 @@ +# Python Program implementation +# of binary insertion sort + +def binary_search(arr, val, start, end): + # we need to distinugish whether we should insert + # before or after the left boundary. + # imagine [0] is the last step of the binary search + # and we need to decide where to insert -1 + if start == end: + if arr[start] > val: + return start + else: + return start+1 + + # this occurs if we are moving beyond left\'s boundary + # meaning the left boundary is the least position to + # find a number greater than val + if start > end: + return start + + mid = (start+end)/2 + if arr[mid] < val: + return binary_search(arr, val, mid+1, end) + elif arr[mid] > val: + return binary_search(arr, val, start, mid-1) + else: + return mid + +def insertion_sort(arr): + for i in xrange(1, len(arr)): + val = arr[i] + j = binary_search(arr, val, 0, i-1) + arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] + return arr + +print("Sorted array:") +print insertion_sort([37, 23, 0, 17, 12, 72, 31, + 46, 100, 88, 54]) diff --git a/BinarySearch/binarysearch.js b/BinarySearch/binarysearch.js new file mode 100644 index 0000000..c2796fb --- /dev/null +++ b/BinarySearch/binarysearch.js @@ -0,0 +1,37 @@ + diff --git a/Bubble Sort/BubbleSort.java b/Bubble Sort/BubbleSort.java new file mode 100644 index 0000000..02e379a --- /dev/null +++ b/Bubble Sort/BubbleSort.java @@ -0,0 +1,35 @@ +class BubbleSort +{ + void bubbleSort(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n-1; i++) + for (int j = 0; j < n-i-1; j++) + if (arr[j] > arr[j+1]) + { + // swap arr[j+1] and arr[j] + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + } + + /* Prints the array */ + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i arr[j+1]) + { + swap(arr,j,j+1); + + } + } + +} +} + +/* Function to print an array */ +function printArray(arr, size) +{ + var i; + for (i=0; i < size; i++) + document.write(arr[i]+ " "); + document.write("\n"); +} + +// Driver program to test above functions +var arr = [64, 34, 25, 12, 22, 11, 90]; + var n = 7; + document.write("UnSorted array: \n"); + printArray(arr, n); + + bubbleSort(arr, n); + document.write("Sorted array: \n"); + printArray(arr, n); + + diff --git a/Bucket Sort/Bucket-sort.cpp b/Bucket Sort/Bucket-sort.cpp new file mode 100644 index 0000000..c486bef --- /dev/null +++ b/Bucket Sort/Bucket-sort.cpp @@ -0,0 +1,46 @@ +// C++ program to sort an +// array using bucket sort +#include +#include +#include +using namespace std; + +// Function to sort arr[] of +// size n using bucket sort +void bucketSort(float arr[], int n) +{ + + // 1) Create n empty buckets + vector b[n]; + + // 2) Put array elements + // in different buckets + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); + } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; +} + +/* Driver program to test above function */ +int main() +{ + float arr[] + = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); + + cout << "Sorted array is \n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} diff --git a/Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp b/Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp new file mode 100644 index 0000000..1069d4c --- /dev/null +++ b/Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +#define Least_Significant_Bit(i) (i) & -(i) + +vector Binary_Indexed_Tree; + +int TREE_SIZE = 1e5 + 10; + +void update(int index, int value) { + while(index <= TREE_SIZE) { + Binary_Indexed_Tree[index] += value; + index += Least_Significant_Bit(index); + } +} + +int query(int index) { + int sum = 0; + while(index > 0) { + sum += Binary_Indexed_Tree[index]; + index -= Least_Significant_Bit(index); + } + return sum; +} + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + + Binary_Indexed_Tree.assign(TREE_SIZE, 0); + int n; + cin >> n; + for(int i = 1; i <= n; i++) { + string operation; + cin >> operation; + if(operation == "U") { + /// Update + int index, value; + cin >> index >> value; + update(index, value); + } + if(operation == "Q") { + /// Query + int index; + cin >> index; + cout << query(index) << "\n"; + } + } + return 0; +} diff --git a/Dijkstra's Algorithm/dijkstra.java b/Dijkstra's Algorithm/dijkstra.java new file mode 100644 index 0000000..75bbe3d --- /dev/null +++ b/Dijkstra's Algorithm/dijkstra.java @@ -0,0 +1,64 @@ +class Pair { + int city, cost; + + Pair(int city, int cost) { + this.city = city; + this.cost = cost; + } +} + +class City { + int city, distFromSrc, costFromSrc; + + City(int city, int distFromSrc, int cost) { + this.city = city; + this.distFromSrc = distFromSrc; + this.costFromSrc = cost; + } +} + +class Solution { + + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { + // DFS + if(n <= 0 || flights == null || flights.length == 0 || K < 0) + return -1; + + List> graph = new ArrayList<>(); + this.buildGraph(graph, n, flights); + + Queue pQueue = new PriorityQueue<>((City c1, City c2) -> c1.costFromSrc - c2.costFromSrc); + pQueue.offer(new City(src, 0, 0)); + + int totalCost = 0; + + while (!pQueue.isEmpty()) { + City top = pQueue.poll(); + + if (top.city == dst) { + return top.costFromSrc; + } + + if (top.distFromSrc > K) { + continue; + } + + List neighbors = graph.get(top.city); + for (Pair neighbor: neighbors) { + pQueue.offer(new City(neighbor.city, top.distFromSrc + 1, top.costFromSrc + neighbor.cost)); + } + } + + return -1; + } + + private void buildGraph(List> graph, int n, int[][] flights) { + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + + for (int[] flight: flights) { + graph.get(flight[0]).add(new Pair(flight[1], flight[2])); + } + } +} diff --git a/Dijkstra's Algorithm/dijkstra.js b/Dijkstra's Algorithm/dijkstra.js new file mode 100644 index 0000000..9bb6e98 --- /dev/null +++ b/Dijkstra's Algorithm/dijkstra.js @@ -0,0 +1,30 @@ +djikstraAlgorithm(startNode) { + let distances = {}; + + // Stores the reference to previous nodes + let prev = {}; + let pq = new PriorityQueue(this.nodes.length * this.nodes.length); + + // Set distances to all nodes to be infinite except startNode + distances[startNode] = 0; + pq.enqueue(startNode, 0); + this.nodes.forEach(node => { + if (node !== startNode) distances[node] = Infinity; + prev[node] = null; + }); + + while (!pq.isEmpty()) { + let minNode = pq.dequeue(); + let currNode = minNode.data; + let weight = minNode.priority; + this.edges[currNode].forEach(neighbor => { + let alt = distances[currNode] + neighbor.weight; + if (alt < distances[neighbor.node]) { + distances[neighbor.node] = alt; + prev[neighbor.node] = currNode; + pq.enqueue(neighbor.node, distances[neighbor.node]); + } + }); + } + return distances; +} diff --git a/Fibonacci series/fibonacci.c b/Fibonacci series/fibonacci.c new file mode 100644 index 0000000..b59d44f --- /dev/null +++ b/Fibonacci series/fibonacci.c @@ -0,0 +1,14 @@ +#include +int fib(int n) +{ + if(n<=1) + return n; + return fib(n-1)+fib(n-2); +} +int main() +{ + int a; + scanf("%d",&a); + printf("%d",fib(a)); + return 0; +} diff --git a/Fibonacci series/fibonacci.cpp b/Fibonacci series/fibonacci.cpp new file mode 100644 index 0000000..014ee91 --- /dev/null +++ b/Fibonacci series/fibonacci.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; +int main() { + int n1=0,n2=1,n3,i,number; + cout<<"Enter the number of elements: "; + cin>>number; + cout< +// declaration of the variables +var n1 = 0, n2 = 1, next_num, i; +var num = parseInt (prompt (" Enter the limit for Fibonacci Series ")); +document.write( "Fibonacci Series: "); +for ( i = 1; i <= num; i++) +{ document.write ("
" + n1); // print the n1 + next_num = n1 + n2; // sum of n1 and n2 into the next_num + + n1 = n2; // assign the n2 value into n2 + n2 = next_num; // assign the next_num into n2 +} + + diff --git a/Heapsort/HeapSort.cs b/Heapsort/HeapSort.cs new file mode 100644 index 0000000..ea350d9 --- /dev/null +++ b/Heapsort/HeapSort.cs @@ -0,0 +1,44 @@ +using System; +namespace HeapSortDemo { + public class example { + static 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--) { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + heapify(arr, i, 0); + } + } + static void heapify(int[] arr, int n, int i) { + int largest = i; + int left = 2*i + 1; + int right = 2*i + 2; + if (left < n && arr[left] > arr[largest]) + largest = left; + if (right < n && arr[right] > arr[largest]) + largest = right; + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + heapify(arr, n, largest); + } + } + public static void Main() { + int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100}; + int n = 10, i; + Console.WriteLine("Heap Sort"); + Console.Write("Initial array is: "); + for (i = 0; i < n; i++) { + Console.Write(arr[i] + " "); + } + heapSort(arr, 10); + Console.Write("\nSorted Array is: "); + for (i = 0; i < n; i++) { + Console.Write(arr[i] + " "); + } + } + } +} diff --git a/Heapsort/hpsort.java b/Heapsort/hpsort.java new file mode 100644 index 0000000..4a03f6e --- /dev/null +++ b/Heapsort/hpsort.java @@ -0,0 +1,64 @@ +public static int[] heapSort(int[] nums) { + //build the heap + for(int i=nums.length-1;i>=0;i--) + //merge the 2 sub-heaps below i, by bubbling nums[i] down to the correct location + sink(nums,i,nums.length); + //turn it into a sorted list + for(int i=nums.length-1;i>0;i--){ + //remove the root, and put the last leaf at the root of the heap + int tmp = nums[i]; + nums[i]=nums[0]; + nums[0] = tmp; + //bubble the new root down to the correct location + sink(nums,0,i); + } + return nums; +} +static void sink(int[] nums, int start, int end){ + int val = nums[start]; + int i = start, next = 2*i+1; + while(nextnums[next]) + next++; + if(nums[next]<=val) + break; + nums[i]=nums[next]; + i=next; + next = 2*i+1; //2*i+1, 2*i+2 are the children of i + } + nums[i]=val; +} +Original code: O(nlogn) build heap + +public static int[] heapSort(int[] nums) { + //build the heap + for(int i=1;i0 && nums[next]0;i--){ + int val = nums[i]; + nums[i]=nums[0]; + + int j = 0, next = 1; + while(nextnums[next]) + next++; + if(nums[next]<=val) + break; + nums[j]=nums[next]; + j=next; + next = 2*j+1; //2*j+1, 2*j+2 are the children of j + } + nums[j]=val; + } + return nums; +} diff --git a/Insertion Sort/InsertionSort.py b/Insertion Sort/InsertionSort.py new file mode 100644 index 0000000..b5751b4 --- /dev/null +++ b/Insertion Sort/InsertionSort.py @@ -0,0 +1,22 @@ +def InsertionSort(arr): + + for i in range(1, len(arr)): + + key = arr[i] + + j = i-1 + while j >=0 and key < arr[j] : + arr[j+1] = arr[j] + j -= 1 + arr[j+1] = key + + + +arr = [112, 1, 12213,44, 44] + +InsertionSort(arr) +print ("Sorted Array: ") +for i in range(len(arr)): + print ("%d" %arr[i]) + + diff --git a/Insertion Sort/insertionsort.cpp b/Insertion Sort/insertionsort.cpp new file mode 100644 index 0000000..4743f61 --- /dev/null +++ b/Insertion Sort/insertionsort.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +int main() +{ + int n; + cin>>n; + cout<<'\n'; + int *a=new int[n]; + for(int i=0;i<=n-1;i++){ + cin>>a[i]; + } + + + for(int i=1;i<=n-1;i++){ + int j=i-1; + int temp =a[i]; + while(j>=0&&a[j]>temp){ + a[j+1]=a[j]; + j--; + } + a[j+1]=temp; + + } + + for(int i=0;i<=n-1;i++){ + cout<< a[i]; + } + return 0; +} \ No newline at end of file diff --git a/Jump Search/jump.java b/Jump Search/jump.java new file mode 100644 index 0000000..0e581e4 --- /dev/null +++ b/Jump Search/jump.java @@ -0,0 +1,19 @@ + bool canJump(vector& nums) { + int n = nums.size(); + vector jump(n,false); + jump[n-1]=true; + + for(int i=n-2;i>=0;i--) + { + for(int j=0;j<=nums[i] && i+j= n: + return -1 + + # Doing a linear search for x in + # block beginning with prev. + while arr[int(prev)] < x: + prev += 1 + + # 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[int(prev)] == x: + return prev + + return -1 + +# Driver code to test function +arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 ] +x = 55 +n = len(arr) + +# Find the index of 'x' using Jump Search +index = jumpSearch(arr, x, n) + +# Print the index where 'x' is located +print("Number" , x, "is at index" ,"%.0f"%index) + +# This code is contributed by "Sharad_Bhardwaj". diff --git a/Jump Search/jumpSearch.js b/Jump Search/jumpSearch.js new file mode 100644 index 0000000..af2b978 --- /dev/null +++ b/Jump Search/jumpSearch.js @@ -0,0 +1,26 @@ +function jumpSearch(arr, target) { + + let len = arr.length + let step = Math.floor(Math.sqrt(len)); + let blockStart = 0, currentStep = step; + + while (arr[Math.min(currentStep, len) - 1] < target) { + blockStart = currentStep; + currentStep += step; + + if (blockStart >= len) + return -1; + } + + while (arr[blockStart] < target) + { + blockStart++; + if (blockStart == Math.min(currentStep, len)) + return -1; + } + + if (arr[blockStart] == target) + return blockStart + else + return -1; +} diff --git a/KMP Algorithm/KMP_1.java b/KMP Algorithm/KMP_1.java new file mode 100644 index 0000000..afabf65 --- /dev/null +++ b/KMP Algorithm/KMP_1.java @@ -0,0 +1,47 @@ +public String shortestPalindrome(String s) { + String temp = s + "#" + new StringBuilder(s).reverse().toString(); + int[] table = getTable(temp); + + //get the maximum palin part in s starts from 0 + return new StringBuilder(s.substring(table[table.length - 1])).reverse().toString() + s; +} + +public int[] getTable(String s){ + //get lookup table + int[] table = new int[s.length()]; + + //pointer that points to matched char in prefix part + + int index = 0; + //skip index 0, we will not match a string with itself + for(int i = 1; i < s.length(); i++){ + if(s.charAt(index) == s.charAt(i)){ + //we can extend match in prefix and postfix + table[i] = table[i-1] + 1; + index ++; + }else{ + //match failed, we try to match a shorter substring + + //by assigning index to table[i-1], we will shorten the match string length, and jump to the + //prefix part that we used to match postfix ended at i - 1 + index = table[i-1]; + + while(index > 0 && s.charAt(index) != s.charAt(i)){ + //we will try to shorten the match string length until we revert to the beginning of match (index 1) + index = table[index-1]; + } + + //when we are here may either found a match char or we reach the boundary and still no luck + //so we need check char match + if(s.charAt(index) == s.charAt(i)){ + //if match, then extend one char + index ++ ; + } + + table[i] = index; + } + + } + + return table; +} diff --git a/KMP Algorithm/KMP_Algo.py b/KMP Algorithm/KMP_Algo.py new file mode 100644 index 0000000..1c08950 --- /dev/null +++ b/KMP Algorithm/KMP_Algo.py @@ -0,0 +1,58 @@ +def kmpAlgo(patt, recurr): + x = len(patt) + y = len(recurr) + + + lps = [0]*x + j = 0 + + + computeLPSArray(patt, x, lps) + + i = 0 + while i < y: + if patt[j] == recurr[i]: + i += 1 + j += 1 + + if j == x: + print ("Found pattern at index " + str(i-j)) + j = lps[j-1] + + + elif i < y and patt[j] != recurr[i]: + x + if j != 0: + j = lps[j-1] + else: + i += 1 + +def computeLPSArray(patt, x, lps): + len = 0 + + lps[0] + i = 1 + + + while i < x: + if patt[i]== patt[len]: + len += 1 + lps[i] = len + i += 1 + else: + + if len != 0: + len = lps[len-1] + + + else: + lps[i] = 0 + i += 1 + + + + + +kmpAlgo(recurr = input("Enter pattern "), patt = input("Enter Reccuring pattern ")) + + diff --git a/KMP Algorithm/kmp.java b/KMP Algorithm/kmp.java new file mode 100644 index 0000000..6756b46 --- /dev/null +++ b/KMP Algorithm/kmp.java @@ -0,0 +1,81 @@ +class KMP_String_Matching { + void KMPSearch(String pat, String txt) + { + int M = pat.length(); + int N = txt.length(); + + // create lps[] that will hold the longest + // prefix suffix values for pattern + int lps[] = new int[M]; + int j = 0; // index for pat[] + + // Preprocess the pattern (calculate lps[] + // array) + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt[] + while (i < N) { + if (pat.charAt(j) == txt.charAt(i)) { + j++; + i++; + } + if (j == M) { + System.out.println("Found pattern " + + "at index " + (i - j)); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && pat.charAt(j) != txt.charAt(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; + } + } + } + + void computeLPSArray(String pat, int M, int lps[]) + { + // length of the previous longest prefix suffix + int len = 0; + int i = 1; + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + while (i < M) { + if (pat.charAt(i) == pat.charAt(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] = len; + i++; + } + } + } + } + + // Driver program to test above function + public static void main(String args[]) + { + String txt = "ABABDABACDABABCABAB"; + String pat = "ABABCABAB"; + new KMP_String_Matching().KMPSearch(pat, txt); + } +} diff --git a/Linear Search/linearsearch.js b/Linear Search/linearsearch.js new file mode 100644 index 0000000..5252e70 --- /dev/null +++ b/Linear Search/linearsearch.js @@ -0,0 +1,8 @@ +function linearSearch(arr, key){ + for(let i = 0; i < arr.length; i++){ + if(arr[i] === key){ + return i + } + } + return -1 +} diff --git a/Linked LIst/reverse-a-inkedlist.js b/Linked LIst/reverse-a-inkedlist.js new file mode 100644 index 0000000..a5a4d35 --- /dev/null +++ b/Linked LIst/reverse-a-inkedlist.js @@ -0,0 +1,47 @@ +// JavaScript program for reversing the linked list + +var head; + + class Node { + constructor(val) { + this.data = val; + this.next = null; + } + } + + /* Function to reverse the linked list */ + function reverse(node) { + var prev = null; + var current = node; + var next = null; + while (current != null) { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + node = prev; + return node; + } + + // prints content of var linked list + function printList(node) { + while (node != null) { + document.write(node.data + " "); + node = node.next; + } + } + + // Driver Code + + head = new Node(85); + head.next = new Node(15); + head.next.next = new Node(4); + head.next.next.next = new Node(20); + + document.write("Given Linked list
"); + printList(head); + head = reverse(head); + document.write("
"); + document.write("Reversed linked list
"); + printList(head); \ No newline at end of file diff --git a/Luhn algorithm/Luhn.py b/Luhn algorithm/Luhn.py new file mode 100644 index 0000000..c267c9b --- /dev/null +++ b/Luhn algorithm/Luhn.py @@ -0,0 +1,23 @@ +""" + Luhn algorithm or Luhn formula + Checksum algorithm. + Source:https://en.wikipedia.org/wiki/Luhn_algorithm + +""" + +def luhn(input_number): + + input_number = [int(i) for i in str(input_number)] + input_number.reverse() + + sum_answer = 0 + for i, number in enumerate(input_number): + temp = number + if i % 2 == 0: + temp = number * 2 + if temp > 9: + temp -= 9 + + sum_answer = sum_answer + temp + + return sum_answer % 10 == 0 diff --git a/MST/Kruskals.cpp b/MST/Kruskals.cpp new file mode 100644 index 0000000..524bf1a --- /dev/null +++ b/MST/Kruskals.cpp @@ -0,0 +1,84 @@ +#include +using namespace std; +class edge +{ + public: + int src; + int dest; + int weight; +}; +bool comapare(edge e1,edge e2) +{ + return (e1.weight >v>>e; + edge *edges = new edge[e]; + for(int i=0;i>x>>y>>z; + edges[i].src =x; + edges[i].dest =y; + edges[i].weight =z; + } + edge *output =kruskal(edges,v,e); + for(int i=0;i +using namespace std; +int getminVertex(vector &weight,vector &visited,int n) +{ + int mini = -1; + for(int i=0;i> a,int n,int e) +{ + vector weight(n,INT_MAX); + vector parent(n); + vector visited(n,false); + parent[0]=-1; + weight[0]=1; + for(int i=0;i a[minvertex][j]) + { + weight[j] = a[minvertex][j]; + parent[j] =minvertex; + } + } + } + } + for(int i=1;i>n>>e; + vector> mat(n,vector (n)); + int x,y,weight; + for(int i=0;i>x>>y>>weight; + mat[x][y]=weight; + mat[y][x]=weight; + + } + prims(mat,n,e); + + + return 0; +} \ No newline at end of file diff --git a/MST/prims.py b/MST/prims.py new file mode 100644 index 0000000..ce969f1 --- /dev/null +++ b/MST/prims.py @@ -0,0 +1,37 @@ +# Prim's Algorithm in Python + +INF = 9999999 +# number of vertices in graph +N = 5 +#creating graph by adjacency matrix method +G = [[0, 19, 5, 0, 0], + [19, 0, 5, 9, 2], + [5, 5, 0, 1, 6], + [0, 9, 1, 0, 1], + [0, 2, 6, 1, 0]] + +selected_node = [0, 0, 0, 0, 0] + +no_edge = 0 + +selected_node[0] = True + +# printing for edge and weight +print("Edge : Weight\n") +while (no_edge < N - 1): + + minimum = INF + a = 0 + b = 0 + for m in range(N): + if selected_node[m]: + for n in range(N): + if ((not selected_node[n]) and G[m][n]): + # not in selected and there is an edge + if minimum > G[m][n]: + minimum = G[m][n] + a = m + b = n + print(str(a) + "-" + str(b) + ":" + str(G[a][b])) + selected_node[b] = True + no_edge += 1 diff --git a/MergeSort/MERGE_1.java b/MergeSort/MERGE_1.java new file mode 100644 index 0000000..d0b96ae --- /dev/null +++ b/MergeSort/MERGE_1.java @@ -0,0 +1,40 @@ +class Solution { + public int[] sortArray(int[] nums) { + int N = nums.length; + mergeSort(nums, 0, N-1); + return nums; + } + + + void mergeSort(int[] nums, int start, int end){ + if (end - start+1 <= 1) return; //Already sorted. + int mi = start + (end - start)/ 2; + mergeSort(nums, start, mi); + mergeSort(nums, mi+1, end); + merge(nums, start,mi, end); + } + + void merge(int[] nums, int start, int mi, int end){ + int lp = start; + int rp = mi + 1; + int[] buffer = new int[end-start+1]; + int t = 0; //buffer pointer + + while (lp <= mi && rp <= end){ + if (nums[lp] < nums[rp]){ + buffer[t++] = nums[lp++]; + }else{ + buffer[t++] = nums[rp++]; + } + } + + while (lp <= mi) buffer[t++] = nums[lp++]; + while (rp <= end) buffer[t++] = nums[rp++]; + //Now copy sorted buffer into original array + for (int i = start; i <= end; i++){ + nums[i] = buffer[i-start]; + } + } + + +} diff --git a/MergeSort/MergeSort.cpp b/MergeSort/MergeSort.cpp new file mode 100755 index 0000000..2b88af6 --- /dev/null +++ b/MergeSort/MergeSort.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include +using namespace std; +using LL = long long; +using ULL = unsigned long long; +#define FOR(i,a,b) for(int i = a; i < b; i++) +#define DFOR(i,a,b) for(int i = a; i > b; i--) + +void merge(int ar[],int lo,int mid,int hi){ + int p1=lo,p2=mid+1,temp[hi-lo+1],k=0; + while(p1<=mid && p2<=hi){ + if(ar[p1] < ar[p2]){ + temp[k++] = ar[p1++]; + } + else{ + temp[k++] = ar[p2++]; + } + } + while(p1<=mid){ + temp[k++] = ar[p1++]; + } + while(p2<=hi){ + temp[k++] = ar[p2++]; + } + FOR(i,0,hi-lo+1){ + ar[i+lo] = temp[i]; + } +} + +void MS(int ar[],int lo,int hi){ + if(lo==hi){ + return; + } + int mid = (lo+hi)/2; + MS(ar,lo,mid); + MS(ar,mid+1,hi); + merge(ar,lo,mid,hi); +} +int main(){ + ios_base::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + int t; + cin >> t; + FOR(i,0,t){ + int n,k; + cin >> n >> k; + int a[n]; + FOR(j,0,n){ + cin >> a[j]; + } + MS(a,0,n-1); + FOR(j,0,n){ + cout << a[j] << " "; + } + } + return 0; +} \ No newline at end of file diff --git a/QuickSort/QuickSort.java b/QuickSort/QuickSort.java new file mode 100644 index 0000000..2c1da03 --- /dev/null +++ b/QuickSort/QuickSort.java @@ -0,0 +1,58 @@ +public class Quick +{ + /* function that consider last element as pivot, +place the pivot at its exact position, and place +smaller elements to left of pivot and greater +elements to right of pivot. */ +int partition (int a[], int start, int end) +{ + int pivot = a[end]; // pivot element + int i = (start - 1); + + for (int j = start; j <= end - 1; j++) + { + // If current element is smaller than the pivot + if (a[j] < pivot) + { + i++; // increment index of smaller element + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } + } + int t = a[i+1]; + a[i+1] = a[end]; + a[end] = t; + return (i + 1); +} + +/* function to implement quick sort */ +void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index */ +{ + if (start < end) + { + int p = partition(a, start, end); //p is partitioning index + quick(a, start, p - 1); + quick(a, p + 1, end); + } +} + +/* function to print an array */ +void printArr(int a[], int n) +{ + int i; + for (i = 0; i < n; i++) + System.out.print(a[i] + " "); +} + public static void main(String[] args) { + int a[] = { 13, 18, 27, 2, 19, 25 }; + int n = a.length; + System.out.println("\nBefore sorting array elements are - "); + Quick q1 = new Quick(); + q1.printArr(a, n); + q1.quick(a, 0, n - 1); + System.out.println("\nAfter sorting array elements are - "); + q1.printArr(a, n); + System.out.println(); + } +} diff --git a/README.md b/README.md index 37f16dc..c92c462 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,19 @@ # AlgorithmBank Help us make a deposit of algorithms. -#Rules to Contribute- - +# Rules to Contribute +-Check the issues section for new issues.
-Add alogorithms under Algorithm Name/Algorithm File.
-You can contribute in any language.
-You can also raise issues to verify with us.
--You can edit existing algorithms,if it is not right, But please raise an issue if you are doing this to verify with us. - +-You can edit existing algorithms,if it is not right. +# Contributors + + + + -If you need the PR for HacktoberFest 2021, plaese comment it and let us know. +If you need the PR for HacktoberFest 2021, please comment it and let us know. Happy coding. diff --git a/Radix sort/Radix_sort.cpp b/Radix sort/Radix_sort.cpp new file mode 100644 index 0000000..927cf97 --- /dev/null +++ b/Radix sort/Radix_sort.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; +void display(int *array, int size) { + for(int i = 0; i pocket[10]; + for(i = 0; i< max; i++) { + m = pow(10, i+1); + p = pow(10, i); + for(j = 0; j> n; + cout << "Enter the maximum digit of elements: "; + cin >> max; + int arr[n]; + cout << "Enter elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Data before Sorting: "; + display(arr, n); + radixSort(arr, n, max); + cout << "Data after Sorting: "; + display(arr, n); +} diff --git a/Selection sort/SelSort.java b/Selection sort/SelSort.java new file mode 100644 index 0000000..24b148c --- /dev/null +++ b/Selection sort/SelSort.java @@ -0,0 +1,32 @@ +public class SelectionSortExample { + public static void selectionSort(int[] arr){ + for (int i = 0; i < arr.length - 1; i++) + { + int index = i; + for (int j = i + 1; j < arr.length; j++){ + if (arr[j] < arr[index]){ + index = j;//searching for lowest index + } + } + int smallerNumber = arr[index]; + arr[index] = arr[i]; + arr[i] = smallerNumber; + } + } + + public static void main(String a[]){ + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Selection Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + System.out.println(); + + selectionSort(arr1);//sorting array using selection sort + + System.out.println("After Selection Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + } +} diff --git a/Tree/tree_dsa.cpp b/Tree/tree_dsa.cpp new file mode 100644 index 0000000..5b96ed8 --- /dev/null +++ b/Tree/tree_dsa.cpp @@ -0,0 +1,129 @@ +#include +using namespace std; +#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +typedef long long ll; +const ll mod=1e9+7; +//<------disjoint set-union------> +vectorparent,size; +void make_set(int v) { + parent[v] = v; + size[v] = 1; +} + +void union_sets(int a, int b) { + a = find_set(a); + b = find_set(b); + if (a != b) { + if (size[a] < size[b]) + swap(a, b); + parent[b] = a; + size[a] += size[b]; + } +} + +int find_set(int v) { + if (v == parent[v]) + return v; + return find_set(parent[v]); +} + +//<-----------fenwick tree---------> +struct FenwickTree { + vector bit; // binary indexed tree + int n; + + FenwickTree(int n) { + this->n = n; + bit.assign(n, 0); + } + + FenwickTree(vector a) : FenwickTree(a.size()) { + for (size_t i = 0; i < a.size(); i++) + add(i, a[i]); + } + + int sum(int r) { + int ret = 0; + for (; r >= 0; r = (r & (r + 1)) - 1) + ret += bit[r]; + return ret; + } + + int sum(int l, int r) { + return sum(r) - sum(l - 1); + } + + void add(int idx, int delta) { + for (; idx < n; idx = idx | (idx + 1)) + bit[idx] += delta; + } +}; + +//<-------------square root decomposition--------------> + +void sqrt_decmpO(){ +//input data +int n; +vector a (n); + +// preprocessing +int len = (int) sqrt (n + .0) + 1; // size of the block and the number of blocks +vector b (len); +for (int i=0; i +int MAXN; +int n; +vectort(4*MAXN); +void build(int a[], int v, int tl, int tr) { + if (tl == tr) { + t[v] = a[tl]; + } else { + int tm = (tl + tr) / 2; + build(a, v*2, tl, tm); + build(a, v*2+1, tm+1, tr); + t[v] = t[v*2] + t[v*2+1]; + } +} +int sum(int v, int tl, int tr, int l, int r) { + if (l > r) + return 0; + if (l == tl && r == tr) { + return t[v]; + } + int tm = (tl + tr) / 2; + return sum(v*2, tl, tm, l, min(r, tm)) + + sum(v*2+1, tm+1, tr, max(l, tm+1), r); +} +void update(int v, int tl, int tr, int pos, int new_val) { + if (tl == tr) { + t[v] = new_val; + } else { + int tm = (tl + tr) / 2; + if (pos <= tm) + update(v*2, tl, tm, pos, new_val); + else + update(v*2+1, tm+1, tr, pos, new_val); + t[v] = t[v*2] + t[v*2+1]; + } +} diff --git a/adler32 hash/adler32.py b/adler32 hash/adler32.py new file mode 100644 index 0000000..3e886cf --- /dev/null +++ b/adler32 hash/adler32.py @@ -0,0 +1,18 @@ +''' +Old database hashfunction. +Source: +https://en.wikipedia.org/wiki/Adler-32 +https://www.youtube.com/watch?v=BWqH4O7OuyY +''' + +def adler32(input_plain_text): + A = 1 + B = 0 + m = 65521 + for char in input_plain_text: + A = (A + ord(char)) % m + B = (B + A) % m + hash = (B << 16) | A + return hash + + diff --git a/djb2 hash/djb2.py b/djb2 hash/djb2.py new file mode 100644 index 0000000..e4098ae --- /dev/null +++ b/djb2 hash/djb2.py @@ -0,0 +1,19 @@ +''' +Old hashfunction. + +Explaination: +(magic_hash_nr + (magic_hash_nr << 5)) is equivalent to (magic_hash_nr*33). +This because the bit shift of <<5 is multiplying by 32 then we add another one. + +Source: +http://www.cse.yorku.ca/~oz/hash.html +https://stackoverflow.com/questions/1579721/why-are-5381-and-33-so-important-in-the-djb2-algorithm +''' + + +def djb2(input_plain_text): + magic_hash_nr = 5381 + for char in input_plain_text: + magic_hash_nr = ord(char) + (magic_hash_nr + (magic_hash_nr << 5)) + magic_hash_nr = magic_hash_nr & 0xFFFFFFFF + return magic_hash_nr \ No newline at end of file diff --git a/hufman code/hufman_code.c b/hufman code/hufman_code.c new file mode 100644 index 0000000..1972c04 --- /dev/null +++ b/hufman code/hufman_code.c @@ -0,0 +1,181 @@ +// Huffman Coding in C + +#include +#include + +#define MAX_TREE_HT 50 + +struct MinHNode { + char item; + unsigned freq; + struct MinHNode *left, *right; +}; + +struct MinHeap { + unsigned size; + unsigned capacity; + struct MinHNode **array; +}; + +// Create nodes +struct MinHNode *newNode(char item, unsigned freq) { + struct MinHNode *temp = (struct MinHNode *)malloc(sizeof(struct MinHNode)); + + temp->left = temp->right = NULL; + temp->item = item; + temp->freq = freq; + + return temp; +} + +// Create min heap +struct MinHeap *createMinH(unsigned capacity) { + struct MinHeap *minHeap = (struct MinHeap *)malloc(sizeof(struct MinHeap)); + + minHeap->size = 0; + + minHeap->capacity = capacity; + + minHeap->array = (struct MinHNode **)malloc(minHeap->capacity * sizeof(struct MinHNode *)); + return minHeap; +} + +// Function to swap +void swapMinHNode(struct MinHNode **a, struct MinHNode **b) { + struct MinHNode *t = *a; + *a = *b; + *b = t; +} + +// Heapify +void minHeapify(struct MinHeap *minHeap, int idx) { + int smallest = idx; + int left = 2 * idx + 1; + int right = 2 * idx + 2; + + if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) + smallest = left; + + if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) + smallest = right; + + if (smallest != idx) { + swapMinHNode(&minHeap->array[smallest], &minHeap->array[idx]); + minHeapify(minHeap, smallest); + } +} + +// Check if size if 1 +int checkSizeOne(struct MinHeap *minHeap) { + return (minHeap->size == 1); +} + +// Extract min +struct MinHNode *extractMin(struct MinHeap *minHeap) { + struct MinHNode *temp = minHeap->array[0]; + minHeap->array[0] = minHeap->array[minHeap->size - 1]; + + --minHeap->size; + minHeapify(minHeap, 0); + + return temp; +} + +// Insertion function +void insertMinHeap(struct MinHeap *minHeap, struct MinHNode *minHeapNode) { + ++minHeap->size; + int i = minHeap->size - 1; + + while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { + minHeap->array[i] = minHeap->array[(i - 1) / 2]; + i = (i - 1) / 2; + } + minHeap->array[i] = minHeapNode; +} + +void buildMinHeap(struct MinHeap *minHeap) { + int n = minHeap->size - 1; + int i; + + for (i = (n - 1) / 2; i >= 0; --i) + minHeapify(minHeap, i); +} + +int isLeaf(struct MinHNode *root) { + return !(root->left) && !(root->right); +} + +struct MinHeap *createAndBuildMinHeap(char item[], int freq[], int size) { + struct MinHeap *minHeap = createMinH(size); + + for (int i = 0; i < size; ++i) + minHeap->array[i] = newNode(item[i], freq[i]); + + minHeap->size = size; + buildMinHeap(minHeap); + + return minHeap; +} + +struct MinHNode *buildHuffmanTree(char item[], int freq[], int size) { + struct MinHNode *left, *right, *top; + struct MinHeap *minHeap = createAndBuildMinHeap(item, freq, size); + + while (!checkSizeOne(minHeap)) { + left = extractMin(minHeap); + right = extractMin(minHeap); + + top = newNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + insertMinHeap(minHeap, top); + } + return extractMin(minHeap); +} + +void printHCodes(struct MinHNode *root, int arr[], int top) { + if (root->left) { + arr[top] = 0; + printHCodes(root->left, arr, top + 1); + } + if (root->right) { + arr[top] = 1; + printHCodes(root->right, arr, top + 1); + } + if (isLeaf(root)) { + printf(" %c | ", root->item); + printArray(arr, top); + } +} + +// Wrapper function +void HuffmanCodes(char item[], int freq[], int size) { + struct MinHNode *root = buildHuffmanTree(item, freq, size); + + int arr[MAX_TREE_HT], top = 0; + + printHCodes(root, arr, top); +} + +// Print the array +void printArray(int arr[], int n) { + int i; + for (i = 0; i < n; ++i) + printf("%d", arr[i]); + + printf("\n"); +} + +int main() { + char arr[] = {'A', 'B', 'C', 'D'}; + int freq[] = {5, 1, 6, 3}; + + int size = sizeof(arr) / sizeof(arr[0]); + + printf(" Char | Huffman code "); + printf("\n--------------------\n"); + + HuffmanCodes(arr, freq, size); +} \ No newline at end of file diff --git a/rabin_karp_algorithm/Rabin.java b/rabin_karp_algorithm/Rabin.java new file mode 100644 index 0000000..36f0fa3 --- /dev/null +++ b/rabin_karp_algorithm/Rabin.java @@ -0,0 +1,68 @@ +public class Main { + // d is the number of characters in the input alphabet + public final static int d = 256; + + /* pat -> pattern + txt -> text + q -> A prime number + */ + static void search(String pat, String txt, int q) + { + int M = pat.length(); + int N = txt.length(); + 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.charAt(i)) % q; + t = (d * t + txt.charAt(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.charAt(i + j) != pat.charAt(j)) + break; + } + + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] + if (j == M) + System.out.println("Pattern found at index " + i); + } + + // Calculate hash value for next window of text: Remove + // leading digit, add trailing digit + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(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 */ + public static void main(String[] args) + { + String txt = "GEEKS FOR GEEKS"; + String pat = "GEEK"; + int q = 101; // A prime number + search(pat, txt, q); + } +} diff --git a/rabin_karp_algorithm/rabin-karp_algorithm.py b/rabin_karp_algorithm/rabin-karp_algorithm.py new file mode 100644 index 0000000..9aabe6e --- /dev/null +++ b/rabin_karp_algorithm/rabin-karp_algorithm.py @@ -0,0 +1,69 @@ +d = 265 + +# pat -> pattern +# txt -> text +# prime -> A prime number + + +def search(pat, txt, prime): + + M = len(pat) + + N = len(txt) + i = 0 + j = 0 + p = 0 + t = 0 + + h = 1 + + for i in xrange(M-1): + + h = (h*d)%prime + + + for i in xrange(M): + + p = (d*p + ord(pat[i]))%prime + + t = (d*t + ord(txt[i]))%prime + + + for i in xrange(N-M+1): + + if p==t: + + for j in xrange(M): + + if txt[i+j] != pat[j]: + + break + + else: j+=1 + + if j==M: + + print "Pattern found at index " + str(i) + + + if i < N-M: + + t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%prime + + + if t < 0: + + t = t+prime + + + +txt = "I AM CHAITANYA" + +pat = "AM" + + + +prime= 101 + +# Function Call +search(pat,txt, prime) diff --git a/sdbm hash/sdbm.py b/sdbm hash/sdbm.py new file mode 100644 index 0000000..d4ecd1c --- /dev/null +++ b/sdbm hash/sdbm.py @@ -0,0 +1,15 @@ +''' +Old database hashfunction. +Source: +https://api.riot-os.org/group__sys__hashes__sdbm.html +http://www.cse.yorku.ca/~oz/hash.html +Docs for ord: https://docs.python.org/3/library/functions.html#ord +Returns the unicode character of a char. +''' + + +def sdbm(input_plain_text): + hash_output = 0 + for char in input_plain_text: + hash_output = ord(char) + (hash_output << 6) + (hash_output << 16) - hash_output + return hash_output \ No newline at end of file