algorithm and problems
algorithm and problems
factorial number:
2. fibonacci number.
class fibonacci {
public static void main(String[] args) {
ob.bubbleSort(a);
int n = a.length;
5.palindrome in string .
class palindrome{
public static void main(String args[]){
String s = "ARORA";
String rev = "";
for(int i=s.length()-1;i>=0;i--){
rev = rev+s.charAt(i);
}
if(s.toLowerCase().equals(rev.toLowerCase())){
System.out.println(s + " is a palindrome");
}
else{
System.out.println(s + "is not a palindrome");
}
}
}
6.binaer search
class BinarySearch {
// Binary Search Function (Iterative)
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
import java.util.ArrayList;
import java.util.List;
// Constructor
public Graph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}
// Detect cycle
public boolean hasCycle() {
boolean[] visited = new boolean[vertices];
boolean[] recStack = new boolean[vertices];
// DFS helper
private boolean dfs(int node, boolean[] visited, boolean[] recStack) {
if (recStack[node]) return true;
if (visited[node]) return false;
visited[node] = true;
recStack[node] = true;
recStack[node] = false;
return false;
}
}
if (graph.hasCycle()) {
System.out.println("Cycle detected.");
} else {
System.out.println("No cycle detected.");
}
}
}
import java.util.ArrayList;
import java.util.List;
// Constructor
public Graph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}
// Perform DFS
public void dfs(int start) {
boolean[] visited = new boolean[vertices];
System.out.println("Depth-First Search starting from vertex " + start +
":");
dfsUtil(start, visited);
}
Node(int value) {
this.value = value;
left = null;
right = null;
}
}
// Constructor
public BinaryTree() {
root = null;
}
// Insert nodes
tree.insert(50);
tree.insert(30);
tree.insert(70);
tree.insert(20);
tree.insert(40);
tree.insert(60);
tree.insert(80);
// Constructor
public Queue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
// Enqueue operation
public void enqueue(int value) {
stack1.push(value);
}
// Dequeue operation
public int dequeue() {
if (stack2.isEmpty()) {
if (stack1.isEmpty()) {
throw new RuntimeException("Queue is empty");
}
// Transfer all elements from stack1 to stack2
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
// Enqueue elements
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
// Dequeue and display elements
System.out.println("Dequeued: " + queue.dequeue()); // 1
System.out.println("Peek: " + queue.peek()); // 2
System.out.println("Dequeued: " + queue.dequeue()); // 2
___________________________________________________________________________________
class Singleton {
// Volatile keyword ensures visibility of changes to variables across threads
private static volatile Singleton instance;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;
// Shared buffer
private static final int BUFFER_SIZE = 5;
private static final Queue<Integer> buffer = new LinkedList<>();
// Semaphores
private static final Semaphore empty = new Semaphore(BUFFER_SIZE); // Tracks
empty slots
private static final Semaphore full = new Semaphore(0); // Tracks
filled slots
private static final Semaphore mutex = new Semaphore(1); // Mutual
exclusion
// Start threads
producerThread.start();
consumerThread.start();
import java.util.concurrent.Semaphore;
// Semaphores
private static final Semaphore mutex = new Semaphore(1); // For reader count
access
private static final Semaphore rwMutex = new Semaphore(1); // For resource
access
private static int readerCount = 0; // Tracks the number of readers
// Start threads
reader1.start();
reader2.start();
writer1.start();
writer2.start();
}
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;
// Producer thread
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
queue.enqueue(i);
Thread.sleep((int) (Math.random() * 500)); // Simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Consumer thread
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
queue.dequeue();
Thread.sleep((int) (Math.random() * 500)); // Simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
}
}
import java.util.concurrent.Semaphore;
// Number of philosophers
private static final int NUM_PHILOSOPHERS = 5;
@Override
public void run() {
try {
while (true) {
think();
pickUpForks();
eat();
putDownForks();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
if (count == 0) {
// All threads have reached the barrier
if (barrierAction != null) {
barrierAction.run(); // Execute the optional barrier action
}
// Reset the barrier for reuse
count = parties;
condition.signalAll(); // Wake up all waiting threads
} else {
// Wait for other threads to reach the barrier
while (count > 0) {
condition.await();
}
}
} finally {
lock.unlock();
}
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.ForkJoinPool;
@Override
protected void compute() {
if (left < right) {
int mid = left + (right - left) / 2;
private void merge(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int i = 0, j = 0, k = left;
parallelMergeSort(array);
System.out.println("\nSorted array:");
printArray(array);
}
19. Write a program to simulate a bank transaction system with multiple threads.
class BankAccount {
private int balance;
// Final balance
System.out.println("Final balance: $" + account.getBalance());
}
}
import java.util.concurrent.*;
// Evict an item from the cache (simple approach: remove first item)
private void evictCache() {
// For simplicity, we just remove one entry. A better strategy could be an
LRU (Least Recently Used) eviction policy.
for (K key : cache.keySet()) {
cache.remove(key);
break; // Evict only one element for this simple example
}
}
thread1.start();
thread2.start();
thread3.start();
_________________________________________________________________________________
1. Implement a Trie data structure with insert, search, and delete operations.
class Trie {
// TrieNode definition
static class TrieNode {
TrieNode[] children = new TrieNode[26]; // Array for 26 lowercase letters
boolean isEndOfWord = false; // Flag to mark the end of a word
}
if (depth == word.length()) {
if (!node.isEndOfWord) {
return false; // Word not found
}
node.isEndOfWord = false; // Unmark the end of the word
return isEmpty(node); // Check if node has no children
}
// Insert words
trie.insert("hello");
trie.insert("world");
trie.insert("help");
trie.insert("heap");
// Delete words
System.out.println(trie.delete("heap")); // true
System.out.println(trie.search("heap")); // false
System.out.println(trie.search("help")); // true
}
}
------------------------------------------------------------------------------
// Handle patterns with '*' at the start (can match empty text)
for (int i = 1; i <= m; i++) {
if (pattern.charAt(i - 1) == '*') {
dp[i][0] = dp[i - 1][0]; // '*' can represent empty sequence
}
}
// Fill DP table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (pattern.charAt(i - 1) == text.charAt(j - 1) || pattern.charAt(i
- 1) == '?') {
dp[i][j] = dp[i - 1][j - 1]; // Match character or '?'
} else if (pattern.charAt(i - 1) == '*') {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; // '*' matches empty
or any char
}
}
}
return dp[m][n];
}
________________________________________________________________________
file handling
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferdReader;
import java.io.IOException;
class SharedResource {
private int data = 0; // Shared variable
// Writer Method
public synchronized void write(int value) {
System.out.println(Thread.currentThread().getName() + " is Writing: " +
value);
data = value;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " finished
Writing.");
}
// Reader Method
public synchronized void read() {
System.out.println(Thread.currentThread().getName() + " is Reading: " +
data);
try { Thread.sleep(500); } catch (InterruptedException e) {}
}
}
// Main Class
public class ReaderWriterRunnable {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
reader1.start();
reader2.start();
writer.start();
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
System.out.println("Produced: " + i);
queue.put(i); // Put item in the queue
Thread.sleep(1000); // Simulate time-consuming task
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
@Override
public void run() {
while (true) {
try {
Integer item = queue.take(); // Take item from queue
System.out.println("Consumed: " + item);
Thread.sleep(1500); // Simulate processing time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
producerThread.start();
consumerThread.start();
}
}
-----------------------------------------
bank details
import java.util.Scanner;
class BankAcc{
private String name;
private double accno;
private double balance;
case 2:
System.out.println("enter amount you withdraw:");
double withdrawAmount = sc.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.display();
break;
case 4:
System.out.println("exit.. Thank u");
break;
default:
System.out.println(" invalid choice");
}
}
while(choice != 4);
sc.close();
}
}