Compare commits
32 Commits
21ff2610f1
...
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
|
|||
|
cf2b2c43a9
|
|||
|
527e2d37fa
|
|||
|
77bf4d569d
|
|||
|
16b452316e
|
|||
|
4896f6782e
|
|||
|
5adfd0301a
|
|||
|
fed68211f0
|
@@ -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
+39
-22
@@ -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)")
|
||||||
|
|
||||||
|
|||||||
@@ -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-queen‘s 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
|
||||||
Executable
+135
@@ -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!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+83
@@ -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!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+171
@@ -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];
|
||||||
|
// }
|
||||||
|
// }
|
||||||
@@ -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.
Executable
BIN
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -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)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user