Swapping two 2D Arrays of integers - java

I am looking to completely swap the contents of two arrays, not swap integers within the array, but across the two. I am just very confused as to where to begin.
ie...
Matrix a = 1 2 3 Matrix b = 3 2 1
4 5 6 6 5 4
I wish for it to output as
Matrix a = 3 2 1 Matrix b = 1 2 3
6 5 4 4 5 6
If that makes sense. Sorry! My code is below for the beginning part of creating the array and filling it with Random, I didn't include the tester because I'm simply inputting which array to use for the calculation, and I am not ready to do that yet.
import java.util.Random;
public class Matrix {
private int[][] matrix;
private int rows;
//constructors
public Matrix() {
matrix = new int[3][3];
rows = 3;
}
public Matrix(int size) {
matrix = new int[size][size];
rows = size;
}
//Mutators
public void fill() {
Random r = new Random();
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.rows; j++) {
this.matrix[i][j] = r.nextInt();
}
}
}
public void clear() {
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.rows; j++) {
this.matrix[i][j] = 0;
}
}
}
public static void swap(Matrix a, Matrix B) {
}
}

You can simply swap the matrix fields:
public static void swap(Matrix a, Matrix b) {
int[][] tmp = a.matrix;
a.matrix = b.matrix;
b.matrix = tmp;
}
You should probably first check that the matrices have the same size. Alternatively, also swap the value of the rows field between a and b.

Related

The code isn't printing anything, and I can't find the problem

The goal of this is to print out the size of the blob when given a set of coordinates within a 10 x 10 matrix. It's written in java and the point of the exercise was to use recursion to find each of the 1's in the blob. (Any 1's that are connected to the original coordinate by going up, down, left, or right.
Example:
The Blob
0010010010
0100100101
1001001010
0011110101
0111101010
1001010100
0010101101
0101010010
1010100100
0101001000
The Coordinates
1 1
2 3
5 7
The Output
1
10
3
import java.util.*;
public class BlobsRunner
{
public static void main(String[] args)
{
//test the Blob class to make sure
//it works as intended
Blobs bloop = new Blobs(10, 10);
//call both constructors
Scanner reader = new Scanner(System.in);
System.out.println("Row: ");
int r = reader.nextInt();
System.out.println("Colum: ");
int c = reader.nextInt();
bloop.recur(r, c);
bloop.getBlobCount();
//print the newly instantiated Blob
bloop.toString();
//call methods - print out the size of the blob
//bloop.getBlobCount();
}
}
//next file
import java.util.*;
public class Blobs
{
private int[][] mat; //grid of 1s and 0s
private int count;
private int[][] visited;
public Blobs( int rows, int cols )
{
//set count to 0
count = 0;
//point mat at new mat size rows X cols
mat = new int[rows][cols];
//loop through mat
for(int a = 0; a < rows; a ++)
{
for(int b = 0; b< cols; b++)
{
mat[a][b] = (int)Math.random();
}
}
//fill in mat with 1s and 0s
//use Math.random()
visited = new int[rows][cols];
}
public Blobs( int rows, int cols, String s )//what does s mean?
{
//set count to 0
count = 0;
//point mat at new mat size rows X cols
mat = new int[rows][cols];
for(int a = 0; a < rows; a ++)
{
for(int b = 0; b< cols; b++)
{
mat[a][b] = (int)Math.random();
}
}
visited = new int[rows][cols];
//loop through mat
//load in the 1s and 0s from s
}
public void recur(int r, int c)
{
//add a base case
if(mat[r][c]==0)
{
//return;
}
if(visited[r][c] == 5)//figure out, make sure it doesn't count if it does
{
//return;
}
visited[r][c] = 5;
//mark current pos as visited
count++;
//increase count by 1
//add in 4 recursive calls
//UP
if(mat[r+1][c] == 1 && visited[r+1][c] != 5)
{
recur(r+1, c);
}
//DOWN
if(mat[r-1][c] == 1 && visited[r-1][c] != 5)
{
recur(r-1,c);
}
//LEFT
if(mat[r][c-1] == 1 && visited[r][c-1] != 5)
{
recur(r,c-1);
}
//RIGHT
if(mat[r][c+1] == 1 && visited[r][c+1] != 5)
{
recur(r,c+1);
}
}
public int getBlobCount()
{
//return count
return 0;
}
public String toString()
{
//you will need nested loops
//you will need a local string variable
for(int a = 0; a < mat.length; a++)
{
for(int b = 0; b < mat[a].length; b++)
{
System.out.print(mat[a][b]);
}
System.out.println();
}
return "";
}
}
Math.random() function returns double values between 0 to 1 so when you try to convert it to (int) it becomes 0. So all of your matrix is 0. And since you are doing nothing at recur() function its print 10x10 0 matrix.
Try adding import java.util.Random; then Random r = new Random(); and when you assign random numbers mat[a][b] = r.nextInt(2);
As #Fatih Aslan noted, Math.random() produces a double between 0.0 and 1.0, not including 1.0. When parsed to an int, Java will always produce the value 0.
If you do not want to use the java.util.Random library you can multiply the value you are obtaining from Math.random() by the difference between the highest and lowest random numbers you would like to generate, plus 1. If you want your lowest possible random number to be greater than 0, add that number to the output of Math.random().
For example, (int)(2 + (Math.random() * 9)) will produce random integers from 2 to 10 including 2 and 10.

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;
}

How to find largest 10 elements in multi dimentional array?

I hope this will print one largest value. but it need 10 largest elements in an 3D array.
public class foo{
Public static void main(String[] args){
int row,col,dep=3;
int[][][] value=new int[row][col][dep];
/* insert the value from user or initialize the matrix*/
int max=0;
for(row=0;row<3;row++)
for(col=0;col<3;col++)
for(dep=0;dep<3;dep++)
if(value[row][col][dep]>max)
max=value[row][col][dep];
System.out.println(max);
}
}
You can add all integers into a List<Integer>, sort it, and then get the X max numbers of it:
public class foo {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
List<Integer> listWithAll = new ArrayList<>();
/* insert the value from user or initialize the matrix*/
int max = 0;
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
for (dep = 0; dep < 3; dep++)
listWithAll.add(value[row][col][dep]);
listWithAll.sort(Collections.reverseOrder());
for (int i = 0; i < 10; i++) {
System.out.println(listWithAll.get(i));
}
}
}
which prints:
15 10 0 0 0 0 0 0 0 0
or using Java 8 streams only:
List<Integer> max10 = listWithAll.stream()
.sorted(Collections.reverseOrder())
.limit(10)
.collect(Collectors.toList());
max10.forEach(System.out::println);
Here is a way to do it with streams. I used a complete 2 x 2 x 2 array to make it easier but it would work with any int[][][] array. Instead of using nested loops, I just flatMapped the arrays.
Initialize the array.
int[][][] v = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
Now get the top4 values (or top N values) and put them in a list.
int top4 = 4;
List<Integer> top4Max =
Arrays.stream(v).flatMap(Arrays::stream).flatMapToInt(
Arrays::stream).boxed().sorted(
Comparator.reverseOrder()).limit(top4).collect(
Collectors.toList());
System.out.println(top4Max);
Prints
8 7 6 5
The Arrays.stream strips one level of array. The flatMap takes those and further flattens them into a single dimenion array. The flatMapToInt flattens that into a stream of ints where they are sorted and processed into a limited collection.
If required, you could also put them in an array instead of a list.
Alternatively, one could create a small array and use it as with a normal findmax function.
public class Array_3D {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
int[] topten = new int[10]; //array to hold max values
int count = 0;
int candidate = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < dep; k++) {
if (count < 10) { //start with first ten values
topten[count] = value[i][j][k];
count++;
}
else {
candidate = value[i][j][k];
for (int x = 0; x < 10; x++) { //loop for loading top values
if (candidate > topten[x]) {
topten[x] = candidate;
break; //exit on first hit
}
}
}
}
}
}
for (int i = 0; i < 10; i++) {
System.out.print(topten[i] + " ");
}
System.out.println();
}
}
I don't know which method is faster for large 3D arrays; here we have to run a small loop at every point in the 3D array, vs creating an entirely new list and sorting it. Clearly this wins in memory usage, but not sure about speed. [Edit note this returns an unsorted array of the top ten values as is].

java array for zigzag works, but tester keeps telling me there's an error?

I have this line of code to create a zigzag array, its fairly simple and I already have the code for it. here's the summary of the question:
This method creates and returns a new two-dimensional integer array, which in Java is really just a one-dimensional array whose elements are one-dimensional arrays of type int[]. The returned array must have the correct number of rows that each have exactly cols columns. This array must contain the numbers start, start + 1, ..., start + (rows * cols - 1) in its rows in order, except that the elements in each odd-numbered row must be listed in descending order.
For example, when called with rows = 4, cols = 5 and start = 4, this method should create and return the two-dimensional array whose contents are
4 5 6 7 8
13 12 11 10 9
14 15 16 17 18
23 22 21 20 19
I've tried talking with my colleagues but they can't spot the problem too
public class P2J1
{
public static int[][] createZigZag(final int rows, final int cols, int start)
{
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = start;
start++;
}
}
return array;
}
}
/// heres the tester program
#Test public void testCreateZigZag() {
Random rng = new Random(SEED);
CRC32 check = new CRC32();
for(int i = 0; i < TRIALS; i++) {
int rows = rng.nextInt(20) + 1;
int cols = rng.nextInt(20) + 1;
int start = rng.nextInt(100);
int[][] zig = P2J1.createZigZag(rows, cols, start);
assertEquals(rows, zig.length);
for(int j = 0; j < rows; j++) {
assertEquals(cols, zig[j].length);
for(int e: zig[j]) { check.update(e); }
}
}
assertEquals(3465650385L, check.getValue());
}
Your column index always goes from 0 to cols-1, in that order. You need to alternate the order every other row.
You can do this by using variables for the start, end, and increment of the inner loop and assign those variables based on the row index being odd or even.
Something like this (untested):
public static int[][] createZigZag(final int rows, final int cols, int start) {
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
boolean backwards = ((i & 1) == 1);
final int jStart = backwards ? cols-1 : -1;
final int jEnd = backwards ? 0 : cols;
final int jStep = backwards ? -1 : 1;
for (int j = jStart; j != jEnd; j += jStep) {
array[i][j] = start;
start++;
}
}
return array;
}
You could also just write two different inner loops, selected on the same condition. One would fill starting from 0, the other would fill starting from cols-1 and going backwards.
public static int[][] createZigZag(final int rows, final int cols, int start) {
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
if ((i & 1) == 1) {
for (int j = cols-1; j >= 0; j--) {
array[i][j] = start;
start++;
}
} else {
for (int j = 0; j < cols; j++) {
array[i][j] = start;
start++;
}
}
}
return array;
}

Java - Getting compile error incompatible types int can't be converted to [][] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Having trouble understanding compile error. Main should be left unchanged. I believe MakeandFillMatix method is the problem and I can't figure it out. I think it's how I created the method.
import java.util.*;
/*
*/
public class TesterProject
{
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);
printMatrix(m);
}
public static int getMatrixSize()
{
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextint();
return n;
}
public static void makeAndFillMatrix(int [][] r)
{
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j]= rand;
}
}
return r;
}
public static void printMatrix(int [][] matrix)
{
for(int r = 0; r < matrix.length; r++)
{
for(int c = 0; c < matrix[r].length; c++)
{
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Hint
You have many problems in your code :
int n = S.nextint(); it should be int n = S.nextInt(); with Upper I
You can't compare an int with an array for (int j = 0; j < r; j++) { i think you need this for (int j = 0; j < i; j++) {
void makeAndFillMatrix(int[][] r) it not return any thing, and your return an array in the end.
makeAndFillMatrix(int[][] r) take an array of 2D and not an int int[][] m = makeAndFillMatrix(n);
Fix this problem and your problem is solve :)
EDIT
Then you have to change your code to be like this :
public static void main(String[] args) {
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);//<<<----Problem 4
printMatrix(m);
}
public static int getMatrixSize() {
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextInt();//<<--------------Problem 1
return n;
}
public static int[][] makeAndFillMatrix(int n) {//<<<---Problem 3
Random generator = new Random(5);
int[][] r = new int[n][n];
int rand = generator.nextInt(10);
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < i; j++) {//<<<-----------Problem 2
r[i][j] = rand;
}
}
return r;
}
public static void printMatrix(int[][] matrix) {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
Change makeAndFillMatrix(int[][] r) to makeAndFillMatrix(int r)
You want the matrix size, which is an integer, so take integer instead of a multidimensional array.
And in the for loop after that, change r.length to just r
Change void to int [][] in the method declaration.
In the method add a line int[][] q; and change r[i][j] = rand to q[i][j] = rand
And change return r to return q
The error you are receiving is due to you calling
int[][] m = makeAndFillMatrix(n);
in your main method.
You set n as an int in the line above, meaning n is a number, BUT, makeAndFillMatrix(int[][]) takes in a 2d array of ints. (A 2d array is a matrix, by the way.)
If you want to make a matrix of the size entered in by the user, then instead of passing n into your makeAndFillMatrix method, you would need to pass in a matrix of size n. You can do this in two ways. Option 1 is to pass in the matrix to your makeAndFillMatrix method like so:
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(new int[n][n]); // new int matrix of size n
printMatrix(m);
}
Or (the more conventional way, in my opinion), you can give makeAndFillMatrix the size of the matrix (like you are doing), and you can have makeAndFillMatrix make the array:
public static void makeAndFillMatrix(int matrixSize)
{
int[][] r = new int[matrixSize][matrixSize];
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r[i].length; j++) //~~~I modified this line as well~~~
{
r[i][j]= rand;
}
}
return r;
}
Anyways, you can take your pick at which approach you want to take to this problem, but regardless, I noticed that your makeAndFillMatrix method had an error. I fixed it and wrote //~~~I modified this line as well~~~
Your inner for loop originally said for(int j = 0; j < r; j++), but r is a matrix. For the inner loop, you would want to increase j until it has reached the size of the current row you are on in the matrix, so I changed that line as well. (Your inner loop was correct in your printMatrix method.) Whichever approach you take for your first issue, the inner loop in your makeAndFillMatrix method will need to be modified as well.
I hope this helps!
You are trying to cast 'int' (in the main function) to an 'int[][]' (the parameter of 'makeAndFillMatrix'. Also, makeAndFillMatrix returns 'void'.
I believe you want to rewrite your function to something like this:
public static int[][] makeAndFillMatrix(int r)
{
// Create a new matrix
int[][] matrix = new int[r][r];
// Get a random value
Random generator = new Random(5);
int rand = generator.nextInt(10);
// Assign random value to each cell of the matrix
for(int i = 0; i < r; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j] = rand;
}
}
// Return the matrix
return matrix;
}

Categories