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

Ilovepdf Merged

The document contains a programming assignment related to Huffman coding, which is a lossless data compression algorithm. It provides details about a student named Rithwik Sundar, including their contact information, and outlines the requirements for implementing a Huffman Tree to encode messages based on character frequencies. The document includes code snippets and functions necessary for building the Huffman Tree and encoding messages.

Uploaded by

sundarrithwik
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)
6 views

Ilovepdf Merged

The document contains a programming assignment related to Huffman coding, which is a lossless data compression algorithm. It provides details about a student named Rithwik Sundar, including their contact information, and outlines the requirements for implementing a Huffman Tree to encode messages based on character frequencies. The document includes code snippets and functions necessary for building the Huffman Tree and encoding messages.

Uploaded by

sundarrithwik
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/ 49

VIT - Vellore

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 1_Huffman_COD_Easy

Attempt : 1
Total Mark : 20
Marks Obtained : 18

Section 1 : Coding
72

72

72

2
1. Problem Statement:

67
06

06

06

E0
E

E
BC

BC

BC

Emily, a data compression engineer, works for a company that deals with BC
23

23

23

23
large volumes of text-based data. Her team is developing an efficient
method to compress text data for faster transmission and reduced storage
costs. Emily decided to use Huffman coding, a popular lossless data
compression algorithm, to encode messages based on the frequency of
characters.

She is tasked with implementing a system that takes in a list of characters


and their frequencies, builds a Huffman Tree, generates Huffman codes for
each character, and then encodes a given message using those codes.
2

2
67

67

67

67

Help Emily write a program that can:


E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
Build a Huffman Tree from the given characters and their
2

72

72
67

67
06

06
frequencies.Generate Huffman codes for the characters.Encode a
E0

E0
E

E
message using the generated Huffman codes.
BC

BC

BC

BC
23

23

23

23
Answer
// You are using GCC
/*#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct HuffmanNode {
char data;
int frequency;
struct HuffmanNode* left;
2

2
67

67

67

67
struct HuffmanNode* right;
E0

E0

E0

E0
BC

BC

BC

BC
};
23

23

23

23
struct MinHeap {
int size;
int capacity;
struct HuffmanNode** array;
};

void buildHuffmanCodes(struct HuffmanNode* root, char* currentCode, char**


huffmanCodes);

struct HuffmanNode* createNode(char data, int frequency)


72

72

72

2
67
06

06

06

E0
E

E
BC

BC

BC

BC
struct HuffmanNode* newNode = (struct HuffmanNode*)malloc(sizeof(struct
23

23

23

23
HuffmanNode));
newNode->data = data;
newNode->frequency = frequency;
newNode->left = newNode->right = NULL;
return newNode;
}
}

struct HuffmanNode* createMinHeapNode(char data, int frequency) {


return createNode(data, frequency);
}
2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC

struct MinHeap* createMinHeap(int capacity) {


23

23

23

23
struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
2

72

72
67

67
minHeap->size = 0;

06

06
E0

E0
E

E
minHeap->capacity = capacity;
BC

BC

BC

BC
minHeap->array = (struct HuffmanNode**)malloc(capacity * sizeof(struct
23

23

23

23
HuffmanNode*));
return minHeap;
}

void swapMinHeapNodes(struct HuffmanNode** a, struct HuffmanNode** b) {


struct HuffmanNode* t = *a;
*a = *b;
*b = t;
}
2

2
67

67

67

67
void minHeapify(struct MinHeap* minHeap, int idx) {
E0

E0

E0

E0
int smallest = idx;
BC

BC

BC

BC
int left = 2 * idx + 1;
23

23

23

23
int right = 2 * idx + 2;

if (left < minHeap->size && minHeap->array[left]->frequency < minHeap-


>array[smallest]->frequency)
smallest = left;

if (right < minHeap->size && minHeap->array[right]->frequency < minHeap-


>array[smallest]->frequency)
smallest = right;
72

72

72

2
67
if (smallest != idx) {
06

06

06

E0
E

swapMinHeapNodes(&minHeap->array[smallest], &minHeap->array[idx]);
BC

BC

BC

minHeapify(minHeap, smallest); BC
23

23

23

23
}
}

int isSizeOne(struct MinHeap* minHeap) {


return minHeap->size == 1;
}

struct HuffmanNode* extractMin(struct MinHeap* minHeap) {


struct HuffmanNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
2

2
67

67

67

67

--minHeap->size;
E0

E0

E0

E0

minHeapify(minHeap, 0);
BC

BC

BC

BC
23

23

23

23
return temp;
2

72

72
67

67
}

06

06
E0

E0
E

E
BC

BC

BC

BC
void insertMinHeap(struct MinHeap* minHeap, struct HuffmanNode* node) {
23

23

23

23
++minHeap->size;
int i = minHeap->size - 1;
while (i && node->frequency < minHeap->array[(i - 1) / 2]->frequency) {
minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
minHeap->array[i] = node;
}

struct HuffmanNode* buildHuffmanTree(char data[], int frequency[], int size)


2

2
67

67

67

67
{
E0

E0

E0

E0
BC

BC

BC

BC
}
23

23

23

23
void printHuffmanCodes(struct HuffmanNode* root, char* currentCode, char**
huffmanCodes) {
if (root->left) {
strcat(currentCode, "0");
printHuffmanCodes(root->left, currentCode, huffmanCodes);
currentCode[strlen(currentCode) - 1] = '\0';
}
if (root->right) {
strcat(currentCode, "1");
72

72

72

2
67
printHuffmanCodes(root->right, currentCode, huffmanCodes);
06

06

06

E0
E

currentCode[strlen(currentCode) - 1] = '\0';
BC

BC

BC

} BC
23

23

23

23
if (!root->left && !root->right) {
printf("%c: %s\n", root->data, currentCode);
huffmanCodes[root->data] = strdup(currentCode);
}
}

void encodeMessage(char message[], char encodedMessage[], char*


huffmanCodes[])
{
//Type your code
2

2
67

67

67

67

}
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
int main() {
2

72

72
67

67
int numCharacters;

06

06
E0

E0
E

E
BC

BC

BC

BC
scanf("%d", &numCharacters);
23

23

23

23
char data[numCharacters];
int frequency[numCharacters];

for (int i = 0; i < numCharacters; ++i) {


scanf(" %c", &data[i]);
scanf("%d", &frequency[i]);
}

struct HuffmanNode* root = buildHuffmanTree(data, frequency,


2

2
67

67

67

67
numCharacters);
E0

E0

E0

E0
BC

BC

BC

BC
char* huffmanCodes[256] = {0};
23

23

23

23
char currentCode[256] = {0};
printHuffmanCodes(root, currentCode, huffmanCodes);

char message[256];

scanf(" %[^\n]", message);

char encodedMessage[256] = {0};


encodeMessage(message, encodedMessage, huffmanCodes);
printf("%s\n", encodedMessage);
72

72

72

2
67
06

06

06

E0
E

return 0;
BC

BC

BC

}*/ BC
23

23

23

23

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

#define MAX_TREE_NODES 256

// Node structure for the Huffman Tree


typedef struct Node {
char character;
2

2
67

67

67

67

int frequency;
E0

E0

E0

E0

struct Node *left;


BC

BC

BC

BC
23

23

23

23
struct Node *right;
2

72

72
67

67
} Node;

06

06
E0

E0
E

E
BC

BC

BC

BC
// Min-heap structure
23

23

23

23
typedef struct MinHeap {
int size;
Node* array[MAX_TREE_NODES];
} MinHeap;

// Function to create a new node


Node* createNode(char character, int frequency) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->character = character;
newNode->frequency = frequency;
2

2
67

67

67

67
newNode->left = newNode->right = NULL;
E0

E0

E0

E0
return newNode;
BC

BC

BC

BC
}
23

23

23

23
// Function to create a min-heap
MinHeap* createMinHeap() {
MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap));
minHeap->size = 0;
return minHeap;
}

// Function to swap two nodes


void swap(Node** a, Node** b) {
72

72

72

2
67
Node* temp = *a;
06

06

06

E0
E

*a = *b;
BC

BC

BC

*b = temp; BC
23

23

23

23
}

// Function to heapify the min-heap


void minHeapify(MinHeap* minHeap, int idx) {
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;

if (left < minHeap->size && minHeap->array[left]->frequency < minHeap-


>array[smallest]->frequency)
2

2
67

67

67

67

smallest = left;
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
if (right < minHeap->size && minHeap->array[right]->frequency < minHeap-
2

72

72
67

67
>array[smallest]->frequency)

06

06
E0

E0
E

E
smallest = right;
BC

BC

BC

BC
23

23

23

23
if (smallest != idx) {
swap(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}

// Function to insert a node into the min-heap


void insertMinHeap(MinHeap* minHeap, Node* node) {
minHeap->array[minHeap->size] = node;
int current = minHeap->size++;
2

2
67

67

67

67
E0

E0

E0

E0
while (current && minHeap->array[current]->frequency < minHeap-
BC

BC

BC

BC
>array[(current - 1) / 2]->frequency) {
23

23

23

23
swap(&minHeap->array[current], &minHeap->array[(current - 1) / 2]);
current = (current - 1) / 2;
}
}

// Function to extract the minimum node from the heap


Node* extractMin(MinHeap* minHeap) {
Node* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
72

72

72

2
67
minHeapify(minHeap, 0);
06

06

06

E0
E

return temp;
BC

BC

BC

} BC
23

23

23

23

// Function to build the Huffman Tree


Node* buildHuffmanTree(char characters[], int frequencies[], int size) {
MinHeap* minHeap = createMinHeap();

for (int i = 0; i < size; ++i) {


insertMinHeap(minHeap, createNode(characters[i], frequencies[i]));
}

while (minHeap->size > 1) {


2

2
67

67

67

67

Node* left = extractMin(minHeap);


E0

E0

E0

E0

Node* right = extractMin(minHeap);


BC

BC

BC

BC
23

23

23

23
2

72

72
67

67
Node* merged = createNode('\0', left->frequency + right->frequency);

06

06
E0

E0
E

E
merged->left = left;
BC

BC

BC

BC
merged->right = right;
23

23

23

23
insertMinHeap(minHeap, merged);
}

return extractMin(minHeap); // Return the root of the tree


}

// Function to generate Huffman codes recursively


void generateHuffmanCodes(Node* root, char* code, int depth, char codes[]
[MAX_TREE_NODES]) {
2

2
67

67

67

67
if (root == NULL)
E0

E0

E0

E0
return;
BC

BC

BC

BC
23

23

23

23
if (root->left == NULL && root->right == NULL) { // Leaf node
code[depth] = '\0'; // Null-terminate the string
strcpy(codes[(unsigned char)root->character], code); // Store code for
character
return;
}

code[depth] = '0';
generateHuffmanCodes(root->left, code, depth + 1, codes);
72

72

72

2
67
code[depth] = '1';
06

06

06

E0
E

generateHuffmanCodes(root->right, code, depth + 1, codes);


BC

BC

BC

} BC
23

23

23

23

// Function to encode the message using generated Huffman codes


void encodeMessage(const char* message, char codes[][MAX_TREE_NODES],
char* encodedMessage) {
encodedMessage[0] = '\0'; // Initialize encoded message as empty

for (int i = 0; message[i]; ++i) {


strcat(encodedMessage, codes[(unsigned char)message[i]]);
}
}
2

2
67

67

67

67
E0

E0

E0

E0

int main() {
BC

BC

BC

BC
23

23

23

23
int n;
2

72

72
67

67
06

06
E0

E0
E

E
scanf("%d", &n); // Number of distinct characters
BC

BC

BC

BC
23

23

23

23
char characters[MAX_TREE_NODES];
int frequencies[MAX_TREE_NODES];

// Read character frequencies


for (int i = 0; i < n; ++i) {
scanf(" %c %d", &characters[i], &frequencies[i]);
}

char message[MAX_TREE_NODES];
2

2
67

67

67

67
scanf("%s", message); // The message to encode
E0

E0

E0

E0
BC

BC

BC

BC
// Build Huffman Tree and generate codes
23

23

23

23
Node* root = buildHuffmanTree(characters, frequencies, n);

char codes[MAX_TREE_NODES][MAX_TREE_NODES]; // Store Huffman codes


char code[MAX_TREE_NODES]; // Temporary storage for generating codes

generateHuffmanCodes(root, code, 0, codes);

// Prepare a vector to sort by Huffman code for output


typedef struct {
char character;
72

72

72

2
67
char huffmanCode[MAX_TREE_NODES];
06

06

06

E0
E

} CodePair;
BC

BC

BC

BC
23

23

23

23
CodePair sortedCodes[MAX_TREE_NODES];
int count = 0;

for (int i = 0; i < MAX_TREE_NODES; ++i) {


if (codes[i][0] != '\0') { // Only include characters with codes
sortedCodes[count].character = i;
strcpy(sortedCodes[count].huffmanCode, codes[i]);
count++;
}
}
2

2
67

67

67

67
E0

E0

E0

E0

// Sort by Huffman code lexicographically


BC

BC

BC

BC
23

23

23

23
qsort(sortedCodes, count, sizeof(CodePair), [](const void *a, const void *b) ->
2

72

72
67

67
int {

06

06
E0

E0
E

E
return strcmp(((CodePair*)a)->huffmanCode, ((CodePair*)b)->huffmanCode);
BC

BC

BC

BC
});
23

23

23

23
// Output the Huffman codes in sorted order of their binary representation
for (int i = 0; i < count; ++i) {
printf("%c: %s\n", sortedCodes[i].character, sortedCodes[i].huffmanCode);
}

// Encode the message and output it


char encodedMessage[MAX_TREE_NODES * MAX_TREE_NODES]; // Large
enough for encoded message
encodeMessage(message, codes, encodedMessage);
2

2
67

67

67

67
E0

E0

E0

E0
printf("%s\n", encodedMessage);
BC

BC

BC

BC
23

23

23

23
return 0;
}

Status : Partially correct Marks : 8/10

2. Problem Statement

Mark is developing a simple data compression system for storing large


text files efficiently. He is using Huffman encoding to represent frequent
72

72

72

2
67
06

06

06

characters with shorter binary codes and infrequent characters with longer

E0
E

E
BC

BC

BC

codes. He needs your help to encode and decode the messages using this
BC
23

23

23

23
system.

Given a set of characters and their respective frequencies, your task is to:
Build a Huffman tree based on the frequencies.Generate the Huffman
codes for each character.Encode a given message using the generated
Huffman codes.Decode the encoded message back to the original format.
Answer
#include <stdio.h>
2

#include <stdlib.h>
67

67

67

67
E0

E0

E0

E0

#include <string.h>
BC

BC

BC

BC
23

23

23

23
#define MAX 100
2

72

72
67

67
06

06
E0

E0
E

E
// Structure to represent a Huffman Tree node
BC

BC

BC

BC
typedef struct Node {
23

23

23

23
char character;
int frequency;
struct Node *left, *right;
} Node;

// Structure for a Min-Heap


typedef struct MinHeap {
int size;
Node* array[MAX];
} MinHeap;
2

2
67

67

67

67
E0

E0

E0

E0
// Function to create a new node
BC

BC

BC

BC
Node* createNode(char character, int frequency) {
23

23

23

23
Node* node = (Node*)malloc(sizeof(Node));
node->character = character;
node->frequency = frequency;
node->left = node->right = NULL;
return node;
}

// Function to create a min-heap


MinHeap* createMinHeap() {
MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap));
72

72

72

2
67
minHeap->size = 0;
06

06

06

E0
E

return minHeap;
BC

BC

BC

} BC
23

23

23

23

// Function to swap two nodes


void swapNodes(Node** a, Node** b) {
Node* temp = *a;
*a = *b;
*b = temp;
}

// Heapify function
void heapify(MinHeap* minHeap, int idx) {
2

2
67

67

67

67

int smallest = idx;


E0

E0

E0

E0

int left = 2 * idx + 1;


BC

BC

BC

BC
23

23

23

23
int right = 2 * idx + 2;
2

72

72
67

67
06

06
E0

E0
E

E
if (left < minHeap->size && minHeap->array[left]->frequency < minHeap-
BC

BC

BC

BC
>array[smallest]->frequency)
23

23

23

23
smallest = left;

if (right < minHeap->size && minHeap->array[right]->frequency < minHeap-


>array[smallest]->frequency)
smallest = right;

if (smallest != idx) {
swapNodes(&minHeap->array[smallest], &minHeap->array[idx]);
heapify(minHeap, smallest);
}
2

2
67

67

67

67
}
E0

E0

E0

E0
BC

BC

BC

BC
// Function to insert a node into the heap
23

23

23

23
void insertHeap(MinHeap* minHeap, Node* node) {
minHeap->size++;
int i = minHeap->size - 1;

while (i && node->frequency < minHeap->array[(i - 1) / 2]->frequency) {


minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}

minHeap->array[i] = node;
72

72

72

2
67
}
06

06

06

E0
E

E
BC

BC

BC

// Function to extract the minimum value node from the heap BC


23

23

23

23
Node* extractMin(MinHeap* minHeap) {
Node* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
minHeap->size--;
heapify(minHeap, 0);
return temp;
}

// Function to build the Huffman Tree


Node* buildHuffmanTree(char characters[], int frequencies[], int size) {
2

2
67

67

67

67

MinHeap* minHeap = createMinHeap();


E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
for (int i = 0; i < size; i++)
2

72

72
67

67
insertHeap(minHeap, createNode(characters[i], frequencies[i]));

06

06
E0

E0
E

E
BC

BC

BC

BC
while (minHeap->size > 1) {
23

23

23

23
Node* left = extractMin(minHeap);
Node* right = extractMin(minHeap);

Node* parent = createNode('$', left->frequency + right->frequency);


parent->left = left;
parent->right = right;

insertHeap(minHeap, parent);
}
2

2
67

67

67

67
return extractMin(minHeap);
E0

E0

E0

E0
}
BC

BC

BC

BC
23

23

23

23
// Function to generate Huffman codes
void generateCodes(Node* root, char code[], int top, char huffmanCodes[26]
[MAX]) {
if (root->left) {
code[top] = '0';
generateCodes(root->left, code, top + 1, huffmanCodes);
}

if (root->right) {
code[top] = '1';
72

72

72

2
67
generateCodes(root->right, code, top + 1, huffmanCodes);
06

06

06

E0
E

}
BC

BC

BC

BC
23

23

23

23
if (!root->left && !root->right) {
code[top] = '\0';
strcpy(huffmanCodes[root->character - 'A'], code);
printf("%c: %s\n", root->character, code);
}
}

// Function to encode the message


void encodeMessage(char* message, char huffmanCodes[26][MAX], char*
encodedMessage) {
2

2
67

67

67

67

for (int i = 0; message[i]; i++) {


E0

E0

E0

E0

if (message[i] == ' ') continue;


BC

BC

BC

BC
23

23

23

23
strcat(encodedMessage, huffmanCodes[message[i] - 'A']);
2

72

72
67

67
}

06

06
E0

E0
E

E
}
BC

BC

BC

BC
23

23

23

23
// Function to decode the message
void decodeMessage(Node* root, char* encodedMessage, char*
decodedMessage) {
Node* current = root;
int j = 0;

for (int i = 0; encodedMessage[i]; i++) {


if (encodedMessage[i] == '0')
current = current->left;
else
2

2
67

67

67

67
current = current->right;
E0

E0

E0

E0
BC

BC

BC

BC
if (!current->left && !current->right) {
23

23

23

23
decodedMessage[j++] = current->character;
current = root;
}
}
decodedMessage[j] = '\0';
}

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

72

72

2
67
06

06

06

E0
E

char characters[n];
BC

BC

BC

int frequencies[n]; BC
23

23

23

23

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


getchar(); // To consume newline
scanf("%c %d", &characters[i], &frequencies[i]);
}

char message[MAX];
getchar();
fgets(message, MAX, stdin);
message[strcspn(message, "\n")] = 0; // Remove newline character
2

2
67

67

67

67
E0

E0

E0

E0

Node* root = buildHuffmanTree(characters, frequencies, n);


BC

BC

BC

BC
23

23

23

23
2

72

72
67

67
char huffmanCodes[26][MAX] = {0};

06

06
E0

E0
E

E
char code[MAX];
BC

BC

BC

BC
printf("");
23

23

23

23
generateCodes(root, code, 0, huffmanCodes);

char encodedMessage[MAX] = "";


encodeMessage(message, huffmanCodes, encodedMessage);
printf("%s\n", encodedMessage);

char decodedMessage[MAX];
decodeMessage(root, encodedMessage, decodedMessage);
printf("%s\n", decodedMessage);
2

2
67

67

67

67
return 0;
E0

E0

E0

E0
}
BC

BC

BC

BC
23

23

23

23
Status : Correct Marks : 10/10
72

72

72

2
67
06

06

06

E0
E

E
BC

BC

BC

BC
23

23

23

23
2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
VIT - Vellore
2

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 1_Huffman_COD_Medium

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Coding
72

72

72

2
1. Problem Statement

67
06

06

06

E0
E

E
BC

BC

BC

Alice works in a tech company that transmits large amounts of data over a BC
23

23

23

23
network. Due to the high volume of data, efficient compression techniques
are necessary to minimize bandwidth usage. Alice has learned about
Huffman encoding, a popular lossless compression technique that assigns
variable-length codes to symbols based on their frequencies. The more
frequent a symbol, the shorter the code assigned to it.

Alice's task is to implement the Huffman encoding algorithm to compress


a set of characters. Given a list of characters and their corresponding
frequencies, she wants to generate a binary code for each character using
2

a Huffman tree.
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
Help Alice by writing a program that constructs the Huffman tree from the
2

72

72
67

67
06

06
given symbols and frequencies, and prints the corresponding binary codes
E0

E0
E

E
for each symbol.
BC

BC

BC

BC
23

23

23

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

#define MAX 100

// Structure to represent a Huffman Tree node


typedef struct Node {
2

2
67

67

67

67
char character;
E0

E0

E0

E0
int frequency;
BC

BC

BC

BC
struct Node *left, *right;
23

23

23

23
} Node;

// Structure for a Min-Heap


typedef struct MinHeap {
int size;
Node* array[MAX];
} MinHeap;

// Function to create a new node


Node* createNode(char character, int frequency) {
72

72

72

2
67
Node* node = (Node*)malloc(sizeof(Node));
06

06

06

E0
node->character = character;
E

E
BC

BC

BC

node->frequency = frequency; BC
23

23

23

23
node->left = node->right = NULL;
return node;
}

// Function to create a min-heap


MinHeap* createMinHeap() {
MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap));
minHeap->size = 0;
return minHeap;
}
2

2
67

67

67

67
E0

E0

E0

E0

// Function to swap two nodes


BC

BC

BC

BC
23

23

23

23
void swapNodes(Node** a, Node** b) {
2

72

72
67

67
Node* temp = *a;

06

06
E0

E0
E

E
*a = *b;
BC

BC

BC

BC
*b = temp;
23

23

23

23
}

// Heapify function
void heapify(MinHeap* minHeap, int idx) {
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;

if (left < minHeap->size && minHeap->array[left]->frequency < minHeap-


>array[smallest]->frequency)
2

2
67

67

67

67
smallest = left;
E0

E0

E0

E0
BC

BC

BC

BC
if (right < minHeap->size && minHeap->array[right]->frequency < minHeap-
23

23

23

23
>array[smallest]->frequency)
smallest = right;

if (smallest != idx) {
swapNodes(&minHeap->array[smallest], &minHeap->array[idx]);
heapify(minHeap, smallest);
}
}

// Function to insert a node into the heap


72

72

72

2
67
void insertHeap(MinHeap* minHeap, Node* node) {
06

06

06

E0
E

minHeap->size++;
BC

BC

BC

int i = minHeap->size - 1; BC
23

23

23

23

while (i && node->frequency < minHeap->array[(i - 1) / 2]->frequency) {


minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}

minHeap->array[i] = node;
}

// Function to extract the minimum value node from the heap


2

2
67

67

67

67

Node* extractMin(MinHeap* minHeap) {


E0

E0

E0

E0

Node* temp = minHeap->array[0];


BC

BC

BC

BC
23

23

23

23
minHeap->array[0] = minHeap->array[minHeap->size - 1];
2

72

72
67

67
minHeap->size--;

06

06
E0

E0
E

E
heapify(minHeap, 0);
BC

BC

BC

BC
return temp;
23

23

23

23
}

// Function to build the Huffman Tree


Node* buildHuffmanTree(char characters[], int frequencies[], int size) {
MinHeap* minHeap = createMinHeap();

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


insertHeap(minHeap, createNode(characters[i], frequencies[i]));

while (minHeap->size > 1) {


2

2
67

67

67

67
Node* left = extractMin(minHeap);
E0

E0

E0

E0
Node* right = extractMin(minHeap);
BC

BC

BC

BC
23

23

23

23
Node* parent = createNode('$', left->frequency + right->frequency);
parent->left = left;
parent->right = right;

insertHeap(minHeap, parent);
}

return extractMin(minHeap);
}
72

72

72

2
67
// Function to generate Huffman codes
06

06

06

E0
E

void generateCodes(Node* root, char code[], int top) {


BC

BC

BC

if (root->left) { BC
23

23

23

23
code[top] = '0';
generateCodes(root->left, code, top + 1);
}

if (root->right) {
code[top] = '1';
generateCodes(root->right, code, top + 1);
}

if (!root->left && !root->right) {


2

2
67

67

67

67

code[top] = '\0';
E0

E0

E0

E0

printf("%c: %s\n", root->character, code);


BC

BC

BC

BC
23

23

23

23
}
2

72

72
67

67
}

06

06
E0

E0
E

E
BC

BC

BC

BC
int main() {
23

23

23

23
int n;
scanf("%d", &n);

char characters[n];
int frequencies[n];

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


getchar(); // To consume newline
scanf("%c %d", &characters[i], &frequencies[i]);
}
2

2
67

67

67

67
E0

E0

E0

E0
Node* root = buildHuffmanTree(characters, frequencies, n);
BC

BC

BC

BC
23

23

23

23
char code[MAX];
generateCodes(root, code, 0);

return 0;
}

Status : Correct Marks : 10/10

2. Problem Statement
72

72

72

2
67
06

06

06

E0
E

Imagine you are in a data science class, and your instructor, Professor
BC

BC

BC

BC
23

23

23

23
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.

Answer
2

2
67

67

67

67

#include <stdio.h>
E0

E0

E0

E0
BC

BC

BC

BC

#include <stdlib.h>
23

23

23

23
#include <string.h>
2

72

72
67

67
06

06
E0

E0
E

E
struct Node {
BC

BC

BC

BC
char data;
23

23

23

23
struct Node* left;
struct Node* right;
};

struct Node* createNode(char data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
2

2
67

67

67

67
}
E0

E0

E0

E0
BC

BC

BC

BC
char decode(struct Node* root, char* encodedMessage, int* index) {
23

23

23

23
if (root == NULL) {
return '\0';
}

if (root->data == 'A' || root->data == 'B') {


return root->data;
}

if (encodedMessage[*index] == '0') {
(*index)++;
72

72

72

2
67
return decode(root->left, encodedMessage, index);
06

06

06

E0
E

} else {
BC

BC

BC

(*index)++; BC
23

23

23

23
return decode(root->right, encodedMessage, index);
}
}

int main() {
char encodedMessage[101];
scanf("%s", encodedMessage);

// Construct the Huffman tree (assuming it's predefined)


struct Node* root = createNode('*');
2

2
67

67

67

67

root->left = createNode('A');
E0

E0

E0

E0

root->right = createNode('B');
BC

BC

BC

BC
23

23

23

23
2

72

72
67

67
int index = 0;

06

06
E0

E0
E

E
char decodedMessage[101];
BC

BC

BC

BC
int i = 0;
23

23

23

23
while (index < strlen(encodedMessage)) {
decodedMessage[i++] = decode(root, encodedMessage, &index);
}
decodedMessage[i] = '\0';

printf("%s\n", decodedMessage);

return 0;
}
2

2
67

67

67

67
E0

E0

E0

E0
Status : Correct Marks : 10/10
BC

BC

BC

BC
23

23

23

23
72

72

72

2
67
06

06

06

E0
E

E
BC

BC

BC

BC
23

23

23

23
2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
VIT - Vellore
2

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 1_Huffman_COD_Hard

Attempt : 1
Total Mark : 20
Marks Obtained : 17

Section 1 : Coding
72

72

72

2
1. Problem Statement

67
06

06

06

E0
E

E
BC

BC

BC

In a world of covert operations, you are tasked with creating a program thatBC
23

23

23

23
enables agents to communicate securely with their headquarters using
Huffman coding techniques. Your mission is to develop a program that can
construct a Huffman tree based on character frequencies and use it to
encode and decode messages. Implement the encoding and decoding
processes, allowing agents to communicate covertly and ensure the
program can successfully encode and decode sample messages to
maintain secrecy.

Answer
2

2
67

67

67

67

#include <stdio.h>
E0

E0

E0

E0

#include <stdlib.h>
BC

BC

BC

BC
23

23

23

23
#include <string.h>
2

72

72
67

67
06

06
E0

E0
E

E
#define MAX 100
BC

BC

BC

BC
23

23

23

23
// Structure to represent a Huffman Tree node
typedef struct Node {
char character;
int frequency;
struct Node *left, *right;
} Node;

// Structure for a Min-Heap


typedef struct MinHeap {
int size;
2

2
67

67

67

67
Node* array[MAX];
E0

E0

E0

E0
} MinHeap;
BC

BC

BC

BC
23

23

23

23
// Function to create a new node
Node* createNode(char character, int frequency) {
Node* node = (Node*)malloc(sizeof(Node));
node->character = character;
node->frequency = frequency;
node->left = node->right = NULL;
return node;
}

// Function to create a min-heap


72

72

72

2
67
MinHeap* createMinHeap() {
06

06

06

E0
E

MinHeap* minHeap = (MinHeap*)malloc(sizeof(MinHeap));


BC

BC

BC

minHeap->size = 0; BC
23

23

23

23
return minHeap;
}

// Function to swap two nodes


void swapNodes(Node** a, Node** b) {
Node* temp = *a;
*a = *b;
*b = temp;
}
2

2
67

67

67

67

// Heapify function
E0

E0

E0

E0

void heapify(MinHeap* minHeap, int idx) {


BC

BC

BC

BC
23

23

23

23
int smallest = idx;
2

72

72
67

67
int left = 2 * idx + 1;

06

06
E0

E0
E

E
int right = 2 * idx + 2;
BC

BC

BC

BC
23

23

23

23
if (left < minHeap->size && minHeap->array[left]->frequency < minHeap-
>array[smallest]->frequency)
smallest = left;

if (right < minHeap->size && minHeap->array[right]->frequency < minHeap-


>array[smallest]->frequency)
smallest = right;

if (smallest != idx) {
swapNodes(&minHeap->array[smallest], &minHeap->array[idx]);
2

2
67

67

67

67
heapify(minHeap, smallest);
E0

E0

E0

E0
}
BC

BC

BC

BC
}
23

23

23

23
// Function to insert a node into the heap
void insertHeap(MinHeap* minHeap, Node* node) {
minHeap->size++;
int i = minHeap->size - 1;

while (i && node->frequency < minHeap->array[(i - 1) / 2]->frequency) {


minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
72

72

72

2
67
06

06

06

E0
E

minHeap->array[i] = node;
BC

BC

BC

} BC
23

23

23

23

// Function to extract the minimum value node from the heap


Node* extractMin(MinHeap* minHeap) {
Node* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
minHeap->size--;
heapify(minHeap, 0);
return temp;
}
2

2
67

67

67

67

// Function to build the Huffman Tree


E0

E0

E0

E0

Node* buildHuffmanTree(char characters[], int frequencies[], int size) {


BC

BC

BC

BC
23

23

23

23
MinHeap* minHeap = createMinHeap();
2

72

72
67

67
06

06
E0

E0
E

E
for (int i = 0; i < size; i++)
BC

BC

BC

BC
insertHeap(minHeap, createNode(characters[i], frequencies[i]));
23

23

23

23
while (minHeap->size > 1) {
Node* left = extractMin(minHeap);
Node* right = extractMin(minHeap);

Node* parent = createNode('$', left->frequency + right->frequency);


parent->left = left;
parent->right = right;

insertHeap(minHeap, parent);
2

2
67

67

67

67
}
E0

E0

E0

E0
BC

BC

BC

BC
return extractMin(minHeap);
23

23

23

23
}

// Function to generate Huffman codes


void generateCodes(Node* root, char code[], int top, char huffmanCodes[][MAX],
char characters[], int *index) {
if (root->left) {
code[top] = '0';
generateCodes(root->left, code, top + 1, huffmanCodes, characters, index);
}
72

72

72

2
67
if (root->right) {
06

06

06

E0
E

code[top] = '1';
BC

BC

BC

BC
generateCodes(root->right, code, top + 1, huffmanCodes, characters, index);
23

23

23

23
}

if (!root->left && !root->right) {


code[top] = '\0';
strcpy(huffmanCodes[*index], code);
characters[*index] = root->character;
(*index)++;
printf("%c: %s\n", root->character, code);
}
}
2

2
67

67

67

67
E0

E0

E0

E0

// Function to encode a message


BC

BC

BC

BC
23

23

23

23
void encodeMessage(char* message, char huffmanCodes[][MAX], char
2

72

72
67

67
characters[], int n) {

06

06
E0

E0
E

E
for (int i = 0; message[i] != '\0'; i++) {
BC

BC

BC

BC
for (int j = 0; j < n; j++) {
23

23

23

23
if (message[i] == characters[j]) {
printf("%s", huffmanCodes[j]);
break;
}
}
}
printf("\n");
}

// Function to decode a message


2

2
67

67

67

67
void decodeMessage(char* encodedMessage, Node* root) {
E0

E0

E0

E0
Node* current = root;
BC

BC

BC

BC
for (int i = 0; encodedMessage[i] != '\0'; i++) {
23

23

23

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

if (!current->left && !current->right) {


printf("%c", current->character);
current = root;
}
}
72

72

72

2
67
printf("\n");
06

06

06

E0
E

}
BC

BC

BC

BC
23

23

23

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

char characters[n];
int frequencies[n];

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


getchar(); // To consume newline
scanf("%c %d", &characters[i], &frequencies[i]);
2

2
67

67

67

67

}
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
Node* root = buildHuffmanTree(characters, frequencies, n);
2

72

72
67

67
06

06
E0

E0
E

E
char huffmanCodes[n][MAX];
BC

BC

BC

BC
char code[MAX];
23

23

23

23
int index = 0;
generateCodes(root, code, 0, huffmanCodes, characters, &index);

char message[MAX];
getchar(); // Consume newline
fgets(message, MAX, stdin);
message[strcspn(message, "\n")] = '\0'; // Remove newline character

encodeMessage(message, huffmanCodes, characters, n);


2

2
67

67

67

67
char encodedMessage[MAX] = "";
E0

E0

E0

E0
for (int i = 0; message[i] != '\0'; i++) {
BC

BC

BC

BC
for (int j = 0; j < n; j++) {
23

23

23

23
if (message[i] == characters[j]) {
strcat(encodedMessage, huffmanCodes[j]);
break;
}
}
}

decodeMessage(encodedMessage, root);

return 0;
72

72

72

2
67
}
06

06

06

E0
E

E
BC

BC

BC

Status : Partially correct BC


Marks : 7/10
23

23

23

23

2. Problem Statement

Kavina is fascinated by data compression techniques and is learning about


Huffman coding. She wants to write a program that can decode a
message encoded using a simple Huffman tree.

Kavina's program should handle a Huffman tree with two types of nodes:
2

internal nodes represented by a "*" character and leaf nodes containing


67

67

67

67
E0

E0

E0

E0

either "A" or "B". Given an encoded message and a Huffman tree, the
BC

BC

BC

BC
23

23

23

23
program should decode the message and print the original text.
2

72

72
67

67
06

06
E0

E0
E

E
Answer
BC

BC

BC

BC
23

23

23

23
// You are using GCC
#include <iostream>
#include <string>

using namespace std;

struct Node {
char character;
Node* left;
Node* right;
2

2
67

67

67

67
E0

E0

E0

E0
Node(char ch) : character(ch), left(nullptr), right(nullptr) {}
BC

BC

BC

BC
Node() : character('*'), left(nullptr), right(nullptr) {}
23

23

23

23
};

string decodeHuff(Node* root, const string& encodedMessage) {


string decodedMessage;
Node* currentNode = root;

for (char bit : encodedMessage) {


if (bit == '0') {
currentNode = currentNode->left;
} else {
72

72

72

2
currentNode = currentNode->right;

67
06

06

06

E0
}
E

E
BC

BC

BC

BC
23

23

23

23
if (currentNode->character != '*') {
decodedMessage += currentNode->character;
currentNode = root;
}
}

return decodedMessage;
}

int main() {
2

Node* root = new Node();


67

67

67

67
E0

E0

E0

E0

root->left = new Node('A');


BC

BC

BC

BC
23

23

23

23
root->right = new Node('B');
2

72

72
67

67
06

06
E0

E0
E

E
string encodedMessage;
BC

BC

BC

BC
cin >> encodedMessage;
23

23

23

23
string decodedMessage = decodeHuff(root, encodedMessage);

cout << decodedMessage << endl;

delete root->left;
delete root->right;
delete root;

return 0;
2

2
67

67

67

67
}
E0

E0

E0

E0
BC

BC

BC

BC
Status : Correct Marks : 10/10
23

23

23

23
72

72

72

2
67
06

06

06

E0
E

E
BC

BC

BC

BC
23

23

23

23
2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
VIT - Vellore
2

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 2_Maximum subarray_COD_Easy

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Coding
72

72

72

2
1. Problem Statement

67
06

06

06

E0
E

E
BC

BC

BC

Given an array A of size N, representing integers, process the array using a BC


23

23

23

23
sliding subarray of size K. For each subarray, identify the first even number
present in the subarray. Suppose no even number exists in a particular
subarray, output -1. The task is to output the result for each sliding
subarray from left to right in the array.

Example:
Input 1:
32
2

2
67

67

67

67

10 12 14
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
Explanation:
2

72

72
67

67
06

06
E0

E0
N = 3 (array size)

E
BC

BC

BC

BC
23

23

23

23
K = 2 (subarray size)
Array = [10, 12, 14]
First subarray[10, 12]:
Check 10: It's even
Output 10 (first even number found)
Move subarray
Second subarray [12, 14]:
2

2
67

67

67

67
E0

E0

E0

E0
Check 12: It's even
BC

BC

BC

BC
23

23

23

23
Output 12 (first even number found)
Output:
10 12

Input 2:
32
152
72

72

72

2
Explanation

67
06

06

06

E0
E

First subarray [1, 5]:


BC

BC

BC

BC
23

23

23

23
Check 1: Not even
Check 5: Not even
No even numbers found, output -1
Move subarray
Second subarray [5, 2]:
Check 5: Not even
2

Check 2: It's even


67

67

67

67
E0

E0

E0

E0

Output 2 (first even number found)


BC

BC

BC

BC
23

23

23

23
Output:
2

72

72
67

67
06

06
E0

E0
-1 2

E
BC

BC

BC

BC
23

23

23

23
Answer
// You are using GCC
#include <stdio.h>

void findFirstEvenInSubarrays(int arr[], int n, int k) {


for (int i = 0; i <= n - k; i++) {
int foundEven = 0;
for (int j = i; j < i + k; j++) {
if (arr[j] % 2 == 0) {
printf("%d ", arr[j]);
2

2
67

67

67

67
foundEven = 1;
E0

E0

E0

E0
BC

BC

BC

BC
break;
23

23

23

23
}
}
if (!foundEven) {
printf("-1 ");
}
}
printf("\n");
}

int main() {
int n, k;
72

72

72

2
67
06

06

06

E0
E

E
BC

BC

BC

BC
// Input the size of the array (n) and size of the subarray (k)
23

23

23

23
scanf("%d %d", &n, &k);

int arr[n];

// Input the array elements


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Process the array


findFirstEvenInSubarrays(arr, n, k);
2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC

return 0;
23

23

23

23
}
2

72

72
67

67
06

06
E0

E0
E

E
Status : Correct Marks : 10/10
BC

BC

BC

BC
23

23

23

23
2. Problem Statement

You are given an array of integers. Your task is to find the longest subarray
in which the elements are first sorted in increasing order and then in
decreasing order. A subarray is defined as a contiguous sequence of
elements from the original array. Your program should output the length of
this bitonic subarray and the elements it contains.
2

2
Answer
67

67

67

67
E0

E0

E0

E0
// You are using GCC
BC

BC

BC

BC
23

23

23

23
#include <stdio.h>

void findLongestBitonicSubarray(int arr[], int n) {


int inc[n], dec[n];

// Initialize increasing and decreasing arrays


inc[0] = 1;
dec[n - 1] = 1;

// Fill the increasing subarray lengths


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

72

72

2
67
06

06

06

if (arr[i] > arr[i - 1]) {

E0
E

inc[i] = inc[i - 1] + 1;
BC

BC

BC

BC
23

23

23

23
} else {
inc[i] = 1;
}
}

// Fill the decreasing subarray lengths


for (int i = n - 2; i >= 0; i--) {
if (arr[i] > arr[i + 1]) {
dec[i] = dec[i + 1] + 1;
} else {
dec[i] = 1;
2

2
67

67

67

67

}
E0

E0

E0

E0

}
BC

BC

BC

BC
23

23

23

23
2

72

72
67

67
// Find the maximum length of bitonic subarray

06

06
E0

E0
E

E
int maxLength = 0, startIdx = 0;
BC

BC

BC

BC
for (int i = 0; i < n; i++) {
23

23

23

23
int currentLength = inc[i] + dec[i] - 1;
if (currentLength > maxLength) {
maxLength = currentLength;
startIdx = i - inc[i] + 1;
}
}

// Output the results


printf("%d\n", maxLength);
for (int i = startIdx; i < startIdx + maxLength; i++) {
2

2
67

67

67

67
printf("%d ", arr[i]);
E0

E0

E0

E0
}
BC

BC

BC

BC
printf("\n");
23

23

23

23
}

int main() {
int n;

// Input the size of the array


scanf("%d", &n);

int arr[n];
72

72

72

2
67
// Input the array elements
06

06

06

E0
E

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


BC

BC

BC

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

23

23

23
}

// Find and print the longest bitonic subarray


findLongestBitonicSubarray(arr, n);

return 0;
}

Status : Correct Marks : 10/10


2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
VIT - Vellore
2

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 2_Maximum subarray_COD_Medium

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Coding
72

72

72

2
1. Problem Statement

67
06

06

06

E0
E

E
BC

BC

BC

Sarah is analyzing the sales performance of her store over a series of BC


23

23

23

23
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:
2

2
67

67

67

67

5
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
-3 1 -1 5 6
2

72

72
67

67
06

06
E0

E0
E

E
Output:
BC

BC

BC

BC
23

23

23

23
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.
2

2
67

67

67

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

E0

E0

E0
BC

BC

BC

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

23

23

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

Answer
// You are using GCC
#include <stdio.h>
#include <limits.h>

// Function to find the maximum crossing subarray


72

72

72

2
67
int find_max_crossing_subarray(int arr[], int low, int mid, int high, int* start, int*
06

06

06

E0
E

end) {
BC

BC

BC

int left_sum = INT_MIN; BC


23

23

23

23
int sum = 0;
int max_left = mid;

for (int i = mid; i >= low; i--) {


sum += arr[i];
if (sum > left_sum) {
left_sum = sum;
max_left = i;
}
}
2

2
67

67

67

67
E0

E0

E0

E0

int right_sum = INT_MIN;


BC

BC

BC

BC
23

23

23

23
sum = 0;
2

72

72
67

67
int max_right = mid + 1;

06

06
E0

E0
E

E
BC

BC

BC

BC
for (int j = mid + 1; j <= high; j++) {
23

23

23

23
sum += arr[j];
if (sum > right_sum) {
right_sum = sum;
max_right = j;
}
}

*start = max_left;
*end = max_right;
return left_sum + right_sum;
2

2
67

67

67

67
}
E0

E0

E0

E0
BC

BC

BC

BC
// Function to find the maximum subarray using divide and conquer
23

23

23

23
int find_maximum_subarray(int arr[], int low, int high, int* start, int* end) {
if (low == high) {
*start = low;
*end = high;
return arr[low];
}

int mid = (low + high) / 2;

int left_start, left_end;


72

72

72

2
67
int right_start, right_end;
06

06

06

E0
E

int cross_start, cross_end;


BC

BC

BC

BC
23

23

23

23
int left_sum = find_maximum_subarray(arr, low, mid, &left_start, &left_end);
int right_sum = find_maximum_subarray(arr, mid + 1, high, &right_start,
&right_end);
int cross_sum = find_max_crossing_subarray(arr, low, mid, high, &cross_start,
&cross_end);

if (left_sum >= right_sum && left_sum >= cross_sum) {


*start = left_start;
*end = left_end;
return left_sum;
2

2
67

67

67

67

} else if (right_sum >= left_sum && right_sum >= cross_sum) {


E0

E0

E0

E0

*start = right_start;
BC

BC

BC

BC
23

23

23

23
*end = right_end;
2

72

72
67

67
return right_sum;

06

06
E0

E0
E

E
} else {
BC

BC

BC

BC
*start = cross_start;
23

23

23

23
*end = cross_end;
return cross_sum;
}
}

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

int arr[n];
2

2
67

67

67

67
for (int i = 0; i < n; i++) {
E0

E0

E0

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

BC

BC

BC
}
23

23

23

23
int start, end;
int max_sum = find_maximum_subarray(arr, 0, n - 1, &start, &end);

double average = (double)max_sum / (end - start + 1);

printf("%d\n", max_sum);
printf("%.2f\n", average);
printf("[");
for (int i = start; i <= end; i++) {
72

72

72

2
67
printf("%d", arr[i]);
06

06

06

E0
E

if (i < end) {
BC

BC

BC

printf(", "); BC
23

23

23

23
}
}
printf("]\n");

return 0;
}

Status : Correct Marks : 10/10


2

2
67

67

67

67

2. Problem Statement
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
2

72

72
Given an integer array nums and an integer k, return the number of non-
67

67
06

06
E0

E0
empty subarrays that have a sum divisible by k.

E
BC

BC

BC

BC
23

23

23

23
A subarray is a contiguous part of an array.

Example 1

Input:
6
4 5 0 -2 -3 1
5
2

2
67

67

67

67
E0

E0

E0

E0
Output:
BC

BC

BC

BC
23

23

23

23
7

Explanation:
There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

Example 2
72

72

72

2
Input:

67
06

06

06

E0
E

1
BC

BC

BC

BC
23

23

23

23
5
9

Output:
0

Explanation:
The sum of elements from 1st position to 5th position is 15.
2

2
67

67

67

67
E0

E0

E0

E0

Answer
BC

BC

BC

BC
23

23

23

23
// You are using GCC
2

72

72
67

67
#include <stdio.h>

06

06
E0

E0
E

E
BC

BC

BC

BC
int countSubarraysDivisibleByK(int arr[], int n, int k) {
23

23

23

23
int prefixSum = 0, count = 0;
int remainderCount[k];

// Initialize remainderCount array to 0


for (int i = 0; i < k; i++) {
remainderCount[i] = 0;
}

// Remainder 0 count starts with 1 (empty subarray case)


remainderCount[0] = 1;
2

2
67

67

67

67
E0

E0

E0

E0
for (int i = 0; i < n; i++) {
BC

BC

BC

BC
prefixSum += arr[i];
23

23

23

23
int remainder = prefixSum % k;

// Handle negative remainders


if (remainder < 0) {
remainder += k;
}

// Add the count of subarrays ending at index `i` with the same remainder
count += remainderCount[remainder];
72

72

72

2
67
// Increment the remainder count
06

06

06

E0
E

remainderCount[remainder]++;
BC

BC

BC

} BC
23

23

23

23

return count;
}

int main() {
int n, k;

// Input the size of the array


scanf("%d", &n);
2

2
67

67

67

67

int arr[n];
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
// Input the elements of the array
2

72

72
67

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

06

06
E0

E0
E

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

BC

BC

BC
}
23

23

23

23
// Input the divisor
scanf("%d", &k);

// Find and print the count of subarrays divisible by k


printf("%d\n", countSubarraysDivisibleByK(arr, n, k));

return 0;
}
2

2
67

67

67

67
Status : Correct Marks : 10/10
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
72

72

72

2
67
06

06

06

E0
E

E
BC

BC

BC

BC
23

23

23

23
2

2
67

67

67

67
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
VIT - Vellore
2

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 2_Karatsuba algo_COD_Easy

Attempt : 1
Total Mark : 20
Marks Obtained : 20

Section 1 : Coding
72

72

72

2
1. Problem Statement

67
06

06

06

E0
E

E
BC

BC

BC

Emma is dealing with large numbers that include decimal points. She BC
23

23

23

23
wants to multiply two large floating-point numbers using the Karatsuba
algorithm.

Answer
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
2

// Karatsuba algorithm for multiplying two large integers


67

67

67

67

long long karatsuba(long long x, long long y) {


E0

E0

E0

E0
BC

BC

BC

BC

if (x < 10 || y < 10) {


23

23

23

23
return x * y;
2

72

72
67

67
}

06

06
E0

E0
E

E
BC

BC

BC

BC
// Calculate the size of the numbers
23

23

23

23
int n = (int)fmax(log10(x) + 1, log10(y) + 1);
int half = n / 2;

long long power = (long long)pow(10, half);


long long high1 = x / power;
long long low1 = x % power;
long long high2 = y / power;
long long low2 = y % power;

// Recursive steps
2

2
67

67

67

67
long long z0 = karatsuba(low1, low2);
E0

E0

E0

E0
long long z1 = karatsuba((low1 + high1), (low2 + high2));
BC

BC

BC

BC
long long z2 = karatsuba(high1, high2);
23

23

23

23
return z2 * power * power + (z1 - z2 - z0) * power + z0;
}

// Function to remove the decimal point and convert to an integer


long long removeDecimal(const char* numStr, int* decimalPlaces) {
int len = strlen(numStr);
char buffer[50] = {0};
int pos = 0;
72

72

72

2
67
*decimalPlaces = 0;
06

06

06

E0
E

for (int i = 0; i < len; i++) {


BC

BC

BC

if (numStr[i] == '.') { BC
23

23

23

23
*decimalPlaces = len - i - 1; // Count digits after the decimal
} else {
buffer[pos++] = numStr[i];
}
}

return atoll(buffer);
}

int main() {
2

2
67

67

67

67

char num1[50], num2[50];


E0

E0

E0

E0

scanf("%s", num1);
BC

BC

BC

BC
23

23

23

23
scanf("%s", num2);
2

72

72
67

67
06

06
E0

E0
E

E
int decimals1, decimals2;
BC

BC

BC

BC
long long intPart1 = removeDecimal(num1, &decimals1);
23

23

23

23
long long intPart2 = removeDecimal(num2, &decimals2);

// Calculate total decimal places in the result


int totalDecimals = decimals1 + decimals2;

// Perform multiplication using Karatsuba


long long product = karatsuba(intPart1, intPart2);

// Adjust the result back to include decimal places


double finalResult = product / pow(10, totalDecimals);
2

2
67

67

67

67
E0

E0

E0

E0
// Print the result rounded to three decimal places
BC

BC

BC

BC
printf("%.3f\n", finalResult);
23

23

23

23
return 0;
}

Status : Correct Marks : 10/10

2. Problem Statement

John is developing a program to perform multiplication of large numbers


72

72

72

2
67
06

06

06

efficiently. Instead of using the standard multiplication method, he wants

E0
E

E
BC

BC

BC

BC
to implement the Karatsuba algorithm, which breaks the numbers into
23

23

23

23
parts and recursively computes the product.

Your task is to help John implement this algorithm and compute the
product of two large numbers.

Answer
// You are using GCC
#include <stdio.h>
#include <math.h>
2

2
67

67

67

67

// Karatsuba algorithm for multiplying two large integers


E0

E0

E0

E0
BC

BC

BC

BC

long long karatsuba(long long x, long long y) {


23

23

23

23
// Base case: If numbers are small, multiply directly
2

72

72
67

67
if (x < 10 || y < 10) {

06

06
E0

E0
E

E
return x * y;
BC

BC

BC

BC
}
23

23

23

23
// Calculate the number of digits in the largest number
int n = (int)fmax(log10(x) + 1, log10(y) + 1);
int half = n / 2;

// Split the numbers into high and low parts


long long power = (long long)pow(10, half);
long long high1 = x / power;
long long low1 = x % power;
long long high2 = y / power;
2

2
67

67

67

67
long long low2 = y % power;
E0

E0

E0

E0
BC

BC

BC

BC
// Recursive steps
23

23

23

23
long long z0 = karatsuba(low1, low2); // Low1 * Low2
long long z1 = karatsuba((low1 + high1), (low2 + high2)); // (Low1 + High1) *
(Low2 + High2)
long long z2 = karatsuba(high1, high2); // High1 * High2

// Combine the results


return z2 * power * power + (z1 - z2 - z0) * power + z0;
}

int main() {
72

72

72

2
67
long long x, y;
06

06

06

E0
E

scanf("%lld", &x);
BC

BC

BC

scanf("%lld", &y); BC
23

23

23

23

// Compute the product using Karatsuba algorithm


long long result = karatsuba(x, y);

// Print the result


printf("%lld\n", result);

return 0;
}
2

2
67

67

67

67

Status : Correct Marks : 10/10


E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
VIT - Vellore
2

72

72
67

67
06

06
E0

E0
E

E
BC

BC

BC

BC
Name: RITHWIK SUNDAR . Scan to verify results
23

23

23

23
Email: [email protected]
Roll no: 23BCE0672
Phone: 9898989898
Branch: BALASUBRAMANIAN V_JAVA
Department: admin
Batch: VL2024250102602
Degree: admin
2

2
67

67

67

67
BCSE204P_Design and Analysis of Algorithms
E0

E0

E0

E0
BC

BC

BC

BC
Lab_VL2024250503079
23

23

23

23
VIT V_DAA_Week 2_Karatsuba algo_COD_Medium

Attempt : 1
Total Mark : 10
Marks Obtained : 10

Section 1 : Coding
72

72

72

2
1. Problem Statement

67
06

06

06

E0
E

E
BC

BC

BC

John needs to multiply several pairs of large numbers in a single program. BC


23

23

23

23
He wants to use the Karatsuba algorithm for efficient computation. Help
John to complete the task.

Answer
// You are using GCC
#include <stdio.h>
#include <math.h>

// Karatsuba algorithm for multiplying two large integers


2

long long karatsuba(long long x, long long y) {


67

67

67

67

// Base case: If numbers are small, multiply directly


E0

E0

E0

E0
BC

BC

BC

BC

if (x < 10 || y < 10) {


23

23

23

23
return x * y;
2

72

72
67

67
}

06

06
E0

E0
E

E
BC

BC

BC

BC
// Calculate the number of digits in the largest number
23

23

23

23
int n = (int)fmax(log10(x) + 1, log10(y) + 1);
int half = n / 2;

// Split the numbers into high and low parts


long long power = (long long)pow(10, half);
long long high1 = x / power;
long long low1 = x % power;
long long high2 = y / power;
long long low2 = y % power;
2

2
67

67

67

67
// Recursive steps
E0

E0

E0

E0
long long z0 = karatsuba(low1, low2); // Low1 * Low2
BC

BC

BC

BC
long long z1 = karatsuba((low1 + high1), (low2 + high2)); // (Low1 + High1) *
23

23

23

23
(Low2 + High2)
long long z2 = karatsuba(high1, high2); // High1 * High2

// Combine the results


return z2 * power * power + (z1 - z2 - z0) * power + z0;
}

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

72

72

2
67
06

06

06

E0
E

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


BC

BC

BC

long long x, y; BC
23

23

23

23
scanf("%lld %lld", &x, &y);

// Compute the product using Karatsuba algorithm


long long result = karatsuba(x, y);

// Print the result


printf("Product of pair %d: %lld\n", i, result);
}

return 0;
2

2
67

67

67

67

}
E0

E0

E0

E0
BC

BC

BC

BC
23

23

23

23
23 23 23 23
BC BC BC BC
E0 E 06 E0 E0
67 67 67
2 72 2 2
Status : Correct

23 23 23 23
BC BC BC BC
E0 E06 E0 E 06
67 67
2 72 2 72

23 23 23 23
BC BC BC BC
E0 E 06 E0 E0
67 67 67
2 72 2 2

23 23 23 23
BC BC BC BC
Marks : 10/10

E0 E0 E0 E 06
67 67 67
2 2 2 72

You might also like