Task 6 Java Programming
Task 6 Java Programming
1. Aim:
2. Algorithm:
1. Create an LRU Cache class using LinkedHashMap (or Doubly Linked List
with HashMap for manual implementation).
2. Define:
o Capacity: Maximum number of elements the cache can hold.
o Put(K, V): Inserts a key-value pair and removes the least recently used
item if full.
o Get(K): Fetches the value for a key and marks it as recently used.
3. Use LinkedHashMap with accessOrder = true to maintain access order.
4. Override removeEldestEntry() to automatically remove the least recently
used element.
3. Program:
import java.util.*;
class LRUCache {
class Node {
int key, value;
Node prev, next;
Node(int k, int v)
{
key = k; value = v; }
}
private final int capacity;
private final Map<Integer, Node> cache;
private final Node head, tail;
Output:
1
-1
-1
3
4
Explanation:
1. Aim:
To write a Java program that sorts an array of elements based on their descending weights, where
weight is defined as a function of divisibility by a given number k. Elements with higher
divisibility (higher weight) are sorted first, and elements with the same weight are sorted in
descending order.
2. Algorithm:
1. Input the array and the integer k (used to determine the weight of each element).
2. Calculate the weight of each element:
o Weight is determined by the number of times the element is divisible by k.
3. Sort the array:
o Elements with a higher weight appear first.
o If two elements have the same weight, they are sorted in descending order.
4. Print the sorted array.
Program:
import java.util.*;
class DescendingWeights {
int k;
WeightComparator(int k) {
this.k = k;
@Override
if (weightA != weightB)
int count = 0;
count++;
num /= k;
return count;
int n = scanner.nextInt();
arr[i] = scanner.nextInt();
// Input: k value
int k = scanner.nextInt();
list.add(num);
}
Sample input
Enter the number of elements: 6
Sample output:
1. 25 (Weight 2)
2. 30 (Weight 1)
3. 20 (Weight 1)
4. 15 (Weight 1)
5. 12 (Weight 0)
6. 8 (Weight 0)
Output:
This Java program solves the problem of distributing apples among students evenly, ensuring
fairness. If apples cannot be evenly divided, the program will indicate the remainder.
1. Aim
2. Algorithm
Program
import java.util.Scanner;
if (students == 0) {
} else {
if (remainingApples > 0) {
scanner.close();
Input:
Input:
Output:
Input:
Output: