Compare commits
25 Commits
cf2b2c43a9
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
ff72fdf47c
|
|||
|
028eb10661
|
|||
|
e8327327d4
|
|||
|
d53169d89f
|
|||
|
ecd6ecae64
|
|||
|
e051c585bc
|
|||
|
f24c40a32e
|
|||
|
158b164fa4
|
|||
|
5c39b18d49
|
|||
|
21eac5a235
|
|||
|
ab568b290b
|
|||
|
1cd69b32e7
|
|||
|
fbaf0330da
|
|||
|
c27d224e93
|
|||
|
bf4f5beb17
|
|||
|
a39a53ea90
|
|||
|
2d45b17899
|
|||
|
fa5f3f94a4
|
|||
|
13bebfc613
|
|||
|
5fdb6776e8
|
|||
|
871e4e9474
|
|||
|
51ebf36804
|
|||
|
493cfbe596
|
|||
|
86ae1c2550
|
|||
|
6dc71e1d77
|
@@ -0,0 +1,64 @@
|
|||||||
|
// Code-A1 (Fibonacci)
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
int recursiveSteps = 0;
|
||||||
|
int iterativeSteps = 0;
|
||||||
|
|
||||||
|
// Recursive function for Fibonacci
|
||||||
|
int fibRecursive(int n) {
|
||||||
|
recursiveSteps++;
|
||||||
|
if (n <= 1)
|
||||||
|
return n;
|
||||||
|
return fibRecursive(n - 1) + fibRecursive(n - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-recursive (Iterative) Fibonacci
|
||||||
|
void fibIterative(int n) {
|
||||||
|
if (n <= 0)
|
||||||
|
return;
|
||||||
|
int prev = 0, curr = 1, next;
|
||||||
|
cout << prev << " ";
|
||||||
|
if (n == 1)
|
||||||
|
return;
|
||||||
|
|
||||||
|
cout << curr << " ";
|
||||||
|
for (int i = 2; i < n; i++) {
|
||||||
|
next = prev + curr;
|
||||||
|
cout << next << " ";
|
||||||
|
prev = curr;
|
||||||
|
curr = next;
|
||||||
|
iterativeSteps++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n;
|
||||||
|
cout << "Enter the number of terms: ";
|
||||||
|
cin >> n;
|
||||||
|
|
||||||
|
cout << "\nFibonacci Series using Recursion: ";
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
cout << fibRecursive(i) << " ";
|
||||||
|
}
|
||||||
|
cout << "\nTotal Recursive Steps: " << recursiveSteps;
|
||||||
|
|
||||||
|
cout << "\n\nFibonacci Series using Iteration: ";
|
||||||
|
fibIterative(n);
|
||||||
|
cout << "\nTotal Iterative Steps: " << iterativeSteps;
|
||||||
|
|
||||||
|
cout << endl;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAMPLE OUTOUT
|
||||||
|
/*
|
||||||
|
* Enter the number of terms: 5
|
||||||
|
*
|
||||||
|
* Fibonacci Series using Recursion: 0 1 1 2 3
|
||||||
|
* Total Recursive Steps: 19
|
||||||
|
*
|
||||||
|
* Fibonacci Series using Iteration: 0 1 1 2 3
|
||||||
|
* Total Iterative Steps: 3
|
||||||
|
*/
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// Code-A2 (Huffman Coding)
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <queue>
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
// A Huffman Tree node
|
||||||
|
struct Node {
|
||||||
|
char ch;
|
||||||
|
int freq;
|
||||||
|
Node *left, *right;
|
||||||
|
|
||||||
|
Node(char c, int f) {
|
||||||
|
ch = c;
|
||||||
|
freq = f;
|
||||||
|
left = right = nullptr;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Compare function for priority queue (min-heap)
|
||||||
|
struct Compare {
|
||||||
|
bool operator()(Node* a, Node* b) {
|
||||||
|
return a->freq > b->freq; // smaller frequency => higher priority
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Recursive function to print Huffman Codes
|
||||||
|
void printCodes(Node* root, string code) {
|
||||||
|
if (!root) return;
|
||||||
|
|
||||||
|
// Leaf node -> contains a character
|
||||||
|
if (!root->left && !root->right)
|
||||||
|
cout << root->ch << " : " << code << endl;
|
||||||
|
|
||||||
|
printCodes(root->left, code + "0");
|
||||||
|
printCodes(root->right, code + "1");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main function to build Huffman Tree and generate codes
|
||||||
|
void huffmanEncoding(vector<char>& chars, vector<int>& freq) {
|
||||||
|
priority_queue<Node*, vector<Node*>, Compare> pq;
|
||||||
|
|
||||||
|
// Step 1: Create a leaf node for each character and add it to the queue
|
||||||
|
for (int i = 0; i < chars.size(); i++)
|
||||||
|
pq.push(new Node(chars[i], freq[i]));
|
||||||
|
|
||||||
|
// Step 2: Repeat until one node remains (the root)
|
||||||
|
while (pq.size() > 1) {
|
||||||
|
Node* left = pq.top(); pq.pop();
|
||||||
|
Node* right = pq.top(); pq.pop();
|
||||||
|
|
||||||
|
// Create new internal node with sum of two smallest frequencies
|
||||||
|
Node* newNode = new Node('-', left->freq + right->freq);
|
||||||
|
newNode->left = left;
|
||||||
|
newNode->right = right;
|
||||||
|
|
||||||
|
pq.push(newNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 3: Print the Huffman codes
|
||||||
|
Node* root = pq.top();
|
||||||
|
cout << "\nHuffman Codes:\n";
|
||||||
|
printCodes(root, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n;
|
||||||
|
cout << "Enter number of characters: ";
|
||||||
|
cin >> n;
|
||||||
|
|
||||||
|
vector<char> chars(n);
|
||||||
|
vector<int> freq(n);
|
||||||
|
|
||||||
|
cout << "Enter characters: ";
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
cin >> chars[i];
|
||||||
|
|
||||||
|
cout << "Enter corresponding frequencies: ";
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
cin >> freq[i];
|
||||||
|
|
||||||
|
huffmanEncoding(chars, freq);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAMPLE OUTPUT
|
||||||
|
/*
|
||||||
|
* $ ./a.out
|
||||||
|
* Enter number of characters: 5
|
||||||
|
* Enter characters: a f v c w
|
||||||
|
* Enter corresponding frequencies: 3 2 1 5 7
|
||||||
|
*
|
||||||
|
* Huffman Codes:
|
||||||
|
* w : 0
|
||||||
|
* c : 10
|
||||||
|
* a : 110
|
||||||
|
* v : 1110
|
||||||
|
* f : 1111
|
||||||
|
*/
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// Code-A3 (Fractical Knapsack)
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <vector>
|
||||||
|
#include <algorithm>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
// Structure for an item
|
||||||
|
struct Item {
|
||||||
|
int weight;
|
||||||
|
int value;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Comparison function to sort items by value/weight ratio
|
||||||
|
bool compare(Item a, Item b) {
|
||||||
|
double r1 = (double)a.value / a.weight;
|
||||||
|
double r2 = (double)b.value / b.weight;
|
||||||
|
return r1 > r2; // Sort in descending order
|
||||||
|
}
|
||||||
|
|
||||||
|
double fractionalKnapsack(int W, vector<Item>& items) {
|
||||||
|
// Sort items by value-to-weight ratio
|
||||||
|
sort(items.begin(), items.end(), compare);
|
||||||
|
|
||||||
|
double totalValue = 0.0; // Total value in knapsack
|
||||||
|
for (auto &i : items) {
|
||||||
|
if (W == 0) break; // Knapsack is full
|
||||||
|
|
||||||
|
// If item can be fully taken
|
||||||
|
if (i.weight <= W) {
|
||||||
|
W -= i.weight;
|
||||||
|
totalValue += i.value;
|
||||||
|
} else {
|
||||||
|
// Take fraction of item
|
||||||
|
totalValue += i.value * ((double)W / i.weight);
|
||||||
|
W = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return totalValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n, W;
|
||||||
|
cout << "Enter number of items: ";
|
||||||
|
cin >> n;
|
||||||
|
|
||||||
|
vector<Item> items(n);
|
||||||
|
cout << "Enter value and weight of each item:\n";
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
cin >> items[i].value >> items[i].weight;
|
||||||
|
|
||||||
|
cout << "Enter capacity of knapsack: ";
|
||||||
|
cin >> W;
|
||||||
|
|
||||||
|
double maxValue = fractionalKnapsack(W, items);
|
||||||
|
cout << "\nMaximum value in knapsack = " << maxValue << endl;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAMPLE OUTPUT
|
||||||
|
/*
|
||||||
|
* $ ./a.out
|
||||||
|
* Enter number of items: 3
|
||||||
|
* Enter value and weight of each item:
|
||||||
|
* 12 32
|
||||||
|
* 56 67
|
||||||
|
* 23 87
|
||||||
|
* Enter capacity of knapsack: 45
|
||||||
|
*
|
||||||
|
* Maximum value in knapsack = 37.6119
|
||||||
|
*/
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// Code-A4 (0-1 Knapsack)
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <vector>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
int knapsack(int W, vector<int>& wt, vector<int>& val, int n) {
|
||||||
|
// dp[i][w] = max value for first i items with weight limit w
|
||||||
|
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
|
||||||
|
|
||||||
|
// Build the table dp[][] bottom-up
|
||||||
|
for (int i = 1; i <= n; i++) {
|
||||||
|
for (int w = 1; w <= W; w++) {
|
||||||
|
if (wt[i - 1] <= w)
|
||||||
|
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
|
||||||
|
else
|
||||||
|
dp[i][w] = dp[i - 1][w];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return dp[n][W]; // The bottom-right cell gives the result
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n, W;
|
||||||
|
cout << "Enter number of items: ";
|
||||||
|
cin >> n;
|
||||||
|
|
||||||
|
vector<int> val(n), wt(n);
|
||||||
|
cout << "Enter values of items:\n";
|
||||||
|
for (int i = 0; i < n; i++) cin >> val[i];
|
||||||
|
|
||||||
|
cout << "Enter weights of items:\n";
|
||||||
|
for (int i = 0; i < n; i++) cin >> wt[i];
|
||||||
|
|
||||||
|
cout << "Enter capacity of knapsack: ";
|
||||||
|
cin >> W;
|
||||||
|
|
||||||
|
int maxValue = knapsack(W, wt, val, n);
|
||||||
|
cout << "\nMaximum value in knapsack = " << maxValue << endl;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAMPLE OUTPUT
|
||||||
|
/*
|
||||||
|
* $ ./a.out
|
||||||
|
* Enter number of items: 3
|
||||||
|
* Enter values of items:
|
||||||
|
* 12
|
||||||
|
* 32
|
||||||
|
* 14
|
||||||
|
* Enter weights of items:
|
||||||
|
* 45
|
||||||
|
* 34
|
||||||
|
* 65
|
||||||
|
* Enter capacity of knapsack: 60
|
||||||
|
*
|
||||||
|
* Maximum value in knapsack = 32
|
||||||
|
*/
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// Code-A5 (N-Queen)
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <vector>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
// Function to print the board
|
||||||
|
void printBoard(vector<vector<int>>& board, int n) {
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
for (int j = 0; j < n; j++)
|
||||||
|
cout << board[i][j] << " ";
|
||||||
|
cout << endl;
|
||||||
|
}
|
||||||
|
cout << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to check if placing a queen is safe
|
||||||
|
bool isSafe(vector<vector<int>>& board, int row, int col, int n) {
|
||||||
|
// Check column
|
||||||
|
for (int i = 0; i < row; i++)
|
||||||
|
if (board[i][col]) return false;
|
||||||
|
|
||||||
|
// Check upper left diagonal
|
||||||
|
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
|
||||||
|
if (board[i][j]) return false;
|
||||||
|
|
||||||
|
// Check upper right diagonal
|
||||||
|
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
|
||||||
|
if (board[i][j]) return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backtracking function
|
||||||
|
bool solveNQueens(vector<vector<int>>& board, int row, int n) {
|
||||||
|
if (row == n) {
|
||||||
|
printBoard(board, n); // Print one valid arrangement
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int col = 0; col < n; col++) {
|
||||||
|
if (isSafe(board, row, col, n)) {
|
||||||
|
board[row][col] = 1; // Place queen
|
||||||
|
solveNQueens(board, row + 1, n);
|
||||||
|
board[row][col] = 0; // Backtrack
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n, firstRow, firstCol;
|
||||||
|
cout << "Enter size of board (N): ";
|
||||||
|
cin >> n;
|
||||||
|
|
||||||
|
vector<vector<int>> board(n, vector<int>(n, 0));
|
||||||
|
|
||||||
|
cout << "Enter position of first queen (row and column index starting from 0): ";
|
||||||
|
cin >> firstRow >> firstCol;
|
||||||
|
|
||||||
|
// Place first queen
|
||||||
|
board[firstRow][firstCol] = 1;
|
||||||
|
|
||||||
|
cout << "\nAll possible solutions:\n";
|
||||||
|
solveNQueens(board, 0, n); // Start solving from row 0
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAMPLE OUTPUT
|
||||||
|
/*
|
||||||
|
* $ ./a.out
|
||||||
|
* Enter size of board (N): 4
|
||||||
|
* Enter position of first queen (row and column index starting from 0): 0 0
|
||||||
|
*
|
||||||
|
* All possible solutions:
|
||||||
|
* 0 1 0 0
|
||||||
|
* 0 0 0 1
|
||||||
|
* 1 0 0 0
|
||||||
|
* 0 0 1 0
|
||||||
|
*
|
||||||
|
* 0 0 1 0
|
||||||
|
* 1 0 0 0
|
||||||
|
* 0 0 0 1
|
||||||
|
* 0 1 0 0
|
||||||
|
*/
|
||||||
Executable → Regular
+41
-24
@@ -1,33 +1,50 @@
|
|||||||
|
# Code-A1 (Fibonacci)
|
||||||
# Problem Statement: Write a program non-recursive and recursive program to calculate Fibonacci numbers and analyze their time and space complexity.
|
# Problem Statement: Write a program non-recursive and recursive program to calculate Fibonacci numbers and analyze their time and space complexity.
|
||||||
|
|
||||||
# Non-recursion
|
# Initalize global variables
|
||||||
def fibonacci(n):
|
iteration_counter = 0
|
||||||
fib_series = []
|
recursion_counter = 0
|
||||||
a = 0
|
|
||||||
b = 1
|
|
||||||
|
|
||||||
for i in range(n):
|
# Iteration
|
||||||
fib_series.append(a)
|
def fibonacci_iteration(n):
|
||||||
a, b = b, a + b
|
fib_series = [] # For storing Fibonacci series
|
||||||
|
previous = 0 # Previous
|
||||||
|
current = 1 # Next
|
||||||
|
global iteration_counter # Global iteration counter
|
||||||
|
iteration_counter = 0 # Initialize global iteration counter to 0
|
||||||
|
|
||||||
return fib_series
|
for i in range(n):
|
||||||
|
fib_series.append(previous)
|
||||||
|
previous, current = current, previous + current
|
||||||
|
iteration_counter += 1
|
||||||
|
|
||||||
|
return fib_series
|
||||||
|
|
||||||
# Recursion
|
# Recursion
|
||||||
def fibonacci_recursive(n):
|
def fibonacci_recursion(n):
|
||||||
if n <= 0:
|
global recursion_counter # Global recursion counter
|
||||||
return []
|
recursion_counter += 1 # Increment recursion counter for each call
|
||||||
elif n == 1:
|
|
||||||
return [0]
|
if (n <= 0): # Handle n less than or equal to 0
|
||||||
elif n == 2:
|
return 0
|
||||||
return [0, 1]
|
elif (n <= 1): # Handle n less than or equal to 1
|
||||||
else:
|
return n
|
||||||
fib_series = fibonacci_recursive(n - 1) # Get the series up to n-1
|
else: # Recursive call
|
||||||
fib_series.append(fib_series[-1] + fib_series[-2]) # Append the next Fibonacci number
|
return fibonacci_recursion(n - 1) + fibonacci_recursion(n - 2)
|
||||||
return fib_series
|
|
||||||
|
|
||||||
# Non-recursion
|
|
||||||
n = int(input("Enter total numbers to print in fibonacci series:\t"))
|
n = int(input("Enter total numbers to print in fibonacci series:\t"))
|
||||||
print("Fibonacci Series (non-recusive):\t", fibonacci(n))
|
|
||||||
|
|
||||||
# Recursion
|
# Fibonacci using iteration
|
||||||
print("Fibonacci Series (recusive):\t\t", fibonacci_recursive(n))
|
fib_series = fibonacci_iteration(n)
|
||||||
|
print(f"Fibonacci using iteration:\t{fib_series}")
|
||||||
|
print(f"Iteration counter:\t{iteration_counter}| Time Complexity: O(n) (linear growth)")
|
||||||
|
|
||||||
|
print("="*80)
|
||||||
|
|
||||||
|
# Fibonacci using recursion
|
||||||
|
fib_series = []
|
||||||
|
for i in range(n):
|
||||||
|
fib_series.append(fibonacci_recursion(i))
|
||||||
|
print(f"Fibonacci using recursion:\t{fib_series}")
|
||||||
|
print(f"Recursion counter:\t{recursion_counter} | Time Complexity: O(2^n) (exponential growth)")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Problem Statement: Write a program non-recursive and recursive program to calculate Fibonacci numbers and analyze their time and space complexity.
|
||||||
|
|
||||||
|
## NOTE: THIS IS A HEAVILY OPTIMIZED CODE FOR FIBONACCI.
|
||||||
|
## NUMBER OF RECURSION CALLS (IN RECURSION) ARE LOWER THAN NUMBER OF ITERATIONS (IN ITERATION FUNCTION)
|
||||||
|
|
||||||
|
iteration_counter = 0
|
||||||
|
recursion_counter = 0
|
||||||
|
|
||||||
|
# Non-recursion
|
||||||
|
def fibonacci(n):
|
||||||
|
global iteration_counter
|
||||||
|
fib_series = []
|
||||||
|
a = 0
|
||||||
|
b = 1
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
fib_series.append(a)
|
||||||
|
a, b = b, a + b
|
||||||
|
iteration_counter += 1
|
||||||
|
|
||||||
|
return fib_series
|
||||||
|
|
||||||
|
# Recursion
|
||||||
|
def fibonacci_recursive(n):
|
||||||
|
global recursion_counter
|
||||||
|
recursion_counter += 1
|
||||||
|
if n <= 0:
|
||||||
|
return []
|
||||||
|
elif n == 1:
|
||||||
|
return [0]
|
||||||
|
elif n == 2:
|
||||||
|
return [0, 1]
|
||||||
|
else:
|
||||||
|
fib_series = fibonacci_recursive(n - 1) # Get the series up to n-1
|
||||||
|
fib_series.append(fib_series[-1] + fib_series[-2]) # Append the next Fibonacci number
|
||||||
|
return fib_series
|
||||||
|
|
||||||
|
# Non-recursion
|
||||||
|
n = int(input("Enter total numbers to print in fibonacci series:\t"))
|
||||||
|
print("Fibonacci Series (non-recusive):\t", fibonacci(n))
|
||||||
|
print("Iteration counter:\t", iteration_counter)
|
||||||
|
|
||||||
|
# Recursion
|
||||||
|
print("Fibonacci Series (recusive):\t\t", fibonacci_recursive(n))
|
||||||
|
print("Recursion counter:\t", recursion_counter)
|
||||||
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# Code-A2 (Huffman Coding)
|
||||||
|
|
||||||
|
import heapq
|
||||||
|
|
||||||
|
# Node class for Huffman Tree
|
||||||
|
class Node:
|
||||||
|
def __init__(self, char, freq):
|
||||||
|
self.char = char
|
||||||
|
self.freq = freq
|
||||||
|
self.left = None
|
||||||
|
self.right = None
|
||||||
|
|
||||||
|
# Comparison function for priority queue
|
||||||
|
def __lt__(self, other):
|
||||||
|
return self.freq < other.freq
|
||||||
|
|
||||||
|
|
||||||
|
# Function to build Huffman Tree
|
||||||
|
def build_huffman_tree(char_freq):
|
||||||
|
heap = [Node(ch, freq) for ch, freq in char_freq.items()]
|
||||||
|
heapq.heapify(heap)
|
||||||
|
|
||||||
|
while len(heap) > 1:
|
||||||
|
# Pick two smallest nodes (greedy choice)
|
||||||
|
left = heapq.heappop(heap)
|
||||||
|
right = heapq.heappop(heap)
|
||||||
|
|
||||||
|
# Merge them into a new node
|
||||||
|
merged = Node(None, left.freq + right.freq)
|
||||||
|
merged.left = left
|
||||||
|
merged.right = right
|
||||||
|
|
||||||
|
heapq.heappush(heap, merged)
|
||||||
|
|
||||||
|
return heap[0]
|
||||||
|
|
||||||
|
|
||||||
|
# Function to generate Huffman codes
|
||||||
|
def generate_codes(root, current_code="", codes={}):
|
||||||
|
if root is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if root.char is not None:
|
||||||
|
codes[root.char] = current_code
|
||||||
|
|
||||||
|
generate_codes(root.left, current_code + "0", codes)
|
||||||
|
generate_codes(root.right, current_code + "1", codes)
|
||||||
|
return codes
|
||||||
|
|
||||||
|
|
||||||
|
# Main program
|
||||||
|
text = input("Enter text to encode: ")
|
||||||
|
|
||||||
|
# Step 1: Calculate frequency of each character
|
||||||
|
freq = {}
|
||||||
|
for ch in text:
|
||||||
|
freq[ch] = freq.get(ch, 0) + 1
|
||||||
|
|
||||||
|
# Step 2: Build Huffman Tree using greedy approach
|
||||||
|
root = build_huffman_tree(freq)
|
||||||
|
|
||||||
|
# Step 3: Generate Huffman Codes
|
||||||
|
codes = generate_codes(root)
|
||||||
|
|
||||||
|
# Step 4: Encode the text
|
||||||
|
encoded_text = "".join(codes[ch] for ch in text)
|
||||||
|
|
||||||
|
# Step 5: Display results
|
||||||
|
print("\nCharacter | Frequency | Huffman Code")
|
||||||
|
print("------------------------------------")
|
||||||
|
for ch in freq:
|
||||||
|
print(f" {ch!r} | {freq[ch]} | {codes[ch]}")
|
||||||
|
|
||||||
|
print("\nEncoded Text:", encoded_text)
|
||||||
|
|
||||||
|
# SAMPLE OUTPUT
|
||||||
|
"""
|
||||||
|
Enter text to encode: lord kska git
|
||||||
|
|
||||||
|
Character | Frequency | Huffman Code
|
||||||
|
------------------------------------
|
||||||
|
'l' | 1 | 1100
|
||||||
|
'o' | 1 | 1101
|
||||||
|
'r' | 1 | 001
|
||||||
|
'd' | 1 | 1010
|
||||||
|
' ' | 2 | 011
|
||||||
|
'k' | 2 | 100
|
||||||
|
's' | 1 | 000
|
||||||
|
'a' | 1 | 010
|
||||||
|
'g' | 1 | 1011
|
||||||
|
'i' | 1 | 1111
|
||||||
|
't' | 1 | 1110
|
||||||
|
|
||||||
|
Encoded Text: 110011010011010011100000100010011101111111110
|
||||||
|
"""
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Code-A5 (N-Queen)
|
||||||
|
|
||||||
|
def print_board(board, n):
|
||||||
|
for i in range(n):
|
||||||
|
for j in range(n):
|
||||||
|
print(board[i][j], end=" ")
|
||||||
|
print()
|
||||||
|
print() # blank line between solutions
|
||||||
|
|
||||||
|
|
||||||
|
def is_safe(board, row, col, n):
|
||||||
|
# Check column
|
||||||
|
for i in range(row):
|
||||||
|
if board[i][col] == 1:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Check upper-left diagonal
|
||||||
|
i, j = row, col
|
||||||
|
while i >= 0 and j >= 0:
|
||||||
|
if board[i][j] == 1:
|
||||||
|
return False
|
||||||
|
i -= 1
|
||||||
|
j -= 1
|
||||||
|
|
||||||
|
# Check upper-right diagonal
|
||||||
|
i, j = row, col
|
||||||
|
while i >= 0 and j < n:
|
||||||
|
if board[i][j] == 1:
|
||||||
|
return False
|
||||||
|
i -= 1
|
||||||
|
j += 1
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def solve_n_queens(board, row, n):
|
||||||
|
if row == n:
|
||||||
|
print_board(board, n)
|
||||||
|
return True
|
||||||
|
|
||||||
|
res = False
|
||||||
|
for col in range(n):
|
||||||
|
if is_safe(board, row, col, n):
|
||||||
|
board[row][col] = 1
|
||||||
|
res = solve_n_queens(board, row + 1, n) or res
|
||||||
|
board[row][col] = 0 # backtrack
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
# Main program
|
||||||
|
n = int(input("Enter number of queens: "))
|
||||||
|
board = [[0 for _ in range(n)] for _ in range(n)]
|
||||||
|
|
||||||
|
print(f"\nSolutions for {n}-Queens Problem:\n")
|
||||||
|
if not solve_n_queens(board, 0, n):
|
||||||
|
print("No solution exists!")
|
||||||
|
|
||||||
|
# SAMPLE OUTPUT
|
||||||
|
"""
|
||||||
|
Enter number of queens: 4
|
||||||
|
|
||||||
|
Solutions for 4-Queens Problem:
|
||||||
|
|
||||||
|
0 1 0 0
|
||||||
|
0 0 0 1
|
||||||
|
1 0 0 0
|
||||||
|
0 0 1 0
|
||||||
|
|
||||||
|
0 0 1 0
|
||||||
|
1 0 0 0
|
||||||
|
0 0 0 1
|
||||||
|
0 1 0 0
|
||||||
|
"""
|
||||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -23,6 +23,10 @@ This repository contains valuable resources for the Design and Analysis of Algor
|
|||||||
4. [Code-A4 - 0/1 Knapsack](Codes/Code_A4.java)
|
4. [Code-A4 - 0/1 Knapsack](Codes/Code_A4.java)
|
||||||
5. [Code-A5 - N-Queen Problem](Codes/Code-A5.py)
|
5. [Code-A5 - N-Queen Problem](Codes/Code-A5.py)
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> C++ versions of all codes are available in the [./Codes/C++](./Codes/C++) directory.
|
||||||
|
> Python version of some codes are available in [./Codes/Python](./Codes/Python) directory.
|
||||||
|
|
||||||
### Practical
|
### Practical
|
||||||
|
|
||||||
1. [Practical-1](Practical/Practical-1)
|
1. [Practical-1](Practical/Practical-1)
|
||||||
@@ -37,6 +41,7 @@ This repository contains valuable resources for the Design and Analysis of Algor
|
|||||||
- [END-SEM](Question%20Papers/END-SEM)
|
- [END-SEM](Question%20Papers/END-SEM)
|
||||||
|
|
||||||
### [IN-SEM PYQ Answers](Notes/IN-SEM%20PYQ%20Answers)
|
### [IN-SEM PYQ Answers](Notes/IN-SEM%20PYQ%20Answers)
|
||||||
|
### [END-SEM PYQ Answers](Notes/END-SEM%20PYQ%20Answers)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user