About
package exam; import java.util.Random;
public class MatrixMultiplication { public static final int ROWS_A = 3; public static final int COLS_A = 4; public static final int ROWS_B = 4; public static final int COLS_B = 2;
public MatrixMultiplication() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
int[][] matrixA = generateRandomMatrix(ROWS_A, COLS_A);
int[][] matrixB = generateRandomMatrix(ROWS_B, COLS_B);
int[][] resultMatrix = new int[ROWS_A][COLS_B];
Thread[] threads = new Thread[ROWS_A];
for (int i = 0; i < ROWS_A; i++) {
threads[i] = new Thread(new MatrixMultiplicationWorker(i, matrixA, matrixB, resultMatrix));
threads[i].start();
}
for (int i = 0; i < ROWS_A; i++) {
threads[i].join();
}
printMatrix(matrixA);
System.out.println("*");
printMatrix(matrixB);
System.out.println("=");
printMatrix(resultMatrix);
}
public static int[][] generateRandomMatrix(int rows, int cols) {
int[][] matrix = new int[rows][cols];
Random random = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = random.nextInt(10);
}
}
return matrix;
}
public synchronized static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
package exam;
public class MatrixMultiplicationWorker implements Runnable {
private int row;
private int[][] matrixA;
private int[][] matrixB;
private int[][] resultMatrix;
public MatrixMultiplicationWorker(int row, int[][] matrixA, int[][] matrixB, int[][] resultMatrix) {
this.row = row;
this.matrixA = matrixA;
this.matrixB = matrixB;
this.resultMatrix = resultMatrix;
}
public void run() {
for (int j = 0; j < MatrixMultiplication.COLS_B; j++) {
int sum = 0;
for (int k = 0; k < MatrixMultiplication.ROWS_B; k++) {
sum += matrixA[row][k] * matrixB[k][j];
}
synchronized (resultMatrix) {
resultMatrix[row][j] = sum;
}
}
// TODO Auto-generated constructor stub
}
}
object EvenOddSeparator { def main(args: Array[String]): Unit = { val inputNumbers = scala.io.StdIn.readLine("Enter the numbers separated by spaces: ") val numbers = inputNumbers.split(" ").map(_.toInt) val separatedNumbers = separateEvenOdd(numbers)
println("Separated Numbers:")
separatedNumbers.foreach(println)
}
def separateEvenOdd(numbers: Array[Int]): Array[Int] = { val evenNumbers = numbers.filter(_ % 2 == 0) val oddNumbers = numbers.filter(_ % 2 != 0) evenNumbers ++ oddNumbers } }
concurrency using------------------------------------------------------------------------------------------ import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
int[][] arr = new int[rows][cols];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = scanner.nextInt();
}
}
DifferenceThread differenceThread = new DifferenceThread(arr);
DiagonalThread diagonalThread = new DiagonalThread(arr);
differenceThread.start();
diagonalThread.start();
try {
differenceThread.join();
diagonalThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The difference of the array is: " + differenceThread.getDifference());
System.out.println("The array is a diagonal matrix: " + diagonalThread.isDiagonalMatrix());
}
} class DifferenceThread extends Thread { private int[][] arr; private int difference;
public DifferenceThread(int[][] arr) {
this.arr = arr;
}
public void run() {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int[] row : arr) {
for (int num : row) {
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
}
}
difference = max - min;
}
public int getDifference() {
return difference;
}
} class DiagonalThread extends Thread { private int[][] arr; private boolean isDiagonalMatrix = true;
public DiagonalThread(int[][] arr) {
this.arr = arr;
}
public void run() {
if (arr.length != arr[0].length) {
isDiagonalMatrix = false;
} else {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
if (i != j && arr[i][j] != 0) {
isDiagonalMatrix = false;
break;
}
}
}
}
}
public boolean isDiagonalMatrix() {
return isDiagonalMatrix;
}
}
fork and join------------------------------------------------------------------------------------------------------------------------ import java.util.Scanner; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask;
public class Main { public static void main(String[] args) throws InterruptedException { Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numRows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int numCols = scanner.nextInt();
int[][] arr = new int[numRows][numCols];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
arr[i][j] = scanner.nextInt();
}
}
ForkJoinPool pool = new ForkJoinPool();
DifferenceTask diffTask = new DifferenceTask(arr, 0, numRows, 0, numCols);
DiagonalTask diagTask = new DiagonalTask(arr, 0, numRows, 0, numCols);
pool.execute(diffTask);
pool.execute(diagTask);
pool.shutdown();
pool.awaitTermination(1, java.util.concurrent.TimeUnit.MINUTES);
System.out.println("The difference of the array is: " + diffTask.join());
System.out.println("Is the array a diagonal matrix? " + diagTask.join());
}
}
class DifferenceTask extends RecursiveTask<Integer> { private int[][] arr; private int startRow; private int endRow; private int startCol; private int endCol;
public DifferenceTask(int[][] arr, int startRow, int endRow, int startCol, int endCol) {
this.arr = arr;
this.startRow = startRow;
this.endRow = endRow;
this.startCol = startCol;
this.endCol = endCol;
}
protected Integer compute() {
if (endRow - startRow == 1 && endCol - startCol == 1) {
return 0;
}
int midRow = (startRow + endRow) / 2;
int midCol = (startCol + endCol) / 2;
DifferenceTask task1 = new DifferenceTask(arr, startRow, midRow, startCol, midCol);
DifferenceTask task2 = new DifferenceTask(arr, startRow, midRow, midCol, endCol);
DifferenceTask task3 = new DifferenceTask(arr, midRow, endRow, startCol, midCol);
DifferenceTask task4 = new DifferenceTask(arr, midRow, endRow, midCol, endCol);
task1.fork();
task2.fork();
task3.fork();
task4.fork();
int result1 = task1.join();
int result2 = task2.join();
int result3 = task3.join();
int result4 = task4.join();
return Math.abs(result1 - result2 - result3 + result4);
}
}
class DiagonalTask extends RecursiveTask<Boolean> { private int[][] arr; private int startRow; private int endRow; private int startCol; private int endCol;
public DiagonalTask(int[][] arr, int startRow, int endRow, int startCol, int endCol) {
this.arr = arr;
this.startRow = startRow;
this.endRow = endRow;
this.startCol = startCol;
this.endCol = endCol;
}
protected Boolean compute() {
if (endRow - startRow != endCol - startCol) {
return false;
}
for (int i = startRow; i < endRow; i++) {
for (int j = startCol; j < endCol; j++) {
if (i != j && arr[i][j] != 0) {
return false;
}
}
}
return true;
}
}
lock and unlock----------------------------------------------------------------------------------------------------------------------- import java.util.Scanner; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import java.util.concurrent.locks.ReentrantLock;
public class Main { public static void main(String[] args) throws InterruptedException { Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numRows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int numCols = scanner.nextInt();
int[][] arr = new int[numRows][numCols];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
arr[i][j] = scanner.nextInt();
}
}
ReentrantLock lock = new ReentrantLock();
ForkJoinPool pool = new ForkJoinPool();
DifferenceTask diffTask = new DifferenceTask(arr, 0, numRows, 0, numCols, lock);
DiagonalTask diagTask = new DiagonalTask(arr, 0, numRows, 0, numCols, lock);
pool.execute(diffTask);
pool.execute(diagTask);
pool.shutdown();
pool.awaitTermination(1, java.util.concurrent.TimeUnit.MINUTES);
System.out.println("The difference of the array is: " + diffTask.join());
System.out.println("Is the array a diagonal matrix? " + diagTask.join());
}
}
class DifferenceTask extends RecursiveTask<Integer> { private int[][] arr; private int startRow; private int endRow; private int startCol; private int endCol; private ReentrantLock lock;
public DifferenceTask(int[][] arr, int startRow, int endRow, int startCol, int endCol, ReentrantLock lock) {
this.arr = arr;
this.startRow = startRow;
this.endRow = endRow;
this.startCol = startCol;
this.endCol = endCol;
this.lock = lock;
}
protected Integer compute() {
if (endRow - startRow == 1 && endCol - startCol == 1) {
return 0;
}
int midRow = (startRow + endRow) / 2;
int midCol = (startCol + endCol) / 2;
DifferenceTask task1 = new DifferenceTask(arr, startRow, midRow, startCol, midCol, lock);
DifferenceTask task2 = new DifferenceTask(arr, startRow, midRow, midCol, endCol, lock);
DifferenceTask task3 = new DifferenceTask(arr, midRow, endRow, startCol, midCol, lock);
DifferenceTask task4 = new DifferenceTask(arr, midRow, endRow, midCol, endCol, lock);
task1.fork();
task2.fork();
task3.fork();
task4.fork();
int result1 = task1.join();
int result2 = task2.join();
int result3 = task3.join();
int result4 = task4.join();
lock.lock();
try {
return Math.abs(result1 - result2 - result3 + result4);
} finally {
lock.unlock();
}
}
}
class DiagonalTask extends RecursiveTask<Boolean> { private int[][] arr; private int startRow; private int endRow; private int startCol; private int endCol; private ReentrantLock lock;
public DiagonalTask(int[][] arr, int startRow, int endRow, int startCol, int endCol, ReentrantLock lock) {
this.arr = arr;
this.startRow = startRow;
this.endRow = endRow;
this.startCol = startCol;
this.endCol = endCol;
this.lock = lock;
}
protected Boolean compute() {
if (endRow - startRow != endCol - startCol) {
return false;
}
lock.lock();
try {
for (int i = startRow; i < endRow; i++) {
for (int j = startCol; j < endCol; j++) {
if (i != j && arr[i][j] != 0) {
return false;
}
}
}
return true;
} finally {
lock.unlock();
}
}
}
Account Sum using java Threads-----------------------------------------------------------------------------------------------
class Account { private int amount = 0;
public Account(int amount) {
this.amount = amount;
}
public synchronized void deposit(int value) {
this.amount += value;
System.out.println("Balance after deposit: " + this.amount);
}
public synchronized void withdraw(int value) {
this.amount -= value;
System.out.println("Balance after withdrawal: " + this.amount);
}
public synchronized int getAmount() {
return this.amount;
}
}
class Deposit extends Thread { private Account acc;
public Deposit(Account acc) {
this.acc = acc;
}
public void run() {
for (int i = 0; i < 10; i++) {
acc.deposit(10);
}
}
}
class Withdrawal extends Thread { private Account acc;
public Withdrawal(Account acc) {
this.acc = acc;
}
public void run() {
for (int i = 0; i < 10; i++) {
acc.withdraw(10);
}
}
}
public class Main { public static void main(String[] args) throws InterruptedException { Account acc = new Account(100); Deposit depo = new Deposit(acc); Withdrawal with = new Withdrawal(acc); depo.start(); with.start(); depo.join(); with.join(); System.out.println("Final Balance: " + acc.getAmount()); } }
using lists--------------------------------------------------------------------------------------------------------------------------------- Write a Java concurrency program to accept two lists of integers. Thread 1 should append both lists into a new list. Thread 2 should find the length of the two lists without using built-in functions, and the result should be printed by the main thread.
import java.util.ArrayList; import java.util.List;
class AppendThread extends Thread { private List<Integer> list1; private List<Integer> list2; private List<Integer> resultList;
public AppendThread(List<Integer> list1, List<Integer> list2) {
this.list1 = list1;
this.list2 = list2;
this.resultList = new ArrayList<>();
}
public List<Integer> getResultList() {
return resultList;
}
public void run() {
synchronized (resultList) {
resultList.addAll(list1);
resultList.addAll(list2);
}
}
}
class LengthThread extends Thread { private List<Integer> list1; private List<Integer> list2; private int length;
public LengthThread(List<Integer> list1, List<Integer> list2) {
this.list1 = list1;
this.list2 = list2;
this.length = 0;
}
public int getLength() {
return length;
}
public void run() {
synchronized (list1) {
length += list1.size();
}
synchronized (list2) {
length += list2.size();
}
}
}
public class Main { public static void main(String[] args) throws InterruptedException { List<Integer> list1 = new ArrayList<>(); list1.add(1); list1.add(2); list1.add(3);
List<Integer> list2 = new ArrayList<>();
list2.add(4);
list2.add(5);
list2.add(6);
AppendThread appendThread = new AppendThread(list1, list2);
LengthThread lengthThread = new LengthThread(list1, list2);
appendThread.start();
lengthThread.start();
appendThread.join();
lengthThread.join();
List<Integer> resultList = appendThread.getResultList();
int totalLength = lengthThread.getLength();
System.out.println("Combined List: " + resultList);
System.out.println("Total Length: " + totalLength);
}
}
scala higher order functions-------------------------------------------------------------------------------------------------------------------------- Problem 1: Write a function scaleList that multiplies each element of a list by a given factor.
Solution 1:
scala Copy code def scaleList(xs: List[Int], factor: Int): List[Int] = xs.map(_ * factor)
val list = List(1, 2, 3, 4, 5) println(scaleList(list, 3)) // Prints List(3, 6, 9, 12, 15) In this solution, map is a higher-order function that applies a given function (in this case, multiplication by factor) to each element of the list.
Problem 2: Write a function filterEven that filters out odd numbers from a list.
Solution 2:
scala Copy code def filterEven(xs: List[Int]): List[Int] = xs.filter(_ % 2 == 0)
val list = List(1, 2, 3, 4, 5) println(filterEven(list)) // Prints List(2, 4) In this solution, filter is a higher-order function that applies a given predicate (a function returning a boolean) to each element of the list and retains only those elements for which the predicate returns true.
Problem 3: Write a function compose that composes two functions (i.e., it creates a new function that, when called with an argument, applies the first function to the result of applying the second function to the argument).
Solution 3:
def composeA, B, C: A => C = { (x: A) => f(g(x)) }
val addTwo = (x: Int) => x + 2 val triple = (x: Int) => x * 3 val addTwoThenTriple = compose(triple, addTwo)
println(addTwoThenTriple(4)) // Prints 18 because (4+2)*3 = 18
Problem 1:---------------------------------------------------------------------------------------------------------------------------- Write a function partition that splits a list into two lists, one with all elements that satisfy a given predicate and one with all elements that do not. The function should not change the order of the elements.
Solution 1:
scala Copy code def partitionT: (List[T], List[T]) = { list.foldRight((ListT, ListT)) { (element, accum) => if (predicate(element)) (element :: accum._1, accum._2) else (accum._1, element :: accum._2) } }
val list = List(1, 2, 3, 4, 5, 6) val isEven = (n: Int) => n % 2 == 0 println(partition(list, isEven)) // Prints (List(6, 4, 2), List(5, 3, 1)) Here foldRight is used with a binary operator that builds up a pair of lists. The lists are built in reverse order, which is corrected by the folding direction of foldRight.
Problem 2: Write a function flatMap that works like a standard map function, but the mapping function produces a list of results for each element.
Solution 2:
scala Copy code def flatMapA, B: List[B] = { list.foldRight(ListB)((element, accum) => f(element) ::: accum) }
val list = List(1, 2, 3) val replicateThree = (n: Int) => List(n, n, n) println(flatMap(list, replicateThree)) // Prints List(1, 1, 1, 2, 2, 2, 3, 3, 3) In this solution, flatMap is implemented using foldRight, which accumulates the result of applying f to each element of the list. ::: is used to concatenate lists.
Problem 3: Write a function zipWith that combines two lists using a function. If one input list is short, excess elements of the longer list should be discarded.
Solution 3:
scala Copy code def zipWithA, B, C => C): List[C] = { (listA, listB) match { case (Nil, _) => Nil case (_, Nil) => Nil case (a :: tailA, b :: tailB) => f(a, b) :: zipWith(tailA, tailB, f) } }
val list1 = List(1, 2, 3) val list2 = List(4, 5, 6) val add = (x: Int, y: Int) => x + y println(zipWith(list1, list2, add)) // Prints List(5, 7, 9)