Java Matrices - Transpose & Sum - java

I am working on a Matrix program on eclipse and I am currently stuck on 2 methods in which I thought were the most simplest of all. The first method that I am working on is to take the sum of 2 different 2D arrays from the #Test cases and returning the sum in a new 2D array. I already have an 2D array instance variable. The reason I am stuck is because the of the parameter in the method. The parameter doesn't give any variable other than the class (Matrix) and the variable (other). So I was wondering how to go about getting this method started and most importantly returning the sum array.
The other method I am stuck on is the transpose method where you must flip the rows and columns of the given 2D array. I know I must create a temp 2D array in order to store the content back into the original 2D array but for some reason it is not passing the test cases. If someone could please help me with these two methods, it would be much appreciated.
import java.util.Arrays;
public class Matrix {
private int[][] array;
private int[][] array2;
private int theRow;
private int theCol;
public Matrix(int[][] arrayOfArrays) {
// TODO Auto-generated constructor stub
array = new int[arrayOfArrays.length][arrayOfArrays[0].length];
for (int r = 0; r < arrayOfArrays.length; r++) {
for (int c = 0; c < arrayOfArrays[r].length; c++) {
array[r][c] = arrayOfArrays[r][c];
}
}
}
public int get(int row, int column) {
return array[row][column];
}
public int getNumberOfRows() {
int nRows = array.length;
return nRows;
}
public int getNumberOfColumns() {
int nCols = array[0].length;
return nCols;
}
public String toString() {
String res = "";
for (int r = 0; r < array.length; r++) {
for (int c = 0; c < array[r].length; c++)
res = res + array[r][c];
}
return res;
}
public Matrix sum(Matrix other) {
return sum;
}
public void scalarMultiply(int scalar) {
for (int r = 0; r < array.length; r++) {
for (int c = 0; c < array[0].length; c++) {
array[r][c] = array[r][c] * scalar;
}
}
}
public void transpose() {
int m = array.length;
int n = array[0].length;
int[][] transpose = new int [n][m];
int temp;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
transpose[c][r] = array[r][c];
array[r][c] = array[c][r];
array[c][r] = transpose[c][r];
}
}
}
//The test cases for sum method and transpose method
#Test
public void testSum() {
int[][] a1 = { { 1, 2, 3 },
{ 5, 6, 7 } };
Matrix a = new Matrix(a1);
int[][] a2 = { { -2, -2, -2 },
{ 4, 4, 4 } };
Matrix b = new Matrix(a2);
Matrix c = a.sum(b);
assertEquals(-1, c.get(0, 0));
assertEquals(0, c.get(0, 1));
assertEquals(1, c.get(0, 2));
assertEquals(9, c.get(1, 0));
assertEquals(10, c.get(1, 1));
assertEquals(11, c.get(1, 2));
}
#Test
public void testTranspose() {
int[][] a1 = { { 1, 3, 5 },
{ 2, 4, 6 } };
Matrix a = new Matrix(a1);
a.transpose();
assertEquals(1, a.get(0, 0));
assertEquals(2, a.get(0, 1));
assertEquals(3, a.get(1, 0));
assertEquals(4, a.get(1, 1));
assertEquals(5, a.get(2, 0));
assertEquals(6, a.get(2, 1));
}

You need change the dimensions, for example, 2x3 -> 3x2.
import java.util.Arrays;
public class Matrix {
private int[][] array;
private int[][] array2;// remove this
private int theRow;// remove this
private int theCol;// remove this
public void transpose() {
int m = array.length;
int n = array[0].length;
int[][] transpose = new int [n][m];
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
transpose[c][r] = array[r][c];
}
}
array = transpose;
}
}

Related

How can I put the additon of multidimensional array into a method within the same class?

public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;
int [][] matrix1 = new int[ir1][ic1];
int [][] matrix2 = new int[ir2][ic2];
// an example of it is the addition of two matrices put into the method
int total[][] = new int [ir1][ic1];
for (int r = 0; r < matrix1.length; r++) {
for (int c = 0; c < matrix2[r].length; c++)
total [r][c] = matrix1[r][c] + matrix2[r][c];
}
System.out.println("\nThe addition of two Matrices: ");
for (int r = 0; r < total.length; r++) {
for (int c = 0; c < total[r].length; c++)
System.out.printf("%7d", total[r][c]);
System.out.println();
}
// this is where I want to put the addition
public static int [][] add () {
}
You almost had it.
But note: In Java, you can't have another method inside a method. Therefore, the add() method must be outside the main() method.
Then you just have to adjust the parameters to accept the matrices and move the logic into the method:
public static void main(String[] args) {
/* ... */
int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;
int[][] matrix1 = new int[ir1][ic1];
int[][] matrix2 = new int[ir2][ic2];
int[][] total = add (matrix1, matrix2);
/* ... */
}
public static int[][] add (int[][] matrix1, int[][] matrix2) {
int total[][] = new int [matrix1.length][matrix1[0].length];
for (int r = 0; r < matrix1.length; r++) {
for (int c = 0; c < matrix2[r].length; c++) {
total[r][c] = matrix1[r][c] + matrix2[r][c];
}
}
return total;
}

Merging two 2D arrays (M + N)

I am a first year programming trying to solve this challenge that was given to us students at uni.
Question image
There's a typo at where it says (N + K) whereas in fact it's actually (M+K) columns.
My attempt for this question goes as follows
public static int[][] mergeArrays(int[][] arrayA, int[][] arrayB){
int rows = 3;
int columns = arrayA[0].length + arrayB[0].length;
int[][] mergedArray = new int[rows][columns];
int k = 0;
for (int i = 0; i < rows; i++)
{
for ( int j = 0 ; j < columns; j++)
{
try
{
mergedArray[i][j] = arrayA[i][j];
}
catch (ArrayIndexOutOfBoundsException e)
{
mergedArray[i][j] = arrayB[i][k];
k += 1;
}
}
}
return mergedArray;
}
public static void main(String [] args)
{
int [][] a1 = { {1,2,3,3,3} , {3,2,1,6,3} , {4,5,6,1,3} };
int [][] a2 = { {1,9,7,2,3} , {0,7,8,3,2} , {3,8,9,7,2} };
int[][] m = mergeArrays(a1,a2);
for (int[] x : m)
{
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}
}
The program doesn't work for some reason. I don't know what's wrong with my approach here. Would really appreciate if someone helps me out.
Without using any libraries, in a manual way, here is my working answer.
I didn't use any of them, since we were not allowed, when I was a student.
public class Main {
private static int[][] mergeArrays(int[][] a1, int[][] a2) {
// Count rows and cols length.
int rows = a1.length;
int cols_a1 = a1[0].length;
int cols_a2 = a2[0].length;
// Total number of cols
int cols = cols_a2 + cols_a1;
int [][] merged = new int[rows][cols];
for (int i = 0; i < rows ; ++i) {
for (int j = 0; j < cols_a1; ++j) {
merged[i][j] = a1[i][j];
}
// To not overwrite values,
// the trick is to add an offset, while assigning,
// which is the amount of elements (cols_a1) used by the previous loop.
// Basically, we are shifting the k-index by this constant,
// as to not overwrite the values assigned from the previous
// inner loop.
for (int k = 0; k < cols_a2; ++k) {
merged[i][cols_a1 + k] = a2[i][k];
}
}
// Return the merged array
return merged;
}
// I refactored your good printing code into a method, for readability.
private static void print2darray(int[][] array2d) {
for (int[] x : array2d) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a1 = {{1,2,3,3,3} , {3,2,1,6,3} , {4,5,6,1,3}};
int [][] a2 = {{1,9,7,2,3} , {0,7,8,3,2} , {3,8,9,7,2}};
int [][] merged = mergeArrays(a1, a2);
print2darray(merged);
}
}
The result is the same, as expected, from your question image:
1 2 3 3 3 1 9 7 2 3
3 2 1 6 3 0 7 8 3 2
4 5 6 1 3 3 8 9 7 2
Since you're a student I think to better if we give a hint, but since the solution is already there you can check this one as well:
public static int[] merge(int[] first,int[] second) {
return ArrayUtils.addAll(first, second);
}
public static void main(String[] args) {
int [][] a1 = { {1,2,3,3,3} , {3,2,1,6,3} , {4,5,6,1,3}};
int [][] a2 = { {1,9,7,2,3} , {0,7,8,3,2} , {3,8,9,7,2}};
int [][] a3 = new int[a1.length][];
for (int i = 0; i < a1.length; i++) {
a3[i] = merge(a1[i],a2[i]);
}
for (int[] ints : a3) {
StringJoiner joiner = new StringJoiner(",","[","]");
for (int i1 : ints) {
joiner.add(i1+"");
}
System.out.println(joiner.toString());
}
}
You are not merging it properly. Your logic is that if arrayA column index is out of bounds, you are adding from arrayB's columns. But what if that is also out of bounds, as in your case. Since you are always incrementing its index k. You could simply iterate over 2 arrays separately and merge into resulting array.
public static int[][] mergeArrays(int[][] arrayA, int[][] arrayB) {
int rows = 3;
int columns = arrayA[0].length + arrayB[0].length;
int[][] mergedArray = new int[rows][columns];
int k = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < arrayA[0].length; j++) {
mergedArray[i][k++] = arrayA[i][j];
}
for (int j = 0; j < arrayB[0].length; j++) {
mergedArray[i][k++] = arrayB[i][j];
}
k=0;
}
return mergedArray;
}

copy specific row from one 2D array to another without system.arraycopy

So I have to write a method that goes in array and goes from i to j rows and copies these rows to a new array. This is what I come up so far
public static void getRows(int i, int j, int[][] array){
int another[] = new int[j-i];
int n = 0;
for (int k = 0; k < array.length; k++){
while (i <= j){
if (k == i){
another[n] = array[k][0];
}
i++;
}
}
}
First, you aren't returning or printing anything. Second, to copy multiple rows from your input your returned array should be 2d (not 1d). Create a new int[][] of j - i rows. Then copy from array to the new array. Something like,
public static int[][] getRows(int i, int j, int[][] array) {
int[][] ret = new int[j - i][];
for (int k = i; k < j; k++) {
ret[k - i] = new int[array[k].length];
for (int m = 0; m < ret[k - i].length; m++) {
ret[k - i][m] = array[k][m];
}
}
return ret;
}
Then you can invoke it (and print the results) with something like
public static void main(String[] args) {
int[][] t = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
System.out.println(Arrays.deepToString(getRows(1, 3, t)));
}
Which outputs
[[2, 3], [4, 5]]
#Elliot I did it like this :)
public static int[][] getRows(int i, int j, int[][] array){
int[][] another = new int[j-i+1][];
while (i <=j){
for (int k = 0; k < another.length; k++){
another[k]=array[i];
i++;
}
}
return another;
}

Shuffling an array of cards

I'm having trouble shuffling an array of cards.I have about 3 shuffling methods in my program and none of them seem to work. If anyone can help me out with this, that would be great. I have a folder full of cards called 1.png, 2.png.... 52.png
public class CardButton extends JButton{
ImageIcon front, back;
boolean flipped;
public CardButton(ImageIcon front, ImageIcon back)
{
this.front = front;
this.back = back;
flipped = true;
flip();
}
public void flip()
{
flipped = !flipped;
if (flipped)
this.setIcon(front);
else
this.setIcon(back);
}
}
public class CardButtonPanel extends JPanel {
CardButton b, b1, b2, b3;
ImageIcon back, card1, card2, card3;
int count;
ActionListener taskPerformer;
Timer t1;
// Instantiating a new array
CardButton[] array;
public CardButtonPanel() {
int w = 72, h = 86;
back = new ImageIcon(getClass().getResource("b2fv.png"));
Image i1 = back.getImage();
Image i2 = i1.getScaledInstance(w, h, Image.SCALE_DEFAULT);
back.setImage(i2);
array = new CardButton[53];
List list = Arrays.asList(array);
Collections.shuffle(list);
for (int i = 1; i < array.length; i++) {
// int j = shuffle();
card1 = new ImageIcon(getClass().getResource(i + ".png"));
i1 = card1.getImage();
i2 = i1.getScaledInstance(w, h, Image.SCALE_DEFAULT);
card1.setImage(i2);
b1 = new CardButton(card1, back);
b1.addActionListener(new ButtonHandler1());
add(b1);
array[i] = b1;
}
taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
b1.flipped = true;
b1.flip();
}
};
t1 = new Timer(200, taskPerformer);
t1.setRepeats(false);
}
/*
* public void shuffle() { currentCard = 1; for (int i = 1; i<array.length;
* i++) { int second = randomNumbers.nextInt(52);
*
*
* } }
*
* public int randomInteger(int x, int y) { Random rInteger = new Random();
* // int IntegerRandom = rInteger.nextInt((x-y) +1) + x; int IntegerRandom
* = rInteger.nextInt(52); return IntegerRandom; }
*
* public void swapCards(int i, int j) { CardButton temp = array[i];
* array[i] = array[j]; array[j] = temp; }
*
* public void shuffle() { for (int i = 0; i < array.length; i++) { int j =
* randomInteger(i, array.length - 1); } }
*/
/*
* public static int[][] randomize(int rows, int cols) { int[][] temp = new
* int[4][13]; Random randomize = new Random(); // int stuff; for (int i =
* 0; i < temp.length; i++) { // temp[i] = new int[cols]; for (int j = 0; j
* < temp[i].length; j++) temp[i][j] = (int) ((Math.random()) * (rows *
* cols)); // stuff = randomize.nextInt(52); } return temp; }
*/
private class ButtonHandler1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Need to create for loop for printing out how many attempts
int i = 0;
System.out.println(i + 1);
CardButton tempCB = (CardButton) e.getSource();
if (!tempCB.flipped && !t1.isRunning()) {
tempCB.flip();
count++;
}
if (count > 1) {
t1.start();
count = 0;
}
}
}
}
I actually attempted to create another shuffle class.
public class Shuffle {
public static int[] shuffleCards(int[] cards) {
for (int i = 1; i < cards.length; i++) {
int rand = new Random().nextInt(cards.length-i)+i;
int temp = cards[i];
cards[i] = cards[rand];
cards[rand] = temp;
}
return cards;
}
}
I don't know how to implement this into my CardButtonPanel, so I'm not too sure if it works or not.
Use best Fisher Yates shuffling algorithm
Sample code :
import java.util.*;
class Test
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
You can do shuffling in two ways:-
1)Fisher Yates Algorithm is one of the great choice.
2)Else You can create the list of cards and make its collection. Then use Collections.shuffle
link for tutorial. One of easiest way I've used so far.
Take look in this question for your ease.
question

Merge Sort Algorithm Code

This is code for Merge Sort using the Java programming language.
Where there is an error, it does not give me the correct output.
Is it possible to help me to resolve? Thank you.
I want to work with arrays of type integer.
import java.util.Arrays;
public class Excersize5 {
public void MergeSort(int[] Arr) {
int N = Arr.length;
if (N > 1) {
int Middle = (N) / 2;
int[] A1 = LeftElement(Arr);
int[] A2 = RightElement(Arr);
MergeSort(A1);
MergeSort(A2);
Merge(Arr, A1, A2);
}
}
public void Merge(int[] Result, int[] A1, int[] A2) {
int i = 0;
int j = 0;
for (int k = 0; k < Result.length; k++) {
if (A1[i] >= A2[j] || (i < A1.length &&
A1[i] <= A2[j])) {
Result[k] = A1[i];
i++;
} else {
Result[k] = A2[j];
j++;
}
}
}
public int[] LeftElement(int[] Total) {
int NL = Total.length / 2;
int[] L = new int[NL];
for (int p = 0; p < NL; p++) {
L[p] = Total[p];
}
return L;
}
public int[] RightElement(int[] Total) {
int NL = Total.length / 2;
int NR = Total.length - NL;
int[] R = new int[NR];
for (int q = 0; q < NR; q++) {
R[q] = Total[q];
}
return R;
}
public static void main(String[] args) {
Excersize5 e5 = new Excersize5();
int[] r = {5, 6, 7, 8, 1, 7};
e5.MergeSort(r);
System.out.print(r);
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at practical4.Excersize5.Merge(Excersize5.java:22) at
practical4.Excersize5.MergeSort(Excersize5.java:14) at
practical4.Excersize5.MergeSort(Excersize5.java:13) at
practical4.Excersize5.MergeSort(Excersize5.java:12) at
practical4.Excersize5.main(Excersize5.java:55) Java Result: 1 BUILD
SUCCESSFUL (total time: 1 second)
You could just use a Vector instead will make it much easier to do. It's because your calling things outside your array length, all of them, and you never return the array result which you should do in some method

Categories