import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ConcurrentStuff {
public static void main(String[] args) {
System.out.println("begin");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
System.out.println("scheduling a task to run after 2 seconds");
// Schedule a task to run after a delay of 2 seconds
executor.schedule(new MyTask(), 2, TimeUnit.SECONDS);
System.out.println("scheduling a task to delay 3 seconds then repeat every 5 seconds");
// Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds
executor.scheduleAtFixedRate(new MyTask(), 3, 5, TimeUnit.SECONDS);
// Wait for scheduled tasks to complete
try {
System.out.println("sleeping to demo scheduling at work");
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Shutdown the executor
executor.shutdown();
System.out.println("end");
}
static class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task executed at: " + new java.util.Date());
}
}
}
Wednesday, September 18, 2024
Java ScheduledExecutorService
Sunday, September 15, 2024
Determinant of a matrix
This little program calculates the determinant of an matrix.. using recursion. You don't even need ad - bc for a 2x2 [[a b][c d]]
https://en.wikipedia.org/wiki/Determinant
public class CodeWar {
public static int[][] buildSubmatrix(int[][] matrix, int r, int c) {
int size = matrix.length - 1;
int result[][] = new int[size][size];
int a = 0, b = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (i != 0 && j != c) {
result[a][b] = matrix[i][j];
b++;
}
}
if (i != r) {
a++;
b = 0;
}
}
return result;
}
public static int determinant(int[][] matrix) {
if (matrix.length == 1)
return matrix[0][0];
int sign = 1;
int sum = 0;
for (int i = 0; i < matrix[0].length; i++) {
int n = matrix[0][i];
int submatrix[][] = buildSubmatrix(matrix, 0,i);
sum += sign * n * determinant(submatrix);
sign = sign * -1;
}
return sum;
}
public static void main(String arg[]) {
int[][] matrix = {
{ -2, -1,2 },
{ 2,1,4 },
{ -3,3,1 } };
System.out.println(determinant(matrix));
}
}
Subscribe to:
Comments (Atom)