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

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

Related

How to create an new one dimensional array with elements of a 2d array and return it?

I need tp create a new array with the elements of a 2d array in java. However, it only adds the last number of the 2d array which results in an array of the same value.
public class MyClass {
public static int[] collect(int[][] array) {
int[] nA = new int[10];
for (int i = 0; i < 7; i++) {
for (int[] y : array) {
for (int x : y) {
nA[i] = x;
}
}
}
return nA;
}
public static void main(String args[]){
int[][] array = {{1}, {2,3}, {4,5,6}, {7}, {}, {}, {8,9,10}};
int[] z = collect(array);
for (int x : z) {
System.out.print(x + " ");
}}
}
You have an outer loop for (int i = 0; i < 7; i++) that is causing the issues.
The value of "i" does not change and the whole array is traversed '7' times and the last element is persisted at the index specified by 'i'. And the whole thing repeats for "i+1". Ultimately what is printed is the last element of the last sub-array multiple times. That is not what you want.
Please look at the following code. Note, we also get the length of the array dynamically from the argument (never hardcode for you would like your method to be suitable for all sizes).
public static int[] collect(int[][] array) {
// calculate length
int length = 0;
for (int a[] : array) {
length += a.length;
}
int[] nA = new int[length];
// for (int i = 0; i < 7; i++) {
int i=0;
for (int[] y : array) {
for (int x : y) {
nA[i++] = x;
}
}
// }
return nA;
}
public static void main(String args[]) {
int[][] array = {{1}, {2, 3}, {4, 5, 6}, {7}, {}, {}, {8, 9, 10}, {11}};
int[] z = collect(array);
for (int x : z) {
System.out.print(x + " ");
}
}
Prints:
1 2 3 4 5 6 7 8 9 10 11
public class MyClass {
public static int[] collect(int[][] array) {
int[] nA = new int[10];
int k=0;
for (int i = 0; i < array.length; i++) {
for (int j=0; j< array[i].length;j++) {
nA[k] = array[i][j];
k++;
}
}
return nA;
}
public static void main(String args[]){
int[][] array = {{1}, {2,3}, {4,5,6}, {7}, {}, {}, {8,9,10}};
int[] z = collect(array);
for (int x : z) {
System.out.print(x + " ");
}}
}
Change your code as above. However to work this solution you have know the size of new array beforehand. No need of 3 for loops. Variable k use to identify the new array current index.
You only need two for loops to go through a 2D Array.
Furthermore it is not a good idea to hard code the length of the array you return. If you don't want to use any other data structures in addition, I think you have no other chance for calculating the length of the new array than iterating over the whole 2D array to calculate the number of elements, initialize the new one with that size and than iterating again over the 2D array to fill the new one.
In code:
public static int[] collect(int[][] array) {
int numberOfElements = 0;
for(int i = 0; i < array.length; i++)
numberOfElements += array[i].length;
int[] nA = new int[numberOfElements];
int fillingCounter = 0;
for (int i = 0; i < array.length; i++) {
int[] current = array[i];
for (int j = 0; j < current.length; j++) {
nA[fillingCounter] = array[i][j];
fillingCounter++;
}
}
return nA;
}
Alternatively, you can use a dynamic data structure (for example java.util.LinkedList) and then convert it to an array (for example with the toArray method)

Remove a Column from a 2D Array

I have little problem with removing col from a 2d array.
The goal is to remove from every row specific index "2" and give it back.
Its how it need to be
I made it but got little problem with 0 at the end.
Its how I got
private static void removeEntry(int[][] workArray, int col) {
int row = workArray.length;
//largest row count
int max = 0;
int tempNum = 0;
for (int[] ints : workArray) {
tempNum = 0;
for (int j = 0; j < ints.length; j++) {
tempNum++;
if (tempNum > max) {
max = tempNum;
}
}
}
int [][] newArray = new int[row][max];
for(int i = 0; i < row; i++) {
for(int j = 0; j < max; j++) {
if(j < col && j < workArray[i].length) {
newArray[i][j] = workArray[i][j];
}else if (j == col) {
// Do nothing
} else if (j > col && j < workArray[i].length) {
newArray[i][j - 1] = workArray[i][j];
}
}
}
for (int i = 0; i < workArray.length; i++) {
for (int j = 0; j < workArray[i].length; j++) {
workArray[i][j] = newArray[i][j];
}
}
Then I tried to remove 0 but don't work
int remIndex = 0;
for (int i = 0; i < workArray.length; i++) {
for (int j = remIndex; j < workArray[i].length-1; j++) {
if(workArray[i][j] == remIndex){
workArray[i][j] = workArray[i][j + 1];
}
}
}
An array is a container of data that occupies a contiguous block of memory, its size should be defined when the array is being instantiated and can't be changed.
If you need an array of smaller or greater length, then you need to create a new one and copy all previously added elements that should be retained.
There's also no such thing in Java as "2D" arrays, we can create a nested array, i.e. an array containing other arrays.
And similarly to how we can reassign an integer value at a particular index in a plain array int[], we can change a reference in the array of arrays, i.e. we can make it point to another (newly created) array.
And that's what is required according to do in your assignment since the method is void. I.e. the given array needs to be changed by replacing all of its "rows", that greater or equal in length than the given column to remove col, with a new array that will retain all the previous element except for the one at index col.
private static void removeEntry(int[][] workArray, int col) {
for (int row = 0; row < workArray.length; row++) {
if (workArray[row].length <= col) { // no need to change anything
continue;
}
int newLength = workArray[row].length - 1;
int[] newRow = new int[newLength]; // creating a new row shorter by 1
for (int oldCol = 0, newCol = 0; oldCol < workArray[row].length; oldCol++, newCol++) {
if (oldCol == col) { // skipping the target column
newCol--; // newCol would be incremented automatically at the end of the iteration, but we want it to remain the same
continue;
}
newRow[newCol] = workArray[row][oldCol];
}
workArray[row] = newRow; // reassigning the row
}
}
main()
public static void main(String[] args) {
int[][] testArr =
{{1, 2},
{1, 2, 3},
{1, 2, 3, 4}};
removeEntry(testArr, 2);
// printing the testArr
for (int[] arr: testArr) {
System.out.println(Arrays.toString(arr));
}
}
Output:
[1, 2]
[1, 2]
[1, 2, 4]
A link to the Online Demo
If you've made the method to be void by mistake, you are required to return a new array, i.e. the return type int[] (check the requirements of your assignment carefully). Then a minor change needs to be applied to the logic explained and implemented above: every array should be replaced with a new one and then placed into the newly created resulting array.
Note Arrays.copyOf() allows creating a duplicate of the hole array, and System.arraycopy() can help you to copy the elements in the given range from one array into another, but because you are working on an assignment I suggest you to do it manually with loops because you are expected to demonstrate the knowledge on how to manipulate with arrays, not the knowledge of special utility features (unless otherwise specified in the assignment).
private static int[][] removeEntry(int[][] workArray, int col) {
int[][] result = new int[workArray.length][];
for (int row = 0; row < workArray.length; row++) {
int newLength = col < workArray[row].length ? workArray[row].length - 1 : workArray[row].length;
int[] newRow = new int[newLength];
for (int oldCol = 0, newCol = 0; oldCol < workArray[row].length; oldCol++, newCol++) {
if (oldCol == col) {
newCol--;
continue;
}
newRow[newCol] = workArray[row][oldCol];
}
result[row] = newRow; // reassigning the row
}
return result;
}
main()
public static void main(String[] args) {
int[][] testArr =
{{1, 2},
{1, 2, 3},
{1, 2, 3, 4}};
int[][] newArr = removeEntry(testArr, 2);
// printing the testArr
for (int[] arr: newArr) {
System.out.println(Arrays.toString(arr));
}
}
Output:
[1, 2]
[1, 2]
[1, 2, 4]
A link to the Online Demo
Here is my approach on this. I used System.arraycopy() to copy the array up to the removed column and from directly after the removed column to the end. This way, we remove the column completely from the array.
private static int[][] removeEntry(int[][] workArray, int col) {
int[][] resultArray = new int[workArray.length][];
int index = 0;
for (int[] row : workArray) {
if (row.length - 1 < col) {
resultArray[index] = row;
index++;
continue;
}
int[] arrayCopy = new int[row.length - 1];
System.arraycopy(row, 0, arrayCopy, 0, col);
System.arraycopy(row, col + 1, arrayCopy, col, row.length - col - 1);
resultArray[index] = arrayCopy;
index++;
}
return resultArray;
}
Arrays are of fixed size. At the time of initializing array, a default value is stored in it. Here, 0 is stored as default. So I would suggest you to not initialize "col" as "max" but rather do it in for loop like this :-
int [][] newArray = new int[row][];
for(int i = 0; i < row; i++) {
if(col <= workArray[i].length){
newArray[i] = new int[workArray[i].length-1]; //initialize it here
}
for(int j = 0; j < workArray[i].length; j++) {
if(j < col) {
newArray[i][j] = workArray[i][j];
}else if (j == col) {
// Do nothing
} else if (j > col) {
newArray[i][j - 1] = workArray[i][j];
}
}
}
return newArray;
You are also supposed to return modified array as we can't changed the size of array and thus we had to create a new one ( newArray ). So do change the method definition as :-
private static int[][] removeEntry(int[][] workArray, int col)
Finally, whole method would look like :-
private static int[][] removeEntry(int[][] workArray, int col) {
int row = workArray.length;
//largest row count
int [][] newArray = new int[row][];
for(int i = 0; i < row; i++) {
if(col <= workArray[i].length){
newArray[i] = new int[workArray[i].length-1]; //initialize it here
}
for(int j = 0; j < workArray[i].length; j++) {
if(j < col) {
newArray[i][j] = workArray[i][j];
}else if (j == col) {
// Do nothing
} else if (j > col) {
newArray[i][j - 1] = workArray[i][j];
}
}
}
return newArray;
}
and you can use it like :-
workArray = removeEntry(workArray, 2);

swap between rows in a 2D array in 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.

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] + " ");
}
}

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