Compare commits

...

5 Commits

5 changed files with 454 additions and 0 deletions
+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];
// }
// }
+4
View File
@@ -18,6 +18,10 @@ This repository contains valuable resources for the Design and Analysis of Algor
### Codes
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)
### Practical