what is a difference between parallel and sequential method in Java? - parallel-processing

I try to code currently in Java 8. Yesterday I have found the next source with the examples from linear algebra. On the basis of the Matrix Vector multiplication (last example in the link) I coded my owner method for multiplication of matrices. My code is here:
import java.util.stream.IntStream;
public static void matrixMatrixProduct() {
System.out.println("Matrix matrix mulptiplication");
final int DIM1 = 15;
final int DIM2 = 20;
final int DIM3 = 2;
int[][] a = new int[DIM1][DIM2];
int[][] b = new int[DIM1][DIM3];
int[][] c = new int[DIM3][DIM2];
int counter = 1;
for (int i =0; i < DIM1; i++) {
for (int j =0; j < DIM3; j++) {
b[i][j] = counter++;
}
}
for (int i =0; i < DIM3; i++) {
for (int j =0; j < DIM2; j++) {
c[i][j] = counter++;
}
}
System.out.println("");
System.out.println("Print matrix b");
System.out.println("");
for (int i = 0; i < DIM1; i++) {
for (int j = 0; j < DIM3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}
System.out.println("");
System.out.println("Print matrix c");
System.out.println("");
for (int i = 0; i < DIM3; i++) {
for (int j = 0; j < DIM2; j++) {
System.out.print(c[i][j] + " ");
}
System.out.print("\n");
}
IntStream.range(0, DIM1)
.parallel()
.forEach( (i) -> {
IntStream.range(0, DIM2)
.sequential()
.forEach( (j) -> {
IntStream.range(0, DIM3)
.parallel()
.forEach( (k) -> {
a[i][j] += b[i][k]*c[k][j];
});
});
});
System.out.println("");
System.out.println("Print matrix a");
System.out.println("");
for (int i = 0; i < DIM1; i++) {
for (int j = 0; j < DIM2; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
My question is, what is exactly the difference between parallel() and sequential() method by the calling of IntStream class? (Actually this is the most important part, where I do the multiplication explicitly). Based on this knowledge I want to know, what is a correct usage in the last IntStream calling. Currently I have defined in this place the method parallel(), but I'm not sure this is a right solution... Actually, if I change parallel() to sequential() I don't see any difference in the output.

Parallel operations happen concurrently. This means that the elements of the stream may be processed simultaneously.
Sequential operations happen one at a time.
Changing from sequential() to parallel() has no impact on the result since your operations are state-independent, but may affect your run-time. However, if the operations your perform affect future operations, then you should consider using sequential().
I would assume you want matrix operations to happen in parallel, but I'm not too familiar with the math.
Link to the Javadoc, as referenced by #the8472.

Related

Is declaring a new intger inside a loop changes the space complexity?

Is declaring a new intger inside a loop changes the space complexity of the metohd?
for exampe if i'm looking at the follwoing 2 methods, is both of the methods space complexity is O(1)? or in the first method becuase I'm declaring the variable c over and over until the loop end it's space complexity is O(n)?
public static int what (int []a) {
int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
**int c = f(a, i, j);**
if (c % 2 == 0) {
if (j - i + 1 > temp)
temp = j - i + 1;
}
}
}
return temp;
}
public static int what (int []a) {
int temp = 0;
**int c;**
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
**c = f(a, i, j);**
if (c % 2 == 0) {
if (j - i + 1 > temp)
temp = j - i + 1;
}
}
}
return temp;
}
Not sure if it's relevant to the question but also attahced the f method.
private static int f (int[]a, int low, int high)
{
int res = 0;
for (int i=low; i<=high; i++)
res += a[i];
return res;
}
When you declare a variable inside the for loop it goes out of scope when the iteration ends and gets re declared in the next iteration so you are not declaring n variables, you are declaring a variable n times

Hockey stick pattern in pascal's triangle

I learnt about pascal's triangle and achieved to print one in Java with O(n2) complexity.
Now for the next part I have to find the sequences of numbers that form a hockey stick pattern and I am stuck here. Any help will be great!
Also this link will help you understand what a hockey stick pattern is in pascal's triangle.
Below is the code I wrote to return the triangle
int[][] printPascal(int n)
{
int[][] arr= new int[n][n];
for(int line=0;line<n;line++)
{
for(int i=0;i<=line;i++)
{
if(line==i|| i==0)
{
arr[line][i]=1;
}
else
{
arr[line][i]=arr[line-1][i-1]+arr[line-1][i];
}
System.out.print(arr[line][i]+" ");
}
System.out.println();
}
return arr;
}
I tried to do something but I am getting arrayIndexOutOfBound
void printSequence(int[][]arr)
{
int n= arr.length;
Map<Integer, List<Integer>> map =new HashMap<>();
List<Integer> sequence= new ArrayList<>();
for(int i=0;i<=n;i++)
{
int count=0;
int res=0;
for(int line=0;line<n;line++)
{
sequence.add(arr[line][i]);
res=sumList(sequence);
if(res!=arr[line+1][i+1])
{
sequence=new ArrayList<>();
continue;
}
else
{
List<Integer> resSeq= new ArrayList<>(sequence);
resSeq.add(arr[line+1][i+1]);
map.put(++count, resSeq);
res=0;
}
}
}
}
I need to find all the sequences that satisfies the rule
nCr+(n+1)Cr+(n+2)Cr+.....+(n+k)Cr=(n+k+1)Cr
And these sequences if marked on a Pascal's triangle will resemble a hockey stick.
Here is how my solution looks like
void hockeyNumbers(int[][] arr) {
int n = arr.length;
List<Integer> sequence;
Map<Integer, List<Integer>> map = new HashMap<>();
int count = 0;
for (int i = 0; i < n; i++) {
int res = 0;
sequence = new ArrayList<>();
for (int line = i; line < n - 1; line++) {
sequence.add(arr[line][i]);
res = sumList(sequence);
if (res == arr[line + 1][i + 1]) {
List<Integer> resSeq = new ArrayList<>(sequence);
resSeq.add(arr[line + 1][i + 1]);
if (resSeq.size() > 2) {
map.put(++count, resSeq);
}
res = 0;
}
}
}
}
I have worked the solution and it looks like below. I am storing all the sequences in a hashmap for later use.
void hockeyNumbers(int[][] arr) {
int n = arr.length;
List<Integer> sequence;
Map<Integer, List<Integer>> map = new HashMap<>();
int count = 0;
for (int i = 0; i < n; i++) {
int res = 0;
sequence = new ArrayList<>();
for (int line = i; line < n - 1; line++) {
sequence.add(arr[line][i]);
res = sumList(sequence);
if (res == arr[line + 1][i + 1]) {
List<Integer> resSeq = new ArrayList<>(sequence);
resSeq.add(arr[line + 1][i + 1]);
if (resSeq.size() > 2) {
map.put(++count, resSeq);
}
res = 0;
}
}
}
}
I have tried finding the hockey stick through Pascal's triangle with some boundary conditions.(0 < n <= 30000 && 0 < l <= 100) where n is the row number(rows starts with 0) and l is the length of the hockey stick(length starts with 0).But, these extreme conditions create timeout issues.
Now, one way to create Pascal's triangle is using Binomial coefficients.
Following the same thing, we can get the hockey stick. For this, we don't need to create the complete triangle. You just need the row number and the length of the hockey stick.
We know that hockey stick always starts with 1 and second index of that row will be the row number itself.
So now, we already have two values of the hockey stick 1 and (Row+1).
The next value can be generated through Binomial coefficients using the following :
C(line, i) = C(line, i-1) * (line - i + 1) / i
private static void hockeyStick(int row, int length) {
System.out.println("Hockey stick statring from " + row);
List<Integer> finalResult = new ArrayList<>(Arrays.asList(1, ++row));
int oldValue = 1;
int newValue = row;
int sum = row + 1;
for (int i = 2; i < length - 1; i++) {
finalResult.add(newValuebimialCoefficient(oldValue + newValue, i, ++row));
oldValue += newValue;
newValue = finalResult.get(i);
sum += newValue;
}
finalResult.add(sum);
System.out.println(finalResult);
}
private static int newValuebimialCoefficient(int oldValue, int index, int line) {
return (oldValue * (line - index + 1) / index);
}
I think this should be helpful.

How to sort the boundary elements of a matrix in ascending order?

I've worked on this but when I'm entering the matrix, all the elements in the matrix are getting sorted! But I want to sort only the boundary elements in ascending order. Can some body please tell me my mistake?
int k,temp=0,sum=0;
k=n;
boolean b=true;
do
{
for(i=0;i<m;i++)
{
for(j=0;j<k-1;j++)
{
if(i!=0||j!=0)
{
if(A[i][j]>A[i][j+1])
{
temp=A[i][j];
A[i][j]=A[i][j+1];
A[i][j+1]=temp;
}
}
}
}
k-=1;
if(k<0)
b=false;
}while(b);
k=m;
do
{
for(i=0;i<k-1;i++)
{
for(j=0;j<n;j++)
{
if(i!=0||j!=0)
{
if(A[j][i]>A[j][i+1])
{
temp=A[j][i];
A[j][i]=A[j][i+1];
A[j][i+1]=temp;
}
}
}
}
k-=1;
if(k<0)
b=false;
}while(b);
System.out.println("REARRANGED MATRIX:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(A[i][j]+" ");
}
System.out.println();
}
Instead of using the condition 'if(i!=0||j!=0)' use 'if(i==0||i==2||j==0||j==2)'.This may solve the ambiguity you are having.Your mistake was that you have taken the number of rows and columns both to be greater than zero.the boundary elements are those where number of rows is 0 or 2 or number of columns is 0 or 2(by this I mean that only those elements which have coordinates with either i=0 or i=2 or j=0 or j=2 will be considered as boundary elements.matrix coordinates
I have one solution of this. I have used selection sort for doing this.At first I have sorted the matrix then displaying the boundary of the sorted array
import java.io.*;
class Boundary_Sorting
{
public static void main(String args[])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter the rows of the matrix=");
int m = Integer.parseInt(br.readLine());
System.out.println("Enter the column of the matrix=");
int n = Integer.parseInt(br.readLine());
int a[][] = new int[m][n];
int i,j;
System.out.println("Enter the elements of the matrix: ");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("**********************");
System.out.println("The original matrix is");
System.out.println("**********************");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
int B[] = new int[m*n]; //creating a 1D Array of size 'r*c'
int x = 0;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
B[x] = a[i][j];
x++;
}
}
/*Sorting the 1D Array in Ascending Order*/
int t = 0;
for(i = 0; i < (m * n) - 1; i++)
{
for(j = i + 1; j < (m * n); j++)
{
if(B[i] > B[j])
{
t = B[i];
B[i] = B[j];
B[j] = t;
}
}
}
/*Saving the sorted 1D Array back into the 2D Array */
x = 0;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
a[i][j] = B[x];
x++;
}
}
/* Printing the sorted 2D Array */
System.out.println("**********************");
System.out.println("The Sorted Array:");
System.out.println("**********************");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
System.out.println("**********************");
System.out.println("The boundary elements of the matrix is=");
System.out.println("**********************");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
if(i==0 || j==0 || i == m-1 || j == n-1) //condition for accessing boundary elements
System.out.print(a[i][j]+"\t");
else
System.out.print(" \t");
}
System.out.println();
}
}
}

The fastest algorithm for returning max length of consecutive same value fields of matrix?

Here is the given example:
We have the function which takes one matrix and it's number of columns and it's number of rows and returns int (this is gonna be length). For example:
int function (int** matrix, int n, int m)
The question is what's the fastest algorithm for implementing this function so it returns the maximum length of consecutive fields with the same value (doesn't matter if those same values are in one column or in one row, in this example on picture it's the 5 fields of one column with value 8)?
Values can be from 0-255 (grayscale for example).
So in the given example function should return 5.
If this is a bottleneck and the matrix is large, the first optimization to try is to make one pass over the matrix in sequential memory order (row-by-row in C or C++) rather than two. This is because it's very expensive to traverse a 2d array in the other direction. Cache and paging behavior are the worst possible.
For this you will need a row-sized array to track the number of consecutive values in the current run within each column.
int function (int a[][], int m, int n) {
if (n <= 0 || m <= 0) return 0;
int longest_run_len = 1; // Accumulator for the return value.
int current_col_run_len[n]; // Accumulators for each column
int current_row_run_len = 1; // Accumulator for the current row.
// Initialize the column accumulators and check the first row.
current_col_run_len[0] = 1;
for (int j = 1; j < n; j++) {
current_col_run_len[j] = 1;
if (a[0][j] == a[0][j-1]) {
if (++current_row_run_len > longest_run_len)
longest_run_len = current_row_run_len;
} else current_row_run_len = 1;
}
// Now the rest of the rows...
for (int i = 1; i < m; i++) {
// First column:
if (a[i][0] == a[i-1][0]) {
if (++current_col_run_len[0] > longest_run_len)
longest_run_len = current_col_run_len[0];
} else current_col_run_len[0] = 1;
// Other columns.
current_row_run_len = 1;
for (int j = 1; j < n; j++) {
if (a[i][j] == a[i][j-1]) {
if (++current_row_run_len > longest_run_len)
longest_run_len = current_row_run_len;
} else current_row_run_len = 1;
if (a[i][j] == a[i-1][j]) {
if (++current_col_run_len[j] > longest_run_len)
longest_run_len = current_col_run_len[j];
} else current_col_run_len[j] = 1;
}
}
return longest_run_len;
}
You need to pass over each entry of the matrix at least once, so you can't possible do better than O(m*n).
The most straightforward way is to pass over each row and each column once. This will be two passes over the matrix, but the algorithm is still O(m*n).
Any attempt to do it in one pass will probably be a lot more complex.
int function (int** matrix, int n, int m) {
int best=1;
for (int i=0; i<m; ++i) {
int k=1;
int last=-1;
for (int j=0; j<n; ++j) {
if (matrix[i][j] == last) {
k++;
if (k > best) {
best=k;
}
}
else {
k=1;
}
last = matrix[i][j];
}
}
for (int j=0; j<n; ++j) {
int k=1;
int last=-1;
for (int i=0; i<m; ++i) {
if (matrix[i][j] == last) {
k++;
if (k > best) {
best=k;
}
}
else {
k=1;
}
last = matrix[i][j];
}
}
return best;
}

can any body help me with this code of multiplication matrix by matrix ?

this is the code that i write i tried it but it just work for same length matrix and its should work for the two matrix that the columns of the first one as the the rows of the Second ..
void msklret(int matrixA[M][N],int matrixB[M][N],int matrixC[M][N],int r1,intc2,int r2)
{
int i , j,k,sum;
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
sum = 0;
for(k=0; k<r2; k++)
{
sum += matrixA[i][k] * matrixB[k][j];
}
matrixC[i][j]=sum;
sum=0;`
}
}
So assuming you are looking for the naive algorithm:
This is written in c#
public float[,] MatrixMultiply(float[,] leftMat, float[,] rightMat)
{
// get the required row and column ranks for both matrices
int leftRowNum = leftMat.GetLength(0);
int rightRowNum = rightMat.GetLength(0);
int leftColNum = leftMat.GetLength(1);
int rightColNum = rightMat.GetLength(1);
// Check that the inner dimensions are the same
if(leftColNum != rightRowNum)
return null;
int innerLen = leftColNum;
// now define resulting matrix dimensions
float[,] result = new float[leftRowNum,rightColNum];
// perform the multiplication using 3 nested for loops
for(int i = 0; i < leftRowNum; i++)
{
for(int j = 0; j < rightColNum; j++)
{
for(int inner = 0; inner < innerLen; inner++)
{
result[i,j]+= leftMat[i,inner]*rightMat[inner,j];
}
}
}
return result;
}
Now your code would be:
void msklret(int matrixA[M][N],int matrixB[M][N],int matrixC[M][N],int r1,intc2,int r2)
float[,] result = MatrixMultiply(MatrixMultiply(matrixA,matrixB),matrixC);
Which can also be written:
float[,] result = MatrixMultiply(matrixA,MatrixMultiply(matrixB,matrixC));
Given the associative property of matrix multiplication.

Resources