Compare commits

..

31 Commits

Author SHA1 Message Date
notkshitij ff72fdf47c Upload end-sem pyq for DAA, november-december 2025. Provided by Ayush Kalaskar. 2026-03-22 02:06:43 +05:30
notkshitij 028eb10661 Added may-june 2025 end-sem pyq (daa) 2025-12-02 13:52:29 +05:30
notkshitij e8327327d4 Title. 2025-11-28 00:20:37 +05:30
notkshitij d53169d89f Added link to end-sem pyq answers. 2025-11-28 00:14:01 +05:30
notkshitij ecd6ecae64 Added end-sem pyq answers for unit 6. Collaborative work by Ayush Kalaskar and Himanshu Patil. 2025-11-28 00:13:34 +05:30
notkshitij e051c585bc Added end-sem pyq answers for unit 5. Collaborative work by Ayush Kalaskar and Himanshu Patil. 2025-11-27 22:58:15 +05:30
notkshitij f24c40a32e Minor formatting changes to end-sem unit 3 pyq answers. 2025-11-27 22:05:04 +05:30
notkshitij 158b164fa4 Added end-sem pyq answers for unit 4. Collaborative work by Ayush Kalaskar and Himanshu Patil. 2025-11-27 21:48:23 +05:30
notkshitij 5c39b18d49 Added end-sem pyq answers for unit 3. Collaborative work by Ayush Kalaskar and Himanshu Patil. 2025-11-27 20:01:28 +05:30
notkshitij 21eac5a235 Added counter for iterative+recursive function and fixed logic for iterative fibonacci in code a1 (c++) 2025-11-06 22:11:00 +05:30
notkshitij ab568b290b Moved optimized fibonacci code to python directory in codes. 2025-11-06 15:30:43 +05:30
notkshitij 1cd69b32e7 Added basic fibonacci code in python (code-a1) 2025-11-06 15:29:43 +05:30
notkshitij fbaf0330da Renamed code-a1. Appended optmized. 2025-11-06 15:28:10 +05:30
notkshitij c27d224e93 Renamed huffman code to huffman coding in C++ directory. 2025-11-05 20:15:40 +05:30
notkshitij bf4f5beb17 Added link to python version of some codes. 2025-11-05 20:10:00 +05:30
notkshitij a39a53ea90 Added python version of n-queen problem, from git repo provided by Prathamesh Patil. 2025-11-05 20:09:23 +05:30
notkshitij 2d45b17899 Added python version of Huffman coding, from git repo provided by Prathamesh Patil. 2025-11-05 20:08:52 +05:30
notkshitij fa5f3f94a4 Added link to C++ codes. 2025-11-05 19:14:27 +05:30
notkshitij 13bebfc613 Added tested code for A5 (n queen) in C++ with sample output, provided by Salvi sir. 2025-11-05 19:13:33 +05:30
notkshitij 5fdb6776e8 Added tested code for A4 (0-1 knapsack) in C++ with sample output, provided by Salvi sir. 2025-11-05 19:12:15 +05:30
notkshitij 871e4e9474 Added tested code for A3 (fractical knapsack) in C++ with sample output, provided by Salvi sir. 2025-11-05 19:11:48 +05:30
notkshitij 51ebf36804 Added sample output in fiboacci code. 2025-11-05 19:11:13 +05:30
notkshitij 493cfbe596 Added sample output in huffman code. 2025-11-05 19:05:15 +05:30
notkshitij 86ae1c2550 Added tested code for A2 (huffman) in C++, provided by Salvi sir. 2025-11-05 19:03:08 +05:30
notkshitij 6dc71e1d77 Added tested code for A1 (fibonacci) in C++, provided by Salvi sir. 2025-11-05 19:02:37 +05:30
notkshitij cf2b2c43a9 Added softcopies for all practical. 2025-10-12 15:30:10 +05:30
notkshitij 527e2d37fa Added links to all codes in readme. 2025-10-12 15:16:13 +05:30
notkshitij 77bf4d569d Added Vedang's huffman coding code. 2025-10-12 15:13:52 +05:30
notkshitij 16b452316e Added code for n-queen problem (practical-5). 2025-10-12 15:13:35 +05:30
notkshitij 4896f6782e Added Vedang's 0/1 Knapsack code. 2025-10-12 15:07:14 +05:30
notkshitij 5adfd0301a Added Vedang's fractional knapsack code. 2025-10-12 15:05:47 +05:30
25 changed files with 1099 additions and 24 deletions
+64
View File
@@ -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
*/
+102
View File
@@ -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
*/
+60
View File
@@ -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
*/
+86
View File
@@ -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
+39 -22
View File
@@ -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 # Iteration
def fibonacci_iteration(n):
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
for i in range(n): for i in range(n):
fib_series.append(a) fib_series.append(previous)
a, b = b, a + b previous, current = current, previous + current
iteration_counter += 1
return fib_series 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)")
+61
View File
@@ -0,0 +1,61 @@
# Practical-A5 (N-Queen)
"""
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
Problem Statement: Design n-Queens matrix having first Queen placed. Use backtracking to place remaining Queens to generate the final n-queens matrix.
Code from DesignAndAnalysisOfAlgorithms (SPPU - Final Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-be-comp-content/DesignAndAnalysisOfAlgorithms/
"""
# BEGINNING OF CODE
def placeQueens(i, cols, leftDiagonal, rightDiagonal, cur):
n = len(cols)
if i == n:
return True
for j in range(n):
if cols[j] or rightDiagonal[i + j] or leftDiagonal[i - j + n - 1]:
continue
cols[j] = 1
rightDiagonal[i + j] = 1
leftDiagonal[i - j + n - 1] = 1
cur.append(j)
if placeQueens(i + 1, cols, leftDiagonal, rightDiagonal, cur):
return True
cur.pop()
cols[j] = 0
rightDiagonal[i + j] = 0
leftDiagonal[i - j + n - 1] = 0
return False
def nQueen(n):
cols = [0] * n
leftDiagonal = [0] * (n * 2)
rightDiagonal = [0] * (n * 2)
cur = []
board = [['.' for _ in range(n)] for _ in range(n)]
if placeQueens(0, cols, leftDiagonal, rightDiagonal, cur):
for i in range(n):
board[i][cur[i]] = 'Q'
return board
else:
return None
def printBoard(board):
if board:
for row in board:
print(" ".join(row))
else:
print("No solution exists.")
n = int(input("Enter the number of queens:\t"))
board = nQueen(n)
printBoard(board)
# END OF CODE
+135
View File
@@ -0,0 +1,135 @@
import java.util.*;
public class Code_A2 {
private static HuffmanNode root;
private static Map<Character, String> huffmanCodes = new HashMap<>();
private static Map<Character, Integer> freqMap = new HashMap<>();
private static String inputText = "";
static class HuffmanNode implements Comparable<HuffmanNode> {
char ch;
int freq;
HuffmanNode left, right;
HuffmanNode(char ch, int freq) {
this.ch = ch;
this.freq = freq;
}
public int compareTo(HuffmanNode other) {
return this.freq - other.freq;
}
}
private static void generateCodes(HuffmanNode node, String code) {
if (node == null) return;
if (node.left == null && node.right == null)
huffmanCodes.put(node.ch, code);
generateCodes(node.left, code + "0");
generateCodes(node.right, code + "1");
}
private static void buildHuffmanTree() {
PriorityQueue<HuffmanNode> pq = new PriorityQueue<>();
for (Map.Entry<Character, Integer> e : freqMap.entrySet())
pq.add(new HuffmanNode(e.getKey(), e.getValue()));
while (pq.size() > 1) {
HuffmanNode left = pq.poll();
HuffmanNode right = pq.poll();
HuffmanNode parent = new HuffmanNode('-', left.freq + right.freq);
parent.left = left; parent.right = right;
pq.add(parent);
}
root = pq.peek();
huffmanCodes.clear();
generateCodes(root, "");
}
private static void displayCodes() {
if (huffmanCodes.isEmpty()) {
System.out.println("No Huffman codes generated yet!");
return;
}
System.out.println("\nCharacter\tFrequency\tHuffman Code");
for (Map.Entry<Character, String> entry : huffmanCodes.entrySet())
System.out.println(entry.getKey() + "\t\t" + freqMap.get(entry.getKey()) + "\t\t" + entry.getValue());
}
private static void encodeText() {
if (huffmanCodes.isEmpty()) {
System.out.println("Please build Huffman Tree first!");
return;
}
StringBuilder encoded = new StringBuilder();
for (char c : inputText.toCharArray())
encoded.append(huffmanCodes.get(c));
System.out.println("\nEncoded Text: " + encoded.toString());
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("\n=== Huffman Encoding Menu ===");
System.out.println("1. Enter input string (auto frequency)");
System.out.println("2. Enter characters with frequencies manually");
System.out.println("3. Build Huffman Tree & display codes");
System.out.println("4. Encode the text");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
System.out.print("Enter the text: ");
inputText = sc.nextLine();
freqMap.clear();
for (char c : inputText.toCharArray())
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
break;
case 2:
freqMap.clear();
inputText = "";
System.out.print("Enter number of characters: ");
int n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++) {
System.out.print("Character " + (i + 1) + ": ");
char c = sc.nextLine().charAt(0);
System.out.print("Frequency of " + c + ": ");
int f = sc.nextInt();
sc.nextLine();
freqMap.put(c, f);
inputText += String.valueOf(c).repeat(f);
}
break;
case 3:
if (freqMap.isEmpty()) {
System.out.println("Please enter input first!");
} else {
buildHuffmanTree();
displayCodes();
}
break;
case 4:
if (inputText.isEmpty())
System.out.println("Enter input text first!");
else
encodeText();
break;
case 5:
System.out.println("Exiting program. Goodbye!");
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}
+83
View File
@@ -0,0 +1,83 @@
import java.util.*;
public class Code_A3 { // Main public class must match filename
static class Item {
int value, weight;
double ratio;
Item(int value, int weight) {
this.value = value;
this.weight = weight;
this.ratio = (double) value / weight;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Item> items = new ArrayList<>();
int choice;
while (true) {
System.out.println("\n=== Fractional Knapsack Menu ===");
System.out.println("1. Enter items");
System.out.println("2. Solve fractional knapsack");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
items.clear();
System.out.print("Enter number of items: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Item " + (i + 1) + " value: ");
int v = sc.nextInt();
System.out.print("Item " + (i + 1) + " weight: ");
int w = sc.nextInt();
items.add(new Item(v, w));
}
break;
case 2:
if (items.isEmpty()) {
System.out.println("Please enter items first!");
break;
}
System.out.print("Enter knapsack capacity: ");
int capacity = sc.nextInt();
// Sort by value-to-weight ratio
items.sort((a, b) -> Double.compare(b.ratio, a.ratio));
double totalValue = 0;
int remaining = capacity;
System.out.println("\nItems taken (value/weight fraction):");
for (Item item : items) {
if (remaining == 0) break;
if (item.weight <= remaining) {
System.out.println(item.value + "/" + item.weight + " -> Full");
totalValue += item.value;
remaining -= item.weight;
} else {
double fraction = (double) remaining / item.weight;
System.out.println(item.value + "/" + item.weight + " -> " + (fraction * 100) + "%");
totalValue += item.value * fraction;
remaining = 0;
}
}
System.out.printf("Maximum total value in knapsack: %.2f\n", totalValue);
break;
case 3:
System.out.println("Exiting program. Goodbye!");
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}
+171
View File
@@ -0,0 +1,171 @@
// THIS CODE SHOWS DP-TABLE
import java.util.*;
public class Code_A4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] values = null;
int[] weights = null;
int n = 0;
int choice;
while (true) {
System.out.println("\n=== 0-1 Knapsack Menu ===");
System.out.println("1. Enter items (values & weights)");
System.out.println("2. Solve 0-1 Knapsack");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter number of items: ");
n = sc.nextInt();
values = new int[n];
weights = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Item " + (i + 1) + " value: ");
values[i] = sc.nextInt();
System.out.print("Item " + (i + 1) + " weight: ");
weights[i] = sc.nextInt();
}
break;
case 2:
if (values == null || weights == null || n == 0) {
System.out.println("Please enter items first!");
break;
}
System.out.print("Enter knapsack capacity: ");
int capacity = sc.nextInt();
int[][] dp = buildKnapsackDP(values, weights, n, capacity);
System.out.println("\nDP Table:");
printDPTable(dp, n, capacity);
System.out.println("Maximum value that can be put in knapsack: " + dp[n][capacity]);
break;
case 3:
System.out.println("Exiting program. Goodbye!");
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
// Build DP table
private static int[][] buildKnapsackDP(int[] val, int[] wt, int n, int W) {
int[][] dp = new int[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (wt[i - 1] <= w)
dp[i][w] = Math.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;
}
// Print DP table
private static void printDPTable(int[][] dp, int n, int W) {
System.out.print(" ");
for (int w = 0; w <= W; w++)
System.out.printf("%4d", w);
System.out.println();
for (int i = 0; i <= n; i++) {
System.out.printf("%2d ", i);
for (int w = 0; w <= W; w++)
System.out.printf("%4d", dp[i][w]);
System.out.println();
}
}
}
// THIS CODE DOESN'T SHOW DP-TABLE
// import java.util.*;
// public class ZeroOneKnapsack {
// public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
// int[] values = null;
// int[] weights = null;
// int n = 0;
// int choice;
// while (true) {
// System.out.println("\n=== 0-1 Knapsack Menu ===");
// System.out.println("1. Enter items (values & weights)");
// System.out.println("2. Solve 0-1 Knapsack");
// System.out.println("3. Exit");
// System.out.print("Enter your choice: ");
// choice = sc.nextInt();
// switch (choice) {
// case 1:
// System.out.print("Enter number of items: ");
// n = sc.nextInt();
// values = new int[n];
// weights = new int[n];
// for (int i = 0; i < n; i++) {
// System.out.print("Item " + (i + 1) + " value: ");
// values[i] = sc.nextInt();
// System.out.print("Item " + (i + 1) + " weight: ");
// weights[i] = sc.nextInt();
// }
// break;
// case 2:
// if (values == null || weights == null || n == 0) {
// System.out.println("Please enter items first!");
// break;
// }
// System.out.print("Enter knapsack capacity: ");
// int capacity = sc.nextInt();
// int maxValue = knapsackDP(values, weights, n, capacity);
// System.out.println("Maximum value that can be put in knapsack: " + maxValue);
// break;
// case 3:
// System.out.println("Exiting program. Goodbye!");
// sc.close();
// return;
// default:
// System.out.println("Invalid choice!");
// }
// }
// }
// // DP solution for 0-1 Knapsack
// private static int knapsackDP(int[] val, int[] wt, int n, int W) {
// int[][] dp = new int[n + 1][W + 1];
// for (int i = 0; i <= n; i++) {
// for (int w = 0; w <= W; w++) {
// if (i == 0 || w == 0)
// dp[i][w] = 0;
// else if (wt[i - 1] <= w)
// dp[i][w] = Math.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];
// }
// }
+46
View File
@@ -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)
+95
View File
@@ -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
"""
+74
View File
@@ -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
"""
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+9
View File
@@ -18,6 +18,14 @@ This repository contains valuable resources for the Design and Analysis of Algor
### Codes ### Codes
1. [Code-A1 - Fibonacci Series](Codes/Code-A1.py) 1. [Code-A1 - Fibonacci Series](Codes/Code-A1.py)
2. [Code-A2 - Huffman Coding](Codes/Code_A2.java)
3. [Code-A3 - Fractical Knapsack](Codes/Code_A3.java)
4. [Code-A4 - 0/1 Knapsack](Codes/Code_A4.java)
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
@@ -33,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)
--- ---