swap between rows in a 2D array in java - java

I am working on a java code that should swap between two 2d rows and I have completed it but I want to check if my work is correct and if it needs any modification to do.
import java.util.*;
public class Main {
public static void printMatrix(int[][] matrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
public static void exchangeAnyTwoRows(int[][] matrix,
int K, int L)
{
for (int i = 0; i < matrix[0].length; i++) {
int temp = matrix[K - 1][i];
matrix[K - 1][i] = matrix[L - 1][i];
matrix[L - 1][i] = temp;
}
printMatrix(matrix);
}
public static void main(String[] args)
{
int K = 2, L = 3;
int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } };
exchangeAnyTwoRows(mat, K, L);
}
}
any help would be really appreciated.

Seems like you are swapping each element in the two rows. I don't think you need to do it in that way. You can just swap the rows at once:
public static void exchangeAnyTwoRows(int[][] matrix, int r1, int r2) {
int[] temp = matrix[r1];
matrix[r1] = matrix[r2];
matrix[r2] = temp;
}
One other comment is that the above code will throw ArrayIndexOutOfBoundsException. The reason is that your row index starts from 1. You may decrease each index inside the method, however, just use 0 based indexes would be better to avoid confusion.
So, you may want to modify the values of K and L to 1 and 2, respectively.

Related

Encountering IndexOutOfBoundsException while implementing ArrayList function in Java to reverse array'

Given an array/list 'ARR' of integers and a position ‘M’. You have to reverse the array after that position. You do not need to print anything, it has already been taken care of. Just implement the given function.
This is my problem statement. The following is the code I tried implementing.
public class Solution
{
public static void reverseArray(ArrayList<Integer> arr, int m)
{
int i=0,p=1;
int n=arr.size();
ArrayList<Integer> reverseArray=new ArrayList<Integer>();
for(int j=0;j<n;j++){
reverseArray.add(0);
}
for(;i<=m;i++){
reverseArray.set(i, arr.get(i));
}
for(;i<n;i++){
reverseArray.set(i,arr.get(n-p));
}
for(int j=0;j<n;j++){
arr.set(i,reverseArray.get(i));
}
}
}
I'm getting runtime error as
Exception in thread main java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Solution.reverseArray(Solution.java:21)
at Runner.executeAndPrintOutput(Runner.java:50)
at Runner.main(Runner.java:61)
Content of arr={1, 2, 3, 4, 5, 6}
First of all, your problem is that in the last loop you are using i, instead of j. Second, your logic seems faulty to me. Here is a simple solution I've programmed -
public static void reverseArray(ArrayList<Integer> arr, int m) {
int i = 0, p = 1;
int n = arr.size();
ArrayList<Integer> reverseArray = new ArrayList<Integer>();
for (i = m; i < n; i++){
reverseArray.add(arr.get(n - i - 1 + m));
}
for (i = m; i < n; i++){
arr.set(i, reverseArray.get(i - m));
}
}
May be something like this? remove the print statements before submitting.
private void reverseArray(List<Integer> src, int pos) {
int j = 0;
Integer[] srcArr = new Integer[src.size()];
Integer[] tarArr = new Integer[src.size()];
src.toArray(srcArr);
src.toArray(tarArr);
for(int i=pos; i<srcArr.length; i++) {
j++;
int tarIndex = srcArr.length-j;
int tarEle = srcArr[tarIndex];
tarArr[i] = tarEle;
}
for(int i = 0; i<tarArr.length; i++) {
System.out.print(tarArr[i] + " ");
}
}

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 can I copy a 2D array and add a new row to store the sum of the columns in Java?

Basically I have a function that receives a two dimensional array, adds an extra row and then calculates the sum of the columns and stores the results for each individual column in the extra row that was created earlier. Here is my code:
public static int[][] sum(int[][] array) {
int tempArray[][] = new int[array.length + 1][array[0].length];
for (int column = 0; column < tempArray[0].length; column++) {
int total = 0;
for (int row = 0; row < tempArray.length; row++) {
total += tempArray[row][column];
}
tempArray[tempArray.length][column] = total;
}
return tempArray;
}
So when I run a for loop to print the results I get an ArrayIndexOutOfBounds error for some reason that refers to the function. I think my logic is correct but I can't seem to make it work. For some more context the values for the array are entered by the user. Thank you whoever will answer !
You are getting ArrayIndexOutOfBounds because you are accessing the index more than the bound of array in the below line:
tempArray[tempArray.length][column] = total;
Replace it with following the line would solve your problem:
tempArray[tempArray.length - 1][column] = total;
However your code still won't work as your summation logic have bug. You are calculating the total by the following line.
total += tempArray[row][column];
But your tempArray doesn't have any value but zeros. To solve this make sure you initiate the tempArray by the values of array's like following:
int tempArray[][] = new int[array.length + 1][array[0].length];
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
tempArray[i][j] = array[i][j];
}
}
Hopefully this will solve your problem. Happy coding!
You have not initialised the tempArray[][].
tempArray[tempArray.length][column] = total
change it to
tempArray[tempArray.length-1][column] = total
this will resolve the index out of bound issue.
public static int[][] sum(int[][] array) {
int tempArray[][] = new int[array.length + 1][array[0].length];
for (int column = 0; column < array[0].length; column++) {
int total = 0;
for (int row = 0; row < array.length; row++) {
tempArray[row][column] = array[row][column];
total += array[row][column];
}
tempArray[tempArray.length-1][column] = total; // resolves the index out of bound issue
}
return tempArray;
}
Mentioned solutions will not work in case if rows have different length. For example, if input array is
int[][] input = new int[][] { { 1, 2, 3 }, { 2, 3 } };
This solution eliminates such problem
public static int[][] sum(int[][] array) {
int[][] tempArray = new int[array.length + 1][];
int maxLength = 0;
for (int i = 0; i < array.length; i++) {
tempArray[i] = Arrays.copyOf(array[i], array[i].length);
maxLength = Math.max(maxLength, array[i].length);
}
tempArray[tempArray.length - 1] = new int[maxLength];
for (int i = 0; i < maxLength; i++ ) {
int total = 0;
for (int[] row : tempArray) {
if (i <= row.length - 1) {
total += row[i];
}
}
tempArray[tempArray.length - 1][i] = total;
}
return tempArray;
}
And the test
public static void main(String[] args) {
int[][] arr = new int[][] { { 1, 2, 3 }, { 2, 3 } };
System.out.println(Arrays.deepToString(sum(arr)));
// Output
// [[1, 2, 3], [2, 3], [3, 5, 3]]
}

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

Finding intersection of two sorted arrays in Java

public class intersect {
public static void find(int[] a, int[] b, int[] acc)
{
int position = 0;
for (int j = 0; j < a.length; j++) {
for (int k = 0; k<b.length; k++) {
if (a[j] == b[k]) {
acc[position] = b[k];
position++;
}
}
}
System.out.println(java.util.Arrays.toString(acc));
}
public static void main (String[] s)
{
int[] acc = new int[2];
int[] a = {1,2,3};
int[] b = {2,3,4};
find(a, b, acc);
}
}
I have written the above code to solve the problem.
But if you see, the function is very limited because I have to change the length of the acc every time. That means I have to know how many elements are intersecting. In this case, the array {1,2,3} and {2,3,4} have {2,3} in common, so the length of the acc would be 2.
I am sure there are millions of ways of tackling this problem, but I cannot seem to think of a way of fixing this.
Please help!
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find() method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
To find intersection of 2 sorted arrays, follow the below approach :
1) Use two index variables i and j, initial values with 0
2) If array1 is smaller than array2 then increment i.
3) If array1 is greater than array2 then increment j.
4) If both are same then print any of them and increment both i and j.
check this link for more information
https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
public class FindIntersection {
static void findInterSection(int array1[], int array2[], int array1NoOfElements, int
array2NoOfElements) {
int i = 0, j = 0;
while (i < array1NoOfElements && j < array2NoOfElements) {
if (array1[i] < array2[j]) {
i++;
} else if (array2[j] < array1[i]) {
j++;
}
// if both array elements are same
else {
System.out.println(array2[j++] + " ");
i++;
}
}
}
public static void main(String[] args)
{
int myFirstArray[] = { 1, 2, 4, 5, 5 };
int mySecondArray[] = { 2, 3, 5, 7 };
int m = myFirstArray.length;
int n = mySecondArray.length;
findInterSection(myFirstArray, mySecondArray, m, n);
}
}
Make your intersection array's size the size of the smaller of your original arrays. That way, you won't ever have to increase it's capacity.
Then you can use Arrays.copy to transfer your results into an appropriately sized array.
Not sure if this is the best solution, but you don't need to hard-code the size of the intersection ahead of time (which is one thing you were concerned about).
As you iterate through both arrays, you can add elements found in both sets to a StringBuilder (along with some delimiter, I used a comma in the example below). Once you're finished, you can call toString() & then split() using the delimiter afterwards to get a String[]. At that point, you can put convert those String objects to int primitives & return an int[].
public class Scratch {
public static void main(String[] s) {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] intersection = findIntersection(a, b);
System.out.println(Arrays.toString(intersection));
}
public static int[] findIntersection(int[] a, int[] b) {
StringBuilder intersectionStringBuilder = new StringBuilder();
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (a[j] == b[k])
intersectionStringBuilder.append(a[j] + ",");
}
}
String[] intersectionStringArray = intersectionStringBuilder.toString().split(",");
int[] intersection = new int[intersectionStringArray.length];
for (int current = 0; current < intersectionStringArray.length; current++) {
intersection[current] = Integer.parseInt(intersectionStringArray[current]);
}
return intersection;
}
}
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j] && !index.contains(j)){
list.add(arr1[i]);
index.add(j);
break;
}
}
}
int result[]=new int[list.size()];
int k=0;
for(int i:list){
result[k]=i;
k++;
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
return result;
}

Categories