0% found this document useful (0 votes)
23 views20 pages

Daa Lab Cat

The document outlines various programming tasks involving algorithms such as Huffman decoding, sales performance analysis using divide and conquer, Karatsuba multiplication, longest common subsequence detection, matrix chain multiplication, and the N-Queens problem. Each task includes a problem statement, input/output formats, constraints, and sample test cases with corresponding code snippets. The tasks are designed to test and implement different algorithmic concepts in programming.

Uploaded by

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

Daa Lab Cat

The document outlines various programming tasks involving algorithms such as Huffman decoding, sales performance analysis using divide and conquer, Karatsuba multiplication, longest common subsequence detection, matrix chain multiplication, and the N-Queens problem. Each task includes a problem statement, input/output formats, constraints, and sample test cases with corresponding code snippets. The tasks are designed to test and implement different algorithmic concepts in programming.

Uploaded by

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

1.

Problem Statement

Imagine you are in a data science class, and your instructor, Professor Huffman, has tasked you with
writing a program to decode messages encoded using a specific Huffman tree.

The Huffman tree has two types of nodes: internal nodes represented by a "*" character and leaf
nodes containing either "A" or "B". You need to write a program that can take an encoded message
and decode it according to this predefined Huffman tree structure.

Input format :

The input consists of a string of '0's and '1's representing the encoded message, without any space.

Output format :

The output displays the decoded message, which will be a sequence of characters ('A' or 'B').

Refer to the sample output for formatting specifications.

Code constraints :

The test cases will fall under the following constraints:

The encoded message will contain at least one character.

1 <= |encodedMessage| <= 100

Sample test cases :

Input 1 :

11100011100

Output 1 :

BBBAAABBBAA

CODE:

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

struct HuffmanNode {
char data;
HuffmanNode* left;
HuffmanNode* right;

HuffmanNode(char data) {
this->data = data;
left = nullptr;
right = nullptr;
}
};

void decodeHuffman(HuffmanNode* root, const string& encodedMessage) {


HuffmanNode* current = root;

for (size_t i = 0; i < encodedMessage.size(); i++) {


if (encodedMessage[i] == '0') {
current = current->left;
} else if (encodedMessage[i] == '1') {
current = current->right;
}

if (current->left == nullptr && current->right == nullptr) {


cout << current->data;
current = root;
}
}
}

int main() {
string encodedMessage;
cin >> encodedMessage;

HuffmanNode* root = new HuffmanNode('*');


root->left = new HuffmanNode('A');
root->right = new HuffmanNode('B');

decodeHuffman(root, encodedMessage);

return 0;
}
2.

Sarah is analyzing the sales performance of her store over a series of consecutive days. She wants to
identify the best-performing period in terms of maximum total sales.

She also needs to calculate the average daily sales and list the sales figures for that period to
understand the contributing factors. Help her to calculate all these values using the divide and
conquer algorithm.

Example

Input:

-3 1 -1 5 6

Output:

11

5.50

[5, 6]

Explanation:

The array is divided into left [-3, 1, -1] and right [5, 6].

The left half's maximum subarray is [1] with a sum of 1.

The right half's maximum subarray is [5, 6] with a sum of 11.

The crossing subarray spanning both halves is [-1, 5] with a sum of 4.

The right half [5, 6] has the highest sum (11), so the result is Sum = 11, Average = 5.50, Subarray =
[5,6].

Input format :

The first line of input consists of an integer N, representing the size of the array.

The second line consists of N space-separated integers, representing the sales figures for each day.

Output format :

The first line of output prints the maximum sum of the subarray,

The second line of output prints a double representing the average sales rounded to two decimal
places.

The third line of output prints an array representing the elements in the subarray.
Refer to the sample output for formatting specifications.

Code constraints :

The given test cases fall under the following specifications:

1 ≤ N ≤ 20

-100 ≤ Array elements ≤ 100

Sample test cases :

Input 1 :

-3 1 -1 5 6

Output 1 :

11

5.50

[5, 6]

Input 2 :

-2 -1 -3 -4

Output 2 :

-1

-1.00

[-1]

CODE:

#include <bits/stdc++.h>
using namespace std;

int main() {
int tt = 1;
while(tt--) {
int n, k;
cin >> n >> k;
vector<int > arr(n);
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
queue<int > Q;
for (int i = 0; i < k; ++i) {
if(arr[i] % 2 == 0) {
Q.push(i);
}
}
if(Q.size()) {
cout << arr[Q.front()] << " ";
if(Q.front() == 0 ){
Q.pop();
}
}
else {
cout << -1 << " ";
}
for (int i = k; i < n; ++i) {
if(arr[i] % 2 == 0) {
Q.push(i);
}
if(Q.size()) {
cout << arr[Q.front()] << " ";
if(Q.front() == i - k + 1) Q.pop();
}
else {
cout << -1 <<" ";
}
}
cout << endl;
}
return 0;
}

3.

John needs to multiply several pairs of large numbers in a single program. He wants to use the
Karatsuba algorithm for efficient computation. Help John to complete the task.

Input format :

The first line contains a single integer n, representing the number of pairs.

The next n lines contain a pair of two integers x and y representing the multiplicands separated by
spaces

Output format :

The output displays n lines containing the product of x and y, rounded to three decimal places

Code constraints :

1 ≤ n ≤ 100

1 ≤ x, y ≤ 1018

Sample test cases :

Input 1 :
2

12345 67890

98765 43210

Output 1 :

Product of pair 1: 838102050

Product of pair 2: 4267635650

Input 2 :

123456789 987654321

11111 22222

555555555 333333333

Output 2 :

Product of pair 1: 121932631112635269

Product of pair 2: 246908642

Product of pair 3: 185185184814814815

CODE:

#include <stdio.h>
#include <math.h>

int get_size(long);

long karatsuba(long X, long Y) {


if (X < 10 && Y < 10)
return X * Y;

int size = fmax(get_size(X), get_size(Y));


if (size < 10)
return X * Y;

size = (size / 2) + (size % 2);


long multiplier = pow(10, size);

long b = X / multiplier;
long a = X - (b * multiplier);
long d = Y / multiplier;
long c = Y - (d * multiplier);

long u = karatsuba(a, c);


long z = karatsuba(a + b, c + d);
long v = karatsuba(b, d);
return u + ((z - u - v) * multiplier) + (v * (long)(pow(10, 2 * size)));
}

int get_size(long value) {


int count = 0;
while (value > 0) {
count++;
value /= 10;
}
return count;
}

int main() {
int n;

scanf("%d", &n);

long x, y;
for (int i = 0; i < n; i++) {
scanf("%ld %ld", &x, &y);
printf("Product of pair %d: %ld\n", i + 1, karatsuba(x, y));
}

return 0;
}

4.
Emma, a software developer, is working on a plagiarism detection tool for an educational platform.
The platform receives large text documents from students, and Emma needs to compare the
submitted papers to check for similarities. She decides to implement an algorithm that finds the
Longest Common Subsequence (LCS) between two documents, which are represented as strings. To
achieve this, Emma needs a program that can efficiently calculate the length of the LCS for these
large document strings.

Help Emma by writing a program that calculates the length of the LCS between two given document
strings
Input format :
The first line of input contains a string representing the first document.
The second line of input contains a string representing the second document.
Output format :
The first line of output displays all the unique combinations of the longest common subsequence.
The last line of output displays the length(counted based on the number of characters in the
subsequence including the spaces between words) of the longest common subsequence.

Refer to the sample output for the formatting specifications.


Code constraints :
In the given scenario, the test cases fall under the following constraints:
0 ≤ len(str1), len(str2) ≤ 1000
Sample test cases :
Input 1 :
This is test
is test This
Output 1 :
is test
The length of the Longest Common Subsequence is: 7
Input 2 :
The brown quick fox
The quick brown fox
Output 2 :
The brown fox
The quick fox
The length of the Longest Common Subsequence is: 13

CODE:

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

#define MAX 1001

char lcs[MAX]={0};
char *results[MAX]={0};
int count=0;
void backtrack(int i,int j,int idx,int dp[MAX][MAX],char*str1,char*str2){
if(i==0 || j==0){
lcs[idx]='\0';\
for(int k=0;k<count;k++){
if(strcmp(results[k],lcs)==0){
return;
}
}
results[count++]=strdup(lcs);
return;
}
if(str1[i-1]==str2[j-1]){
lcs[idx]=str1[i-1];
backtrack(i-1,j-1,idx-1,dp,str1,str2);
}

else {
if(dp[i-1][j] == dp[i][j-1]){
backtrack(i-1,j,idx,dp,str1,str2);
backtrack(i,j-1,idx,dp,str1,str2);

}
else if (dp[i-1][j]>dp[i][j-1]){
backtrack(i-1,j,idx,dp,str1,str2);
}
else{
backtrack(i,j-1,idx,dp,str1,str2);
}
}
}

void find(char*str1,char*str2,int m,int n){


int dp[MAX][MAX]={0};

for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(str1[i-1] == str2[j-1]){
dp[i][j]=dp[i-1][j-1]+1;

}
else{
dp[i][j]=(dp[i-1][j]>dp[i][j-1])?dp[i-1][j]:dp[i][j-1];
}

}
}
int lcs_len=dp[m][n];
backtrack(m,n,lcs_len-1,dp,str1,str2);
for(int i=0;i<count;i++){

printf("%s\n",results[i]);
free(results[i]);
}

printf("The length of the Longest Common Subsequence is:%d\n",lcs_len);

}
int main(){
char str1[MAX],str2[MAX];
fgets(str1,MAX,stdin);
fgets(str2,MAX,stdin);
str1[strcspn(str1,"\n")]='\0';
str2[strcspn(str2,"\n")]='\0';
find(str1,str2,strlen(str1),strlen(str2));
return 0;
}

5.
Emily is managing a factory that operates on sequential machines represented by matrices. Each
machine outputs data in a format that matches the input dimensions of the next machine. To reduce
processing time, Emily wants to determine the minimum number of scalar operations required to
process the sequence.

Additional Constraint: It should display the optimal order of the Multiplication

Help Emily to complete the task


Input format :
The first line contains a single integer n, representing the number of dimensions in the array
The second line contains n integers, representing the dimensions of the matrices.
Output format :
The output prints the minimum scalar multiplications considering the given constraint.
and then it display the optimal order of the Multiplication

Refer to the sample output for formatting specifications.


Code constraints :
3 ≤ n ≤ 100
1 ≤ dimensions of matrices ≤ 500
Sample test cases :
Input 1 :
5
12343
Output 1 :
30
(((M1M2)M3)M4)
Input 2 :
3
10 20 30
Output 2 :
6000
(M1M2)

CODE:

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

void printOptimalParenthesis(int i, int j, int n, int *bracket, char *name) {


if (i == j) {
printf("M%c", (*name)++);
return;
}
printf("(");
printOptimalParenthesis(i, *((bracket + i * n) + j), n, bracket, name);
printOptimalParenthesis(*((bracket + i * n) + j) + 1, j, n, bracket, name);
printf(")");
}

void matrixChainOrder(int d[], int n) {


int m[n][n], bracket[n][n];

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


m[i][i] = 0;

for (int L = 2; L < n; L++) {


for (int i = 1; i < n - L + 1; i++) {
int j = i + L - 1;
m[i][j] = INT_MAX;

for (int k = i; k < j; k++) {


int q = m[i][k] + m[k+1][j] + d[i-1] * d[k] * d[j];
if (q < m[i][j]) {
m[i][j] = q;
bracket[i][j] = k;
}
}
}
}

printf("%d ", m[1][n-1]);


char name = '1';
printOptimalParenthesis(1, n-1, n, (int*)bracket, &name);
printf("\n");
}

int main() {
int n;
scanf("%d", &n);
int d[n];

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


scanf("%d", &d[i]);

matrixChainOrder(d, n);

return 0;
}
6.
Daniel has a standard 8x8 chessboard, and he wants to place 8 queens on the board in such a way
that no two queens threaten each other. In chess, a queen can move horizontally, vertically, and
diagonally. Therefore, no two queens should share the same row, column, or diagonal.

Daniel's goal is to find a valid arrangement of the queens on the chessboard where they do not
threaten each other. If such an arrangement exists, he wants to display the positions of the queens
on the board.

Rules:
Each queen should be placed on a different row and column.
No two queens should be on the same row, column, or diagonal.
Input format :
No console input.
Output format :
The output displays the arrangement of the queens on the chessboard as an 8x8 grid, where:
Each cell containing a queen is represented by the number '1'.
Each empty cell is represented by the number '0'.

Refer to the sample output for the formatting specifications.


Sample test cases :
Input 1 :
Output 1 :
10000000
00000010
00001000
00000001
01000000
00010000
00000100
00100000

CODE:

#include <iostream>
#include <vector>

using namespace std;

const int N = 8;

bool isSafe(vector<vector<int> >& board, int row, int col)


{
for (int x = 0; x < col; x++)
if (board[row][x] == 1)
return false;
for (int x = row, y = col; x >= 0 && y >= 0; x--, y--)
if (board[x][y] == 1)
return false;
for (int x = row, y = col; x < N && y >= 0; x++, y--)
if (board[x][y] == 1)
return false;
return true;
}

bool solveNQueens(vector<vector<int> >& board, int col)


{
if (col == N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << board[i][j] << " ";
cout << endl;
}
cout << endl;
return true;
}
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQueens(board, col + 1))
return true;
board[i][col] = 0;
}
}
return false;
}

int main()
{
vector<vector<int> > board(N, vector<int>(N, 0));
solveNQueens(board, 0);
return 0;
}

7.
Given two strings, text1, and text2, return the length of their longest common subsequence. If there
is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters
(can be none) deleted without changing the relative order of the remaining characters. For example,
"ace" is a subsequence of "abcde".

A common subsequence of two strings is a subsequence that is common to both strings.


Input format :
The first line of input consists of a string representing text1.
The second line of input consists of a string representing text2.
Output format :
The output prints a single integer which is the length of the Longest Common Subsequence of the
two strings.

Refer to the sample output for the formatting specifications.


Code constraints :
In the given scenario, the test cases will fall under the following constraints:
1 ≤ text1.length, text2.length ≤ 100
text1 and text2 consist of only lowercase English characters.
Sample test cases :
Input 1 :
abcde
ace
Output 1 :
3
Input 2 :
abc
abc
Output 2 :
3
Input 3 :
abc
def
Output 3 :
0

CODE:

#include<stdio.h>
#include<string.h>
int longestCommonSubsequence(char*text1,char*text2) {
int len1=strlen(text1);

int len2=strlen(text2);
int dp[len1+1][len2+1];
for(int i=0;i<=len1;i++){
for(int j=0;j<=len2;j++){
if(i==0 || j==0){
dp[i][j]=0;
} else if(text1[i-1]==text2[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
}else{
dp[i][j]=(dp[i-1][j]>dp[i][j-1])?dp[i-1][j]:dp[i][j-1];
}
}
}
return dp[len1][len2];
}
int main(){
char text1[101],text2[101];
scanf("%s",text1);
scanf("%s",text2);
printf("%d\n",longestCommonSubsequence(text1,text2));
return 0;
}
8.
Problem Statement

You are given a standard 4x4 chessboard, and your task is to place 4 rooks on the board in such a way
that no two rooks threaten each other. In chess, a rook can move horizontally and vertically.
Therefore, no two rooks should share the same row or column.

Your goal is to find a valid arrangement of the rooks on the chessboard where they do not threaten
each other. If such an arrangement exists, display the positions of the rooks on the board. If no valid
arrangement exists, indicate that no solution can be found.

Rules:
Each rook should be placed on a different row and column.
No two rooks should be on the same row or column.
Input format :
No console input.
Output format :
Display the arrangement of the rooks on the chessboard as a 4x4 grid, where:
Each cell containing a rook is represented by the number '1'.
Each empty cell is represented by the number '0'.

Refer to the sample output for the formatting specifications.


Sample test cases :
Input 1 :
Output 1 :
1000
0100
0010
0001

CODE:
#include <iostream>
#include <vector>

using namespace std;


const int N = 4;
bool isValid(const vector<vector<int>>& board, int row, int col) {
for (int i = 0; i < N; ++i) {
if (board[row][i] == 1 || board[i][col] == 1) {
return false;
}
}
return true;
}
bool solve4RooksUtil(vector<vector<int>>& board, int col) {
if (col == N) {
return true;
}
for (int i = 0; i < N; ++i) {
if (isValid(board, i, col)) {
board[i][col] = 1;
if (solve4RooksUtil(board, col + 1)) {
return true;
}
board[i][col] = 0;
}
}
return false;
}
void solve4Rooks() {
vector<vector<int>> board(N, vector<int>(N, 0));
if (solve4RooksUtil(board, 0)) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cout << board[i][j] << " ";
}
cout << endl;
}
} else {
cout << "No solution exists." << endl;
}
}
int main() {
solve4Rooks();
return 0;
}
9.
KMP Algorithm for Pattern Searching

Raj is working on a project that involves searching for a specific pattern in a given text. He has heard
about the Knuth-Morris-Pratt (KMP) algorithm, which is efficient for string matching, and he decided
to implement it.

Write a program that takes a text and a pattern as input, and then applies the KMP algorithm to find
and print all pattern occurrences within the text.
Input format :
The first line of input consists of the text string txt, representing the main string where the pattern
needs to be searched.
The second line of input consists of the pattern string pat, that Raj wants to find within the text as a
string.
Output format :
If the pattern is found, print "Found pattern at index i", where i is the index of the first occurrence of
the pattern in the text.
If the pattern is not found, print "Pattern not found".

Refer to the sample output for the formatting specifications.


Code constraints :
In this scenario, the given test cases will fall under the following constraints:
1 ≤ |txt| ≤ 50
1 ≤ |pat| ≤ 25
The input strings are case-sensitive.
The index starts from 0.
Sample test cases :
Input 1 :
ABABDABACDABABCABAB
ABABCABAB
Output 1 :
Found pattern at index 10
Input 2 :
ababcababcabcabc
abc
Output 2 :
Found pattern at index 2
Found pattern at index 7
Found pattern at index 10
Found pattern at index 13
Input 3 :
ABC
XY
Output 3 :
Pattern not found
Input 4 :
AABAACAADAABAABA
AABA
Output 4 :
Found pattern at index 0
Found pattern at index 9
Found pattern at index 12

CODE:

// You are using GCC


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

#define MAX_TEXT 50
#define MAX_PATTERN 25

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


int length = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}

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


int N = strlen(txt);
int M = strlen(pat);
int lps[MAX_PATTERN];
computeLPSArray(pat, M, lps);
int i = 0, j = 0, found = 0;
while (i < N) {
if (pat[j] == txt[i]) {
i++;
j++;
}
if (j == M) {
printf("Found pattern at index %d\n", i - j);
found = 1;
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (!found) {
printf("Pattern not found\n");
}
}

int main() {
char txt[MAX_TEXT + 1];
char pat[MAX_PATTERN + 1];
scanf("%50s", txt);
scanf("%25s", pat);
KMPSearch(txt, pat);
return 0;
}
10.
Anil is working on a project that involves counting occurrences of a specific pattern within a given
text. He needs a program that efficiently finds and counts all occurrences of a pattern within a given
text using the Knuth-Morris-Pratt (KMP) algorithm.

Your task is to help Anil by developing a program that takes a text and a pattern as input and counts
the number of times the pattern appears in the text using the KMP algorithm.
Input format :
The first line contains a string txt, representing the text in which Anil wants to search for the pattern.
The second line contains a string pat, representing the pattern Anil wants to search for in the text.
Output format :
The output displays a single integer, representing the count of occurrences of the pattern pat in the
text txt.
If the pattern is not found, nothing will be printed.

Refer to the sample output for the formatting specifications.


Code constraints :
1 <= |txt| <= 50
1 <= |pat| <= 25
The input strings should be case-sensitive.
Sample test cases :
Input 1 :
AABAACAADAABAABA
AABA
Output 1 :
3
Input 2 :
AAABVCAAABVCAAABCV
AAABVC
Output 2 :
2
Input 3 :
AAAAAAAA
AA
Output 3 : 7
CODE:

// You are using GCC


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

#define MAX_TEXT 50
#define MAX_PATTERN 25

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


int length = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}

int KMPSearch(char *txt, char *pat) {


int N = strlen(txt);
int M = strlen(pat);
int lps[MAX_PATTERN];
computeLPSArray(pat, M, lps);
int i = 0, j = 0, count = 0;
while (i < N) {
if (pat[j] == txt[i]) {
i++;
j++;
}
if (j == M) {
count++;
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return count;
}

int main() {
char txt[MAX_TEXT + 1];
char pat[MAX_PATTERN + 1];
scanf("%50s", txt);
scanf("%25s", pat);
int result = KMPSearch(txt, pat);
if (result > 0) {
printf("%d\n", result);
}
return 0;
}

You might also like