0% found this document useful (0 votes)
28 views

All DAA Codes

Uploaded by

darjiyaksh8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

All DAA Codes

Uploaded by

darjiyaksh8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Divide and Conquer:

#include<stdio.h>
int b[10],a[10];
int ctr = 0;
//merging of arrays

void merge(int a[] , int lb , int mid, int ub ){


int i=lb , j=mid+1 , k = lb;
while(i<=mid && j<=ub){
if (a[i] <= a[j])
{
b[k] = a[i];
i++;
}
else
{
b[k] = a[j];
j++;
}
k++;
}
if(i > mid){
while (j <= ub)
{
b[k] = a[j];
j++;
k++;
}
}
else{
while (i <= mid){
b[k] = a[i];
i++;
k++;
}
}
// array copy
for (int i = lb; i <= ub; i++) {
a[i] = b[i];
}
}

void mergeSort(int a[] ,int lb ,int ub){


int mid;
mid = (lb+ub)/2;
if (lb < ub)
{
mergeSort(a,lb,mid);
mergeSort(a,mid+1,ub);
merge(a,lb,mid,ub); // count the conquer step
}
ctr++; // count the divide step

}
int main(){
int n,i;
printf("Enter the number of elements:\n");
scanf("%d",&n);
//array input
for (int i = 0; i < n; i++)
{
printf("Enter the element %d:\n",i+1);
scanf("%d",&a[i]);
}
mergeSort(a,0,n-1);
printf("Sorted array:\n");
for ( i = 0; i < n; i++)
{
printf("%d\n",a[i]);
}

printf("No of divide and conquer steps: %d\n",ctr);


return 0;
}

Greedy:

#include<stdio.h>
#include<conio.h>

void coinchanging(int coins[] , int n , int amount){

int coincount = 0;

for (int i = n-1; i >= 0; i--)


{
while(amount >= coins[i]){
amount = amount - coins[i];
coincount++;
}
}

printf("Minimum number of coins needed: %d\n",coincount);


}
int main(){
int n;
printf("Enter number of coins:\n");
scanf("%d",&n);
int coins[100];
for (int i = 0; i < n; i++)
{
printf("Enter the value of coin %d:\n",i);
scanf("%d",&coins[i]);
}
int amount;
printf("Enter the amount to make change for:\n");
scanf("%d",&amount);

coinchanging(coins , n , amount);

return 0;
}

2.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define V 5 // Number of vertices in the graph

// Function to find the vertex with maximum bandwidth value, from the set of
vertices not yet included in max bandwidth tree
int maxBandwidthVertex(int bandwidth[], bool mstSet[]) {
int max = INT_MIN, max_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == false && bandwidth[v] >= max) {
max = bandwidth[v];
max_index = v;
}
}
return max_index;
}

// Function to find the maximum bandwidth path using Dijkstra's algorithm


void dijkstraMaxBandwidth(int graph[V][V], int src, int dest) {
int* bandwidth = (int*)malloc(V * sizeof(int)); // The output array to
store maximum bandwidth from src to i
bool* mstSet = (bool*)malloc(V * sizeof(bool)); // mstSet[i] will be true
if vertex i is included in max bandwidth tree or maximum bandwidth from src to
i is finalized
// Initialize all bandwidth values as 0 and mstSet[] as false
for (int i = 0; i < V; i++) {
bandwidth[i] = 0;
mstSet[i] = false;
}

// Bandwidth of source vertex from itself is the maximum possible


bandwidth[src] = INT_MAX;

// Find maximum bandwidth path for all vertices


for (int count = 0; count < V - 1; count++) {
int u = maxBandwidthVertex(bandwidth, mstSet); // Pick the vertex with
maximum bandwidth from the set of vertices not yet processed

mstSet[u] = true; // Mark the picked vertex as processed

// Update bandwidth value of the adjacent vertices of the picked


vertex
for (int v = 0; v < V; v++) {
if (!mstSet[v] && graph[u][v] != 0) {
bandwidth[v] = bandwidth[u] < graph[u][v] ? bandwidth[u] :
graph[u][v];
}
}5
}

// Print the maximum bandwidth path from source to destination


printf("Maximum Bandwidth Path from %d to %d: %d\n", src, dest,
bandwidth[dest]);
}

int main() {
// Create a graph represented as an adjacency matrix
int graph[V][V];

// Input graph
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (i == j)
{
graph[i][j] = 0;
}
else
{
printf("Enter the weight of edge between %d and %d:\n",i,j);
scanf("%d",&graph[i][j]);
}
}
}

// Find maximum bandwidth path from source to destination


dijkstraMaxBandwidth(graph, 0, 4); // Source: 0, Destination: 4

return 0;
}

3.

#include<stdio.h>
#include<conio.h>
float weight[50],profit[50],ratio[50];

void knapsack(int n , int capacity){


float total = 0;
int i,j;
for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
{
break;
}
else
{
total = total + profit[i];
capacity = capacity - weight[i];
}
}

if (weight[i] > capacity)


{
total = total + (ratio[i] * capacity);
}

printf("Total profit is %f",total);

void sort(int n){


for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
float temp;
if (ratio[i]<ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;

temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
}
void main(){
int n;
printf("Enter number of items:\n");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
printf("Enter weight of item %d:\n",i);
scanf("%f",&weight[i]);
}

for (int i = 0; i < n; i++)


{
printf("Enter profit of item %d:\n",i);
scanf("%f",&profit[i]);
}

for (int i = 0; i < n; i++)


{
ratio[i] = profit[i]/weight[i];
}

int capacity;
printf("Enter capacity of knapsack:\n");
scanf("%d",&capacity);

sort(n);

knapsack(n , capacity);
}

4.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define V 5 // Number of vertices in the graph

// Function to find the vertex with minimum key value, from the set of
vertices not yet included in MST
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}

// Function to print the MST


void printMST(int parent[], int graph[V][V]) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}

// Function to implement Prim's algorithm to find MST


void primMST(int graph[V][V]) {
int parent[V]; // Array to store constructed MST
int key[V]; // Key values used to pick minimum weight edge in cut
bool mstSet[V]; // To represent set of vertices not yet included in MST

// Initialize all keys as INFINITE, mstSet[] as false


for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = false;
}

// Include first vertex in MST


key[0] = 0; // Make key 0 so that this vertex is picked as first vertex
parent[0] = -1; // First node is always root of MST
// Construct MST for the rest V-1 vertices
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet); // Pick the minimum key vertex from the
set of vertices not yet included in MST
mstSet[u] = true; // Add the picked vertex to the MST
printf("Added vertex %d to MST\n", u);

// Update key value and parent index of the adjacent vertices of the
picked vertex
for (int v = 0; v < V; v++) {
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
printf(" Updated key value of vertex %d to %d\n", v, key[v]);
}
}
}

// Print the constructed MST


printMST(parent, graph);
}

int main() {
/* Let us create the following graph
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int graph[V][V] = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}};

// Print the MST using Prim's algorithm


primMST(graph);

return 0;
}

DP:
#include <stdio.h>

// Function to find the maximum of two integers


int max(int a, int b) {
return (a > b) ? a : b;
}

// Function to solve 0/1 knapsack problem


int knapsack(int weights[], int values[], int capacity, int n) {
int dp[n + 1][capacity + 1];

// Build dp table
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= capacity; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (weights[i - 1] <= w) {
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]],
dp[i - 1][w]);
printf("dp[%d][%d] = %d\n", i, w, dp[i][w]);
}
else
dp[i][w] = dp[i - 1][w];
}
}

// Trace back the items included in the knapsack


int selected_items[n];
int k = 0;
int w = capacity;
for (int i = n; i > 0 && w > 0; i--) {
if (dp[i][w] != dp[i - 1][w]) {
selected_items[k++] = i - 1;
w -= weights[i - 1];
}
}

// Print selected items


printf("Selected items: ");
for (int i = k - 1; i >= 0; i--)
printf("%d ", selected_items[i]);
printf("\n");

// Return maximum value


return dp[n][capacity];
}

int main() {
int weights[] = {2, 3, 4, 5};
int values[] = {3, 4, 5, 6};
int capacity = 5;
int n = sizeof(values) / sizeof(values[0]);

printf("Capacity: %d\n", capacity);


printf("Weights: ");
for (int i = 0; i < n; i++)
printf("%d ", weights[i]);
printf("\n");
printf("Values: ");
for (int i = 0; i < n; i++)
printf("%d ", values[i]);
printf("\n");

int max_value = knapsack(weights, values, capacity, n);


printf("Maximum value: %d\n", max_value);

return 0;
}

2.

#include <stdio.h>
#include <limits.h>

#define MAX_VERTICES 100 // Maximum number of vertices in the graph


#define MAX_EDGES 100 // Maximum number of edges in the graph

// Function to perform Bellman-Ford algorithm


void bellmanFord(int graph[][3], int numVertices, int numEdges, int source) {
int distance[MAX_VERTICES];

// Step 1: Initialize distances


for (int i = 0; i < numVertices; i++) {
distance[i] = INT_MAX;
}
distance[source] = 0;

// Step 2: Relax edges numVertices - 1 times


for (int i = 0; i < numVertices - 1; i++) {
for (int j = 0; j < numEdges; j++) {
int u = graph[j][0];
int v = graph[j][1];
int weight = graph[j][2];
printf("Processing edge (%d, %d) with weight %d\n", u, v, weight);
printf("Current distance to %d: %d\n", v, distance[v]);
if (distance[u] != INT_MAX && distance[u] + weight < distance[v])
{
distance[v] = distance[u] + weight;
printf("Updated distance to %d: %d\n", v, distance[v]);
}
}
}

// Step 3: Check for negative cycles


for (int i = 0; i < numEdges; i++) {
int u = graph[i][0];
int v = graph[i][1];
int weight = graph[i][2];
if (distance[u] != INT_MAX && distance[u] + weight < distance[v]) {
printf("Graph contains negative weight cycle\n");
return;
}
}

// Print the shortest distances


printf("Vertex\tDistance from Source\n");
for (int i = 0; i < numVertices; i++) {
if (distance[i] == INT_MAX) {
printf("%d\tINF\n", i);
} else {
printf("%d\t%d\n", i, distance[i]);
}
}
}

int main() {
int numVertices, numEdges, source;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);

int graph[MAX_EDGES][3]; // Adjacency matrix representation: [source,


destination, weight]

printf("Enter the source vertex: ");


scanf("%d", &source);

printf("Enter the edges (source, destination, weight):\n");


for (int i = 0; i < numEdges; i++) {
scanf("%d %d %d", &graph[i][0], &graph[i][1], &graph[i][2]);
}
bellmanFord(graph, numVertices, numEdges, source);

return 0;
}

3.

#include <stdio.h>
int min_coins_change(int amount, int denominations[], int num_denominations)
{
int dp[amount + 1];
dp[0] = 0;
// intitaialize the table with infinity for all other amounts..
for (int i = 1; i <= amount; i++)
{
dp[i] = amount + 1;
}
printf("Considering denominations: ");
for (int i = 0; i <= amount; i++)
{
printf("%d ", dp[i]);
}

printf("\n");

for (int i = 0; i < num_denominations; i++)


{
for (int j = denominations[i]; j <= amount; j++)
{
if (dp[j - denominations[i]] + 1 < dp[j])
{
dp[j] = dp[j - denominations[i]] + 1;
}
}
}
int amt = amount;
int coins_used = dp[amt];
printf("Coins used: ");
while (amt > 0)
{
for (int i = 0; i < num_denominations; i++)
{
if (amt >= denominations[i] && dp[amt] == dp[amt -
denominations[i]] + 1)
{
printf("%d ", denominations[i]);
amt -= denominations[i];
break;
}
}
}
printf("\nNumber of coins used: %d\n", coins_used);
return coins_used;
}
int main()
{
int num_denominations;
printf("Enter the number of denominations: ");
scanf("%d", &num_denominations);
int denominations[num_denominations];
printf("Enter the denominations:\n");
for (int i = 0; i < num_denominations; i++)
{
scanf("%d", &denominations[i]);
}
int amount;
printf("Enter the amount to make: ");
scanf("%d", &amount);
int coins_used = min_coins_change(amount, denominations,
num_denominations);
return 0;
}

4.

#include <stdio.h>
#define V 5
#define INF 99999

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");
}
}

void floydWarshall(int dist[][V])


{
int i, j, k;

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);
}

int main()
{
int graph[V][V] = { { 0, 4, INF, 5,INF },
{ INF, 0, 1, INF,6 },
{ 2,INF, 0, 3,INF },
{ INF, INF, 1, 0,2},
{ 1,INF, INF, 4,0} };

floydWarshall(graph);
return 0;
}

5.

#include <stdio.h>
#include <string.h>

int max(int a, int b);


int lcs(char *X, char *Y, int i, int j)
{
if (X[i] == 0 || Y[j] == 0)
return 0;
if (X[i] == Y[j])
return 1 + lcs(X, Y, i + 1, j + 1);
else
return max(lcs(X, Y, i, j + 1), lcs(X, Y, i + 1, j));
}
int max(int a, int b) { return (a > b) ? a : b; }
int main()
{
char S1[] = "BD";
char S2[] = "ABCD";
int m = strlen(S1);
int n = strlen(S2);
int i = 0, j = 0;
printf("Length of LCS is %d", lcs(S1, S2, i, j));

return 0;
}

6.

#include <limits.h>
#include <stdio.h>

// Matrix Ai has dimension p[i-1] x p[i]


// for i = 1 . . . n
int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
return 0;
int k;
int min = INT_MAX;
int count;

printf("Calculating MatrixChainOrder(p, %d, %d)\n", i, j); // Print


statement for debugging

// Place parenthesis at different places


// between first and last matrix,
// recursively calculate count of multiplications
// for each parenthesis placement
// and return the minimum count
for (k = i; k < j; k++)
{
count = MatrixChainOrder(p, i, k)
+ MatrixChainOrder(p, k + 1, j)
+ p[i - 1] * p[k] * p[j];

printf("i=%d, k=%d, j=%d, count=%d, min=%d\n", i, k, j, count, min);


// Print statement for debugging

if (count < min)


min = count;
}

// Return minimum count


return min;
}

// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 3 };
int N = sizeof(arr) / sizeof(arr[0]);

// Function call
printf("Minimum number of multiplications is %d\n",
MatrixChainOrder(arr, 1, N - 1));
getchar();
return 0;
}

7.

#include <stdio.h>
#include <limits.h>

#define V 4 // Number of vertices in the graph

// Function to find minimum of two numbers


int min(int a, int b) {
return (a < b) ? a : b;
}

// Function to find the shortest Hamiltonian cycle


int tsp(int graph[][V], int mask, int pos, int n, int dp[][V]) {
// If all vertices have been visited, return the cost from current vertex
to the starting vertex
if (mask == (1 << n) - 1) {
printf("All vertices visited, returning to starting vertex %d\n", 0);
return graph[pos][0];
}
// If the current subproblem has already been computed, return its result
from the dp table
if (dp[mask][pos] != -1) {
printf("Subproblem tsp(mask=%d, pos=%d) already computed, returning
stored value\n", mask, pos);
return dp[mask][pos];
}

// Initialize minimum cost to infinity


int ans = INT_MAX;

// Try all unvisited cities as the next destination


for (int city = 0; city < n; city++) {
// If the city is not visited yet
if ((mask & (1 << city)) == 0) {
printf("Considering city %d as the next destination\n", city);
// Calculate the cost of going to the next city and returning back
int newAns = graph[pos][city] + tsp(graph, mask | (1 << city),
city, n, dp);

// Update the minimum cost


ans = min(ans, newAns);
printf("NewAns for city %d: %d\n", city, newAns); // Print newAns
for each city
printf("Current min cost: %d\n", ans); // Print current minimum
cost
}
}

// Save the result of the current subproblem in the dp table


return dp[mask][pos] = ans;
}

// Driver code
int main() {
// Example graph represented as an adjacency matrix
int graph[V][V] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};

// Initialize the dp table with -1


int dp[1 << V][V];
for (int i = 0; i < (1 << V); i++) {
for (int j = 0; j < V; j++) {
dp[i][j] = -1;
}
}

// Start from the first vertex (0th vertex) and mask of visited vertices
is 1
int startingVertex = 0;
int mask = 1 << startingVertex;

// Call the TSP function to find the shortest Hamiltonian cycle


printf("Starting TSP from vertex %d\n", startingVertex); // Print starting
vertex
int minCost = tsp(graph, mask, startingVertex, V, dp);

// Output the minimum cost


printf("Minimum cost of the Hamiltonian cycle: %d\n", minCost);

return 0;
}

Backtracking:

#include <stdio.h>
#include <stdlib.h>

// Structure to represent a job


struct Job {
int id; // Job ID
int deadline; // Deadline of the job
int profit; // Profit of the job
};

// Function to sort jobs based on their profit using bubble sort


void bubbleSort(struct Job arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].profit < arr[j + 1].profit) {
// Swap arr[j] and arr[j+1]
struct Job temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to find the maximum profit using Branch and Bound
int jobScheduling(struct Job arr[], int n, int slot[], int currentProfit, int
index) {
// Base case: if all jobs are processed or we reached the end of the slot
array
if (index == n || slot[arr[index].deadline - 1]) {
return currentProfit;
}

// Explore two branches: one where we include the job and one where we
skip the job
// Branch where we include the job
int withProfit = 0;
if (!slot[arr[index].deadline - 1]) {
// Mark the slot as occupied
slot[arr[index].deadline - 1] = 1;
// Recursively explore next job with increased profit
withProfit = jobScheduling(arr, n, slot, currentProfit +
arr[index].profit, index + 1);
// Unmark the slot after backtracking
slot[arr[index].deadline - 1] = 0;
}

// Branch where we skip the job


int withoutProfit = jobScheduling(arr, n, slot, currentProfit, index + 1);

// Return the maximum profit from both branches


return (withProfit > withoutProfit) ? withProfit : withoutProfit;
}

int main() {
// Example jobs
struct Job arr[] = {{1, 2, 100}, {2, 1, 19}, {3, 2, 27}, {4, 1, 25}, {5,
3, 15}};
int n = sizeof(arr) / sizeof(arr[0]);

// Sort jobs based on their profit using bubble sort


bubbleSort(arr, n);

// Array to keep track of whether a slot is occupied


int slot[5] = {0};

// Calculate the maximum profit


int maxProfit = jobScheduling(arr, n, slot, 0, 0);

printf("Maximum Profit: %d\n", maxProfit);

return 0;
}

2.

#include <stdio.h>
#include <stdbool.h>
#define N 4
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%d ", board[i][j]);
}
printf("\n");
}
}
bool isSafe(int board[N][N], int row, int col)
{
for (int i = 0; i < col; i++)
{
if (board[row][i])
{
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j])
{
return false;
}
}
for (int i = row, j = col; j >= 0 && i < N; i++, j--)
{
if (board[i][j])
{
return false;
}
}
return true;
}
bool solveNQueensUtil(int board[N][N], int col)
{
if (col >= N)
{
return true;
}
for (int i = 0; i < N; i++)
{
if (isSafe(board, i, col))
{
board[i][col] = 1;
if (solveNQueensUtil(board, col + 1))
{
return true;
}
board[i][col] = 0;
}
}
return false;
}
void solveNQueens()
{
int board[N][N] = {0};
if (solveNQueensUtil(board, 0) == false)
{
printf("Solution does not exist");
return;
}
printSolution(board);
}
int main()
{
solveNQueens();
return 0;
}

3.

#include <stdio.h>

#define MAX 100

int totalNodes; // Number of nodes in the search tree

// Function to find all subsets of set[] that sum to a given value


void subsetSum(int set[], int n, int sum, int currentSum, int idx, int
solution[], int depth) {
// If the current subset's sum is equal to the given sum, print the subset
if (sum == currentSum) {
printf("Subset found: ");
for (int i = 0; i < idx; i++) {
printf("%d ", solution[i]);
}
printf("\n");
return;
}

// If we have reached the end of the array or sum exceeds the target sum,
return
if (idx >= n || currentSum > sum) {
return;
}

// Include the current element in the subset and recur with the next index
solution[idx] = set[idx];
subsetSum(set, n, sum, currentSum + set[idx], idx + 1, solution, depth +
1);

// Exclude the current element from the subset and recur with the next
index
subsetSum(set, n, sum, currentSum, idx + 1, solution, depth);
}

// Wrapper function for subsetSum


void findSubsets(int set[], int n, int sum) {
int solution[MAX];
subsetSum(set, n, sum, 0, 0, solution, 0);
}

int main() {
int set[] = {10, 7, 5, 18, 12, 20, 15};
int n = sizeof(set) / sizeof(set[0]);
int sum = 35;

printf("Given set: ");


for (int i = 0; i < n; i++) {
printf("%d ", set[i]);
}
printf("\nTarget sum: %d\n", sum);

findSubsets(set, n, sum);

return 0;
}

STRING ALGORITHMS:

RABIN KARP:
#include <stdio.h>

#include <string.h>

// d is the number of characters in the input alphabet

#define d 256

// q is a prime number

#define q 101

// Function to search for the pattern pat in the string txt using Rabin-Karp algorithm

void search(char *pat, char *txt) {

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 one 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 (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]

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);

int main() {

char txt[] = "AABAACAADAABAABA";

char pat[] = "AABA";

search(pat, txt);

return 0;

}
Knuth moris patt:

#include <stdio.h>

#include <string.h>

// Function to compute temporary array to maintain size of suffix which is same as prefix

void computeLPSArray(char *pat, int M, int *lps) {

int len = 0; // Length of the previous longest prefix suffix

lps[0] = 0; // lps[0] is always 0

int i = 1;

// Calculate lps[i] for i = 1 to M-1

while (i < M) {

if (pat[i] == pat[len]) {

len++;

lps[i] = len;

i++;

} else {

if (len != 0) {

// This is tricky. Consider the example AAACAAAA and i = 7

len = lps[len - 1];

// Also, note that we do not increment i here

} else {

lps[i] = 0;

i++;

}
}

// Function to implement Knuth-Morris-Pratt algorithm

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("Pattern found at index %d\n", 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;

int main() {

char txt[] = "ABABDABACDABABCABAB";

char pat[] = "ABABCABAB";

KMPSearch(pat, txt);

return 0;

You might also like