product of two matrices with Threads - java

I'm not very good at programming, but I am obliged to write a program that calculates the product of two matrices by two methods :
The first method in a direct way.
The second using Threads so that the computation time is minimal.
I wrote this program for the first method :
Matrix.java
public class Matrix {
public int [][] M;
public int line,col;
static int [][]MProd=null;
//Constructeur
public Matrix (int [][] M,int line,int col) {
this.M=M;
this.col=col;
this.line=line;
for ( int i=0;i<this.line;i++){
for (int j=0;j<this.col;j++)
{
M[i][j]=(int)(Math.random()*100);}}
}
static int [][] prod(Matrix Mat1, Matrix Mat2 ){
for (int j=0;j<Mat2.col;j++){
for (int i=0;i<Mat1.col;i++){
for (int k=0;k<Mat1.line;k++){
MProd[k][j] += Mat1.M[k][i]*Mat2.M[i][j];
}}}
return MProd ;
}}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int [][] M = null,N = null;
int line1,line2,col1,col2;
int [][] P=null;
Scanner scanner = new Scanner(System.in);
System.out.println("enter the line number of the first matrix");
line1=scanner.nextInt();
System.out.println("enter the number of columns of the first matrix");
col1=scanner.nextInt();
Matrix Mat= new Matrix (M,line1,col1);
System.out.println("enter the line number of the 2nd matrix");
line2=scanner.nextInt();
System.out.println("enter the number of columns of the 2nd matrix");
col2=scanner.nextInt();
Matrix Mat1= new Matrix (N,line2,col2);
if (col1==line2)
{
P=Matrix.prod(Mat,Mat1) ;
System.out.println("matrix product :");
for (int i=0;i<Mat.line;i++)
{
for (int j=0;j<Mat1.col; j++)
System.out.print( + P[i][j]+" ");
System.out.println();
}}
else {
System.out.println("the matrices product is impossible");
}
}}
when I run the program it shows me :
Exception in thread "main" java.lang.NullPointerException
at Matrice.(Matrice.java:18)
at Main.main(Main.java:15)
Can someone help me to correct this program, and shows me how to write this program with Threads ?

Your NullPointerException is due to this:
public static void main(String[] args) {
int [][] M = null,N = null; // all declared null
// ...
Matrix Mat= new Matrix (M,line1,col1); // here you use a null value, M
// ...
Matrix Mat1= new Matrix (N,line2,col2); // and same here, N is null
When you call, M[i][j]=(int)(Math.random()*100); in your Matrix class, M is null so this will fail. You must first create a Matrix, your 2D array, before you can use it.
Edit
You ask:
Can you explain me more.
You're passing a null reference into your Matrix constructor and then trying to use it as a variable. You should pass a non-null 2D array instead:
int[][] myArray = new int[x][y]; // where x and y are appropriate numbers
Matrix Mat= new Matrix (myArray, line1, col1);
Also, please study and use standard Java Coding Conventions (please see link) including:
All class, enum and interface names begin with an uppercase letter.
All method and variable names begin with a lowercase letter.
Learn to use judicious use of white space including a space between parameters.
Do this and folks will be better able to read and understand your code and then be able to give you better help.

Related

Finding for a specific row in a 2D Array and printing it out in Java

Sorry, I'm new to Java. I created a 2D array and populated it with String data. Now the task is to find a specific row in that array, that is filled with certain String and print it out. I mean to print only the row that was found. The problem is I don't know what row would it be. I managed to find that row and print it, but it prints the column along with the found row. Is it possible to print only the row but not the column?
Sorry for my English.
public class Math extends StudentCharts {
public Math(){
math = new String [3][3];
math[0][0]="math"; math[0][1]="person1"; math[0][2]="49";
math[1][0]=math[0][0]; math[1][1]="person2"; math[1][2]="12";
math[2][0]=math[0][0]; math[2][1]="person3"; math[2][2]="31";
}
public void prnt (String namechk){
int x = 0;
int y = 0;
for (x=0; x<3; x++) {
if (namechk.equals(math[x][1])) {
for (y=0; y<3; y++) {
System.out.println(math[x][y]+" ");
}
}
else { System.out.println("error");
}
The main class:
public static void main(String[] args) {
Math chr1 = new Math();
Scanner user = new Scanner(System.in);
System.out.println("Enter full name, please");
String namecheck = user.nextLine();
chr1.prnt(namecheck);

How can I pass these parameters (java)?

I am very new to Java, and I'm having a difficult time figuring out how to take arguments from the command prompt and pass them around in my code. I am able to get them into the main method of my code, but I'd rather have them in the Chessboard class. There is a public static int n that is hard coded, but I would like it to be whatever I send in as arguments. I'll later be taking an initial position for a queen's placement, so I'm hoping the process will be similar; if I get help with this, hopefully I can use the same technique for that.
public class Chessboard {
public static void main(String[] args) {
System.out.println("Hello World");
Chessboard board = new Chessboard(); //creates a Chessboard object
board.start();
}
public static int n = 8;
private static int board[][]; //this is the Chessboard array
private int numQueens; //this is the number of queens on the board
public Chessboard(){
numQueens = 0; //initialized to zero, no queens on board to start yet
board = new int[n][n]; //nxn 2D array of zeros
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
board[j][k] = 0; //redundant, but I need to learn how to
} //initialize. this manually puts zeros into
} //the array
}
...and the code continues from here, but I don't think it's necessary. If it is, I'm happy to upload it.
Thank you for your time.
Here's what I'd do.
public static void main(String[] args) {
try {
int firstArg = Integer.parseInt(args[0]);
Chessboard board = new Chessboard(firstArg);
// Do some stuff with the chessboard here.
}
catch(NumberFormatException e) {
System.out.println("That's not a number");
}
}
This looks at the first command line argument and tries to convert it to an int. If it succeeds, it passes that int to the constructor of Chessboard to make an object for you to use.
This snippet also shows how you can provide code that runs if the first command line argument isn't actually a number.
Notice that the main method is already in your Chessboard class. If you want to leave your n variable as static, you can just do this in the main method.
n = Integer.parseInt(args[0]);
If you make n an instance variable instead of having it be static, then the answer that David Wallace gave will point you in the right direction.
In your Chessboard Class create an
private String[] args;
Then add an setter to Chessboard like:
public void setArgs(String[] args{
this.args = args;
}
Then put something like this in your main:
public static void main(String[] args) {
Chessboard board = new Chessboard();
board.setArgs(args);
board.start();
}

Terminated due to timeout in hacker rank for large inputs

This code shows "Terminated due to timeout" error on some large inputs on Hackerrank but works fine for the rest of the cases. Help me improve this code please.
John Watson performs an operation called a right circular rotation on an array of integers, . After performing one right circular rotation operation, the array is transformed from to .
Watson performs this operation times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks queries, where each query consists of a single integer, , for which you must print the element at index in the rotated array (i.e., the value of ).
Input Format
The first line contains space-separated integers, , , and , respectively.
The second line contains space-separated integers, where each integer describes array element (where ).
Each of the subsequent lines contains a single integer denoting .
Constraints
Output Format
For each query, print the value of the element at index of the rotated array on a new line.
Sample Input
3 2 3
1 2 3
0
1
2
Sample Output
2
3
1
MY CODE
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n,k,q,temp=0,c=0;
Scanner sc=new Scanner(System.in);
try{
n=sc.nextInt();
k=sc.nextInt();
q=sc.nextInt();
int[] arr=new int[n];
int qrr[]=new int[q];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
while(sc.hasNext()){
qrr[c++]=sc.nextInt();
}
for(int j=1;j<=k;j++){
temp=arr[n-1];
for(int i=n-2;i>=0;i--){
arr[i+1]=arr[i];
}
arr[0]=temp;
}
for(int i=0;i<q;i++){
System.out.println(arr[qrr[i]]);
}
}
catch(Exception ae){
System.out.println(ae.getMessage());
}
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static int m,n,k,q,i=0,c=0;
public static int errorflag = 0;
public static int array[];
public static int rotated[];
public static Scanner in = new Scanner(System.in);
public static int[] getArray(int n){
array = new int[n];
for(i=0;i<n;i++){
array[i] = in.nextInt();
}
return(array);
}
public static int[] rotate(int[] original){
int[] rotated = new int[original.length];
for(i=0;i<original.length;i++){
rotated[(i+k)%original.length] = original[i];
}
return(rotated);
}
The above function works with a worst case O(n) complexity.
Basically what you're doing is assigning a new index for the elements such that they are right rotated or incremented by an amount k and the overflow is taken care of by the modulus operation.
public static void main(String[] args) {
n = in.nextInt();
k = in.nextInt();
q = in.nextInt();
array = getArray(n);
int m[] = new int[q];
for(i=0;i<m.length;i++){
m[i] = in.nextInt();
}
rotated = rotate(array);
for(i=0;i<m.length;i++){
System.out.println(rotated[m[i]]);
}
}
}

calculate number of occurrences in array in java

I want to calculate the number of occurences of a specific number I decide in my main method. Here is what I have to do :
• A function that fills the array with random numbers.
• A function that calculates the number of occurrences,this function may not do any input or output.
• The main function that asks the user for the number and present the result on the screen.
Here is my code in java :
import java.util.Random;
import java.util.Scanner;
public class Code {
public void calculate(int value) {
Code c = new Code();
int count=0;
for (int n=0; n<array.length; n++) { // the code does not recognize array
if (array[n]==value) { // the code does not recognize array
count++;
}
}
System.out.println(count);
}
public void addToArray() {
int k =0;
int [] array = new int[10];
int min=0;
int max=10;
int diff = max-min;
while (k<10) {
Random r = new Random();
int x = r.nextInt(diff);
array[k]=x;
k=k+1;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("give your number");
Code c = new Code();
Scanner s = new Scanner(System.in);
int value = s.nextInt();
c.addToArray();
c.calculate(value);
}
}
The only thing I need help with is the calculate method ,, eclipse does not recognize array in the calculate method above ..
How to correct the calculate method to make it recognize array ?
thank you
Your array is limited to the scope of the method addToArray(). So, it will not be visible to other methods. You need to make it global. Then it will work.
Instead of declaring array in the method addToArray, declare it in your class, like:
public class Code {
int [] array = new int[10];
...
if using Java 8 you could update your calculate methode like this :
public void calculate(int value) {
System.out.println(Arrays.stream(array)
.filter(i -> i == value)
.count());
}
By adding this imports to your class :
import java.util.Arrays;
And like mentionned HackerDarshi declaring the attribut array as a member of your class

Unable to increase the size of the array dynamically in java

I'm trying to increase the size of a two dimensional array dynamically. However,I'm getting an Array out of Bounds error it. Below posted the code. In this scenario,I'm trying to add values dynamically to the two dimensional vector weight[][] under some condition. Any suggestions would be highly helpful!
class perceptron {
public static void main(String[] args) {
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [] classlabels = {1,1,-1,-1};
int [] [] weight = {{0,0}};
int base=0;
int i,j;
int activation=0;
for(i=0;i<myPoints.length;i++) {
for(j=0;j<classlabels.length;j++) {
activation = activation+((myPoints[i][0]*weight[i][0])+(myPoints[i]
[1]*weight[i][1]));
System.out.println("dot product of two vectors" + activation);
if((activation*classlabels[j]) <= 0) {
System.out.println("hi");
weight[i+1][0] = weight[i][0]+ (classlabels[j]*myPoints[i]
[0]);
weight [i+1][1] =weight[i][1]+(classlabels[j]*myPoints[i]
[1]);
System.out.println(weight[i+1][0]);
System.out.println(weight[i+1][1]);
base = base+classlabels[j];
System.out.println(base);
}
}
}
}
}
Java arrays are strictly fixed-size. You must use an ArrayList.
Example:
ArrayList<ArrayList<Double>> weights = new ArrayList<>();
weights.add(new ArrayList<Double>()); // extend to be 1x0
weights.get(0).add(1.2); //weights[0][0]=1.2
weights.get(0).add(2.3); // weights[0][1]=2.3

Categories

Resources