I'm trying to implement the matrix multiplication algorithm, but I have an issue dealing with BigInteger.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Size of Matrix A");
int tamA1 = scan.nextInt();
int tamA2 = scan.nextInt();
System.out.println("Size of Matrix B");
int tamB1 = scan.nextInt();
int tamB2 = scan.nextInt();
BigInteger[][] A = new BigInteger[tamA1][tamA2];
BigInteger[][] B = new BigInteger[tamB1] [tamB2];
BigInteger[][] C = new BigInteger[A.length][B[0].length];
System.out.println("Values of Matrix A");
for (int i = 0; i < tamA1; i++) {
for (int j = 0; j < tamA2; j++) {
A[i][j] = scan.nextBigInteger();
}
}
System.out.println("Values of Matrix B");
for (int i = 0; i < tamB1; i++) {
for (int j = 0; j < tamB2; j++) {
B[i][j] = scan.nextBigInteger();
}
}
if (A[0].length == B.length) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < A[0].length; k++) {
C[i][j] =C[i][j].add(A[i][k].multiply(B[k][j])); // Result
}
}
}
}
System.out.println(" C is equal to: ");
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
System.out.print(C[i][j]+" ");
}
System.out.println("");
}
}
Take a look at this output:
Matrix A
2 2
Matrix B
2 2
Values of A
2 2
1 0
Values of B
3 4
5 6
Exception in thread "main" java.lang.NullPointerException
at matrixmultiplication.MatrixMultiplication.main(MatrixMultiplication.java:56)
C:\Users\Luis Miguel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
I don't know why I can do this operation with int and not with BigInteger.
Thanks in advance.
The "difference" (or really a similarity, depending on how you think about it) between an array of int and an array of BigInteger is that when you make a new array of integers, all the integers exist (and are zero) while a new array of BigInteger is filled with null. Of course add cannot be called on null.
There are different fixes, for example you could fill the matrix C with zeros, or you could modify the multiplication so that it does not read from C at all but instead sums into a local variable which you initialize to zero.
Related
hello guys I am struggling to find the right way to print only the even numbers of the array.
I made a 1 dimensionnal array to save the element of the columns and then make sure if the index of the col%2==0 put that number in the output.
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//array with 3 row in 5 col
int[][] matrix = new int[3][5];
//int []y = new int[5];
// to impalement th array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print("Enter matrix[" + i + "][" + j + "]: ");
matrix[i][j] = input.nextInt();
}
System.out.print("\n");
}
System.out.print("matrix values \n");
// to show up the originally array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.print("\n");
}
//////the new array to display only the even numbers in the col
System.out.print("\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
int[] y = matrix[j];
for (int k = 0; i < y.length; i++) {
if (y[k] % 2 == 0)
System.out.println(y[k]);
}
}
}
}
}
the output doesn't print the new array
matrix values
1 2 3 4 5
6 7 8 9 10
3 2 4 5 9
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Matrix.main(Matrix.java:43)
Replace i by k here :
for (int j = 0; j < 5; j++) {
int[] y = matrix[j];
for (int k = 0; i < y.length; i++) {
if (y[k] % 2 == 0)
System.out.println(y[k]);
}
}
Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
So I am creating a program that rolls z die x times with y sides, and I keep getting an out of bounds error at the first line in the first for loop. However I'm not sure why this is, the loop counts from 0 to (z-1). I'm basically in the home stretch of this program and I need the help of the stackoverflow community.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int x = console.readInt();
System.out.print("Enter the amount of sides: ");
int y = console.readInt();
System.out.print("Enter the amount of die: ");
int z = console.readInt();
int[][] dice = new int[x][z];
int row = 0;
for (int i = 0; i<z; ++i){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x)) {
i = 0;
++row;
}
}
row = 0;
int[] sum = new int[x];
for (int j = 0; j<z; ++j){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x)) {
j = 0;
++row;
}
}
int[] counter = new int[2*y];
int k = 0;
while (k<sum.length){
for (int l = 0;l<((2*y)-1);++l){
if (sum[k]==l) ++counter[l];
if (l==((2*y)-1)) {
++k;
}
}
}
for (int m = 0;m<sum.length;++m) System.out.println(sum[m]+"'s: "+counter[m]+"times, "+((((double)counter[m])/x)*100)+"%");
}
}
first loop:
for (int i = 0; i<z; i++){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x-1)) {
i = -1;
++row;
}
}
second loop:
for (int j = 0; j<z; j++){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x-1)) {
j = -1;
++row;
}
}
Third loop: runs forever. I'm not sure what this is trying to achieve, so I can't fix it for you...
There are x rows but you are using z as the row loop
int[][] dice = new int[x][z]; <-- x is the row count
int row = 0;
for (int i = 0; i < z; ++i){ <--- The outer loop is iterating the rows (x),
Here's how to iterate through a 2D array
int[][] dice = new int[x][z];
for (int i = 0; i < x; i++){
for (int j = 0; j < z; j++){
// do something with dice[i][j]
}
}
I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.
Hey guys, im working through the Introduction to Programming in Java book and one of the exercises is this:
Empirical shuffle check. Run
computational experiments to check
that our shuffling code works as
advertised. Write a program
ShuffleTest that takes command-line
arguments M and N, does N shuffles of
an array of size M that is initialized
with a[i] = i before each shuffle, and
prints an M-by-M table such that row i
gives the number of times i wound up
in position j for all j. All entries
in the array should be close to N/M.
Now, this code just outputs a block of zeros...
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
for (int i = 0; i < M; ++i)
deck [i] = i;
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
for(int n = 0; n < N; n++) {
int r = i + (int)(Math.random() * (M-i));
int t = deck[r];
deck[r] = deck[i];
deck[i] = t;
for (int b = 0; b < N; b++)
{
for (int c = 0; c < M; c++)
System.out.print(" " + a[b][c]);
System.out.println();
}
}
}
}
}
}
What am i doing wrong? :(
Thanks
So a is like a history? As you are now it is always filled with zeroes just like you initialized, you never assign to it! After the "shuffling" for loop you need to set
A[i][POSITION] = CARD_VALUE
Meaning that after i-th shuffle, card CARD_VALUE is in position POSITION. I don't want to give you all the specifics, but it will take another for loop, and the nested for-loop for printing needs to be independent of any other loop, occuring when everything else is done.
Looks like you have a few things concerning the for-loops that you need to look over carefully. Trace the program flow manually or with a debugger and you'll notice that some of those braces and code blocks need to be moved.
--TRY THIS--
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) { //initialize a to all zeroes
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
}
}
for(int i = 0; i < N; i++) //puts the deck in order, shuffles it, and records. N times
{
for (int j = 0; j < M; j++) //order the deck
deck[j] = j;
for(int j = 0; j < M; j++) { //shuffle the deck (same as yours except counter name)
int r = j + (int)(Math.random() * (M-j));
int t = deck[r];
deck[r] = deck[j];
deck[j] = t;
}
for(int j = 0; j < M; j++) //record status of this deck as described
{
int card_at_j = deck[j]; //value of card in position j
a[card_at_j][j]++; //tally that card_at_j occured in position j
}
} //big loop ended
for (int b = 0; b < M; b++) //print loop. a is MxM, so limit of N was wrong.
{
for (int c = 0; c < M; c++)
{
System.out.print(" " + a[b][c]);
System.out.println();
}
} //print loop ended
} //main() ended
} //class ended