'Added Java functional programming tutorial and excercises;'

This commit is contained in:
Arkadiusz Hypki 2024-05-20 13:36:41 +02:00
parent 4993b801c6
commit b54d5336f2
7 changed files with 345 additions and 46 deletions

View File

@ -1,59 +1,57 @@
/*
============================================================================
Name : openmp1.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>
void maks(int numThreads, int my_array[])
{
int globMaks = 0;
int threadMaks = 0;
int a = 10;
clock_t start = clock();
omp_set_num_threads(numThreads);
#pragma omp parallel private(threadMaks) shared(globMaks)
{
#pragma omp for
for (int i = 0; i < a; i++)
{
if (my_array[i] > threadMaks)
{
threadMaks = my_array[i];
}
}
void sum() {
int partial_Sum, total_Sum;
#pragma omp parallel private(partial_Sum) shared(total_Sum)
{
partial_Sum = 0;
total_Sum = 0;
#pragma omp for
for(int i = 1; i <= 10; i++) {
partial_Sum += i;
}
//Create thread safe region.
#pragma omp critical
{
//add each threads partial sum to the total sum
total_Sum += partial_Sum;
}
}
printf("Total Sum: %d\n", total_Sum);
#pragma omp critical
{
if (threadMaks > globMaks)
{
globMaks = threadMaks;
}
}
}
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
printf("\n%d maksymalna dla %d watkow, czas: %f \n", globMaks, numThreads, seconds);
printf("\n");
}
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
const int a = 10;
int my_array[a];
srand(time(NULL));
for (int i = 0; i < a; i++) {
my_array[i] = rand();
}
const int numThreads = 4;
int a[numThreads];
omp_set_num_threads(numThreads);
#pragma omp parallel
{
int id = omp_get_thread_num();
a[id] = id + 1;
}
for (int i = 0; i < a; i++) {
printf("%d ", my_array[i]);
}
for (int i = 0; i < numThreads; i++) {
printf("Hello from thread %d\n", a[i]);
}
int globMaks;
int threadMaks = 0;
sum();
// sum2();
maks(2, my_array);
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}

10
09_JavaFP/ex.txt Normal file
View File

@ -0,0 +1,10 @@
1. Write Lambda expression in Java which implements sum of two integers
2. Write Lambda expression in Java which removes duplicates from a list
3. Write Lambda expression in Java which capitalize all strings
4. Write Lambda expression in Java which finds all even and odd numbers
5. Write Lambda expression in Java which finds the average length of strings in a list.

View File

@ -0,0 +1,55 @@
package net.hypki.wmi.javafp;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ArraysFunctionalProgramming {
// Java program to demonstrate an
// external iterator
public static void printArrayWithIterator() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
// External iterator, for Each loop
for (Integer n : numbers) {
System.out.print(n + " ");
}
System.out.println();
}
public static void printArrayWithIndices() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
// External iterator, with indices
for (int i = 0; i < numbers.size(); i++) {
System.out.print(numbers.get(i) + " ");
}
System.out.println();
}
public static void printArrayWithLambdas() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
// Internal iterator
numbers.forEach(number -> System.out.print(number + " "));
System.out.println();
// it is the same as implementing interfaces, but with interfaces it is a little bit more ugly
numbers.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.print(t + " ");
}
});
System.out.println();
}
public static void main(String[] args) {
printArrayWithIterator();
printArrayWithIndices();
printArrayWithLambdas();
}
}

View File

@ -0,0 +1,39 @@
package net.hypki.wmi.javafp;
import java.util.function.Function;
import java.util.logging.Logger;
public class FunctionChaining {
static Logger logger = Logger.getLogger(FunctionChaining.class.getName());
private static Function<Integer, Integer> multiply = x -> x * 2;
private static Function<Integer, Integer> add = x -> x + 2;
private static Function<Integer, Integer> logOutput = x -> {
logger.info("Data:" + x);
return 0;
};
public static void execute(Integer input) {
Function<Integer, Integer> pipeline = multiply
.andThen(add)
.andThen(logOutput);
pipeline.apply(input);
}
public static void execute2(Integer input) {
multiply
.andThen(add)
.andThen(logOutput)
.apply(input);
}
public static void main(String[] args) {
execute(10);
execute2(10);
}
}

View File

@ -0,0 +1,70 @@
package net.hypki.wmi.javafp;
import java.util.Arrays;
import java.util.List;
public class ImperativeVsDeclarative {
public static void imperative() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
int result = 0;
for (Integer n : numbers) {
if (n % 2 == 0) {
result += n * 2;
}
}
System.out.println(result);
}
public static void declarative() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
System.out.println(numbers
.stream()
.filter(number -> number % 2 == 0) // 1.
.mapToInt(e -> e * 2) // Closure
.sum());
// 1. Lambda expressions: A Lambda expression is an anonymous method that has mutability at very minimum and it has only a parameter list and a body.
// 2. in the above code of declarative style, every function is a pure function and pure functions dont have side effects.
// 3. lambdas are stateless and closure has immutable state. It means in any circumstances, the closure could not be mutable.
}
public static void immutable() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
int factor = 2;
System.out.println(numbers
.stream()
.filter(number -> number % 2 == 0)
.mapToInt(e -> e * factor)
.sum());
}
public static void NOTimmutable() {
List<Integer> numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100);
int factor = 2;
System.out.println(numbers
.stream()
.filter(number -> number % 2 == 0)
.mapToInt(e -> e * factor)
.sum());
// factor = 3;// uncomment this
// * the variable factor is by default being considered as final.
// * we should never try mutating any variable which is used inside pure functions == that would violate pure functions rules
// which says pure function should neither change anything nor depend on anything that changes
}
public static void main(String[] args) {
imperative();
declarative();
immutable();
NOTimmutable();
}
}

View File

@ -0,0 +1,94 @@
package net.hypki.wmi.javafp;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Parallel {
public static void main(String[] args) {
// forEach
System.out.println("Printing list: ");
Arrays
.asList(1,2,3)
.forEach(System.out::println); // Consumer
// print output -> 1 2 3
// map
System.out.println("Computing squares (with limit and sort): ");
List<Integer> numbers = Arrays.asList(2,3,4,5);
numbers.stream()
.map(x -> x *x) // Function
.sorted()
.limit(2)
.collect(Collectors.toList())
.forEach(System.out::println);;
// print output -> [4, 9]
// filter
System.out.println("Filtering list of strings: ");
List<String> names = Arrays.asList("Sally", "Harry", "Sephora");
names
.stream()
.filter(s -> s.startsWith("S")) // Predicate
.collect(Collectors.toList())
.forEach(System.out::println);;
// print output -> [Sally, Sephora]
// sorted
System.out.println("Sorting names: ");
names.stream()
.sorted()
.collect(Collectors.toList())
.forEach(System.out::println);;
// print output -> [Harry, Sally, Sephora]
// reduce
System.out.println("Printing even numbers: ");
numbers.stream()
.filter(x -> x % 2 == 0)
.collect(Collectors.toList())
.forEach(System.out::println);
int even = numbers.stream()
.filter(x -> x % 2 == 0) // Predicate
.reduce(4, Integer::sum); // BinaryOperator which extends BiFunction
// print output -> 10
System.out.println("Sum of even numbers (+4 initial value): " + even);
// max
int maxN = numbers
.stream()
.max(Integer::compare)
.get(); // Comparator
// print output -> 5
System.out.println("Max value: " + maxN);
// min
int minN = numbers
.stream()
.min(Integer::compare)
.get(); // Comparator
// print output -> 2
System.out.println("Min value: " + minN);
// skip
System.out.println("Skipping first number: ");
numbers
.stream()
.skip(1)
.collect(Collectors.toList())
.forEach(System.out::println);;
// print output -> [3,4,5]
System.out.println("Computing squares in parallel: ");
numbers.stream()
.parallel() // add this line here
.map(x -> x *x)
.sorted()
.limit(2)
.collect(Collectors.toList())
.forEach(System.out::println);;
}
}

View File

@ -0,0 +1,33 @@
package net.hypki.wmi.javafp;
import java.util.Arrays;
import java.util.List;
public class RunnableFunctionalProgramming {
public static void runnableWithoutFunProgramming() {
Runnable r = new Runnable() {
public void run() {
System.out.println("Running in Runnable thread");
}
};
r.run();
System.out.println("Running in main thread");
}
public static void runnableWithFunProgramming() {
// lambda expression
Runnable r = () -> System.out.println("Running in Runnable thread");
r.run();
System.out.println("Running in main thread");
}
public static void main(String[] args) {
runnableWithoutFunProgramming();
runnableWithFunProgramming();
}
}