Lab6 daa
Lab6 daa
*;
class Item {
int value, weight;
Item(int value, int weight) {
this.value = value;
this.weight = weight;
}
}
if (item.weight <=
capacity) {
totalValue +=
item.value;
capacity -=
item.weight;
} else {
// Take fraction of the
item
totalValue +=
(double)item.value * capacity /
item.weight;
capacity = 0;
}
}
return totalValue;
}
System.out.print("Enter
knapsack capacity: ");
int capacity = sc.nextInt();
double maxValue =
getMaxValue(capacity, items);
System.out.printf("Maximum
value in knapsack = %.2f\n",
maxValue);
}
}
....
import java.util.*;
class HuffmanNode {
char ch;
int freq;
HuffmanNode left, right;
static void
generateCodes(HuffmanNode
root, String code,
Map<Character, String>
huffmanCodes) {
if (root == null) return;
if (root.left == null &&
root.right == null) {
huffmanCodes.put(root.ch,
code);
}
generateCodes(root.left,
code + "0", huffmanCodes);
generateCodes(root.right,
code + "1", huffmanCodes);
}
// Frequency map
Map<Character, Integer>
freqMap = new HashMap<>();
for (char ch :
input.toCharArray()) {
freqMap.put(ch,
freqMap.getOrDefault(ch, 0) + 1);
}
HuffmanNode root =
pq.poll();
Map<Character, String>
huffmanCodes
= new HashMap<>();
generateCodes(root, "",
huffmanCodes);
// Encode input
StringBuilder encoded =
new StringBuilder();
for (char ch :
input.toCharArray()) {
encoded.append(huffmanCodes.
get(ch));
}
System.out.println("Encoded
string: " + encoded.toString());
}
}