Java sum of 2 arrays - java

In my app I have 2 arrays
Integer[] array1= {1, 2, 3, 8, 6, 4, 10};
Integer[] array2= {200, 100, 50, 20, 10, 5, 1};
Now I want to multiply every element from the first array with every element from the second array and finally to sum, for example:
200x1 = 200; 100x2 = 200; 50x3 = 150; 20x8 = 160; 10x6 = 60; 5x4 = 20; 1x10 = 10;
and then to sum 200+200+150+160+60+20+10 = 800

You can even use streams:
Integer[] array1 = {1, 2, 3, 8, 6, 4, 10};
Integer[] array2 = {200, 100, 50, 20, 10, 5, 1};
public void test() {
System.out.println(
// Each index of the arrays.
IntStream.range(0, Math.min(array1.length, array2.length))
// Multiply the two array entries.
.mapToLong(n -> array1[n] * array2[n])
// Add them up.
.sum());
}

Integer[] array1= {1, 2, 3, 8, 6, 4, 10};
Integer[] array2= {200, 100, 50, 20, 10, 5, 1};
int resultOfSum = 0;
for (int i = 0; i < array1.length;i++){
resultOfSum += array1[i]*array2[i];
}
Hope this helps :)

use this
int total = 0;
for(int i = 0; i < array1.length; i++){
total += array2[i] * array1[i];
}

Here, try this :
int s=0;
for(int i=0;i<array1.length;i++)
s+=array1[i]*array2[i];
System.out.println(s);

Related

How can I pick out the odd numbers and even numbers from a given array and then store them in another array?

How can I pick out the odd numbers and even numbers from a given array and then store them in another array? The flow is: the odd numbers will go to the odd[] array while the even numbers will go to the even[] array??
Here's my code, I'm not sure if this is correct since it somewhat stores and prints a mix of zeros and even numbers, no presence of odd numbers.....
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] odd = new int[10];
int[] even = new int[10];
for (int i = 0; i < num.length; i++) { // For odd numbers
if (num[i] % 2 != 0) {
num[i] = odd[i];
}
System.out.println(num[i] + " ");
}
for (int j = 0; j < num.length; j++) { // For even numbers
if (num[j] % 2 == 0) {
num[j] = even[j];
}
System.out.println(num[j] + " ");
}
You can do all that in one loop - that would be way faster. To know the correct position to put the number in, add extra counter for each array.
Your kind of approach
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] odd = new int[10];
int[] even = new int[10];
int oddPos = 0;
int evenPos = 0;
for (int i = 0; i < num.length; i++) {
if (num[i] % 2 == 0) {
even[evenPos] = num[i];
evenPos++;
} else {
odd[oddPos] = num[i];
oddPos++;
}
}
However this would not be the best solution as you (in most cases) cannot determine the length of odd and even arrays beforehand. Then you should use either arraylists or count the values of each or something else.
More dynamic approach
As stated before - you need to determine the size of the arrays at first
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int oddCount = 0, evenCount = 0;
int oddPos = 0, evenPos = 0;
//get the count of each type
for (int i = 0; i < num.length; i++) {
if (num[i] % 2 == 0)
oddCount++;
else
evenCount++;
}
//define arrays in correct sizes
int[] odd = new int[oddCount];
int[] even = new int[evenCount];
//put values in arrays
for (int i = 0; i < num.length; i++) {
if (num[i] % 2 == 0) {
even[evenPos] = num[i];
evenPos++;
} else {
odd[oddPos] = num[i];
oddPos++;
}
}
the approach for detecting odd and even numbers is correct, But I think the problem with the code you wrote is that the length of odd and even arrays, isn't determinant. so for this matter, I suggest using ArrayList<Integer>, let's say you get the array in a function input, and want arrays in the output (I'll mix the arrays in the output for better performance. but separating the functions for each list extracting is also ok depending on what you're going to do with them).
Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static Integer[][] separateOddnEven(int[] input) {
Integer[][] output = new Integer[2][];
List<Integer> odds = new ArrayList<>();
List<Integer> evens = new ArrayList<>();
for (int i = 0; i < input.length; ++i) {
int temp = input[i];
if (temp % 2 == 0)
evens.add(temp);
else
odds.add(temp);
}
// alternative is to use these Arraylists directly
output[0] = new Integer[odds.size()];
output[1] = new Integer[evens.size()];
output[0] = odds.toArray(output[0]);
output[1] = evens.toArray(output[1]);
return output; // index 0 has odd numbers and index 1 has even numbers.
}
public static void main(String[] args) {
int[] input = {0, 21, 24, 22, 14, 15, 16, 18};
Integer[][] output = separateOddnEven(input);
System.out.println("odd numbers :");
System.out.println(Arrays.toString(output[0]));
System.out.println("even numbers :");
System.out.println(Arrays.toString(output[1]));
}
}
output :
odd numbers :
[21, 15]
even numbers :
[0, 24, 22, 14, 16, 18]
You can collect a 2d array with two rows: even and odd as follows:
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
// a 2d array of two rows: even and odd
int[][] arr = new int[2][];
// process a 1d array and fill a 2d array
Arrays.stream(num).boxed()
// Map<Integer,List<Integer>>
.collect(Collectors.toMap(
// key: 0 - even, 1 - odd
n -> n % 2,
// value - a list of one
// element, i.e. number
n -> new ArrayList<>(List.of(n)),
// merge duplicates
(list1, list2) -> {
list1.addAll(list2);
return list1;
}))
// fill the rows of a 2d array: even and odd
.forEach((key, value) -> arr[key] = value.stream()
.mapToInt(Integer::intValue).toArray());
// output
System.out.println("Even: " + Arrays.toString(arr[0]));
// Even: [2, 4, 6, 8, 10, 12, 14, 16]
System.out.println("Odd: " + Arrays.toString(arr[1]));
// Odd: [1, 3, 5, 7, 9, 11, 13, 15]
in lambda (3 lines)
int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
separate even and odd nums with partitioningBy:
Map<Boolean, List<Integer>> map = IntStream.of(nums)
.boxed().collect(partitioningBy(n -> (n & 1) == 0));
…and transform the resulting List<Integer> for even and odd to int[]:
int[] even = map.get(true).stream().mapToInt(i -> i).toArray();
int[] odd = map.get(false).stream().mapToInt(i -> i).toArray();
System.out.println("even numbers: " + Arrays.toString(even));
System.out.println("odd numbers: " + Arrays.toString(odd));
even numbers: [2, 4, 6, 8, 10, 12, 14, 16]
odd numbers: [1, 3, 5, 7, 9, 11, 13, 15]

Concatenating two arrays with alternating values

What is the best way to concatenate two arrays with alternating values?
Let's say array1 is:
[1, 3, 5, 7]
array2 is:
[2, 4, 6, 8]
I want to combine these two arrays, so that the result is:
[1, 2, 3, 4, 5, 6, 7, 8]
In Java:
int[] a1 = { 1, 3, 5, 7 };
int[] a2 = { 2, 4, 6, 8 };
int[] concat = new int[a1.length * 2];
for (int i = 0; i < concat.length; i++) {
// concatenation
}
System.out.println(concat.toString());
// should be [1, 2, 3, 4, 5, 6, 7, 8]
Update: No sorting is required, as the arrays are already sorted, using Arrays.sort(array)
A basic way
int[] concat = new int[a1.length * 2];
int index = 0;
for (int i = 0; i < a1.length; i++) {
concat[index++] = a1[i];
concat[index++] = a2[i];
}
assuming that both array will be of same size.
Put the elements of both array in a list and then sort it.You can use lambdas also
Integer[] a1 = { 1, 3, 5, 7 };
Integer[] a2 = { 2, 4, 6, 8 };
List<Integer> list = new ArrayList<>();
list.addAll(Arrays.asList(a1));
list.addAll(Arrays.asList(a2));
System.out.println("Before Sorting "+list);
Collections.sort(list,(a, b) -> Integer.compare(a,b));
System.out.println("After Sorting "+list);
Output
Before Sorting [1, 3, 5, 7, 2, 4, 6, 8]
After Sorting [1, 2, 3, 4, 5, 6, 7, 8]
If you want to zip together any length arrays (where then lengths differ, the remaining is appended to the result):
public static int[] zip(int[] a, int[] b){
int[] result = new int[a.length + b.length];
int index = 0;
final int minLen = Math.min(a.length, b.length);
for (int i = 0; i < minLen; i++) {
result[index++] = a[i];
result[index++] = b[i];
}
if(a.length > minLen)
System.arraycopy(a, minLen, result, index, a.length - minLen);
else if(b.length > minLen)
System.arraycopy(b, minLen, result, index, b.length - minLen);
return result;
}
Try it like this:
int[] concat = new int[a1.length + a2.length];
int k = 0, m = 0;
for (int i = 0; i < concat.length; i++) {
if( k < al.length && a1[k] <= a2[m])
concat[i] = a1[k++];
else
concat[i] = a2[m++];
}
NB: The result will be sorted as in your desired output.
you could also use two variables in your loop like this
int[] a1 = { 1, 3, 5, 7 };
int[] a2 = { 2, 4, 6, 8 };
int[] concat = new int[a1.length + a2.length];
for (int i = 0, j = 0; i+j < concat.length;) {
if(i<a1.length) {
concat[i+j] = a1[i++];
}
if(j<a2.length) {
concat[i+j] = a2[j++];
}
}
System.out.println(Arrays.toString(concat));
Try This if it solves ur problem
int[] a1 = { 1, 3, 5, 7 };
int[] a2 = { 2, 4, 6, 8 };
int[] concat = new int[a1.length + a2.length];
System.arraycopy(a1, 0, concat, 0, a1.length);
System.arraycopy(a2, 0, concat, a1.length, a2.length);
Arrays.sort(concat);
System.out.println(Arrays.toString(concat));
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
There are utility methods for example addALL() method from ArrayUtil class. But what they do is simple concatenate. For your problem you need to write your own logic. For example the following code ensures correct alternate concatenation even if arrays are of unequal length.
int[] a1 = { 1, 3, 5, 7 };
int[] a2 = { 2, 4, 6, 8, 9, 10, 122 };
int totalLen = a1.length + a2.length;
int[] concat = new int[totalLen];// I made a change here incase the
// arrays are not of equal length
int i = 0; // this will be the concat array index counter
int j1 = 0; // this will be the a1 array index counter
int j2 = 0; // this will be the a2 array index counter
while (i < totalLen) {
if ((j1 < a1.length)) {
concat[i] = a1[j1];
i++;
j1++;
}
if ((j2 < a2.length)) {
concat[i] = a2[j2];
i++;
j2++;
}
}

Calculate the percentage between 2 arrays and output a new array

For most of you, this will be very simple, but I'm a newbie- so don't hate too much! Ok, so I have two arrays, one showing 'correct scores' and another showing 'incorrect scores'. I want to create a new array using these which shows the % correct.
I have written :
int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0, 1};
for(int a = 0; a < correct1.length; a++ ){
int[] percentage1 = ((correct1[a] / (correct1[a] + incorrect1[a]))*100);
}
But this gives me a type mismatch between int and int[]. Any help would be appreciated, thanks.
for(int a = 0; a < correct1.length; a++ ){
int[] percentage1 = ((correct1[a] / (correct1[a] + incorrect1[a]))*100);
}
Above should be:
double[] percentage1 = new double[correct1.length];
for(int a = 0; a < correct1.length; a++ ){
percentage1[a] = (double)((correct1[a] / (correct1[a] + incorrect1[a]))*100);
}

Rotate array by arbitrary step size without creating second array

So for a step size of 1, I want the array:
{1, 2, 3, 4}
To become:
{4, 1, 2, 3}
And for a step of size 2 the result will be:
{3, 4, 1, 2}
This is the code I'm using now:
private static int[] shiftArray(int[] array, int stepSize) {
if (stepSize == 0)
return array;
int shiftStep = (stepSize > array.length ? stepSize % array.length : stepSize);
int[] array2 = new int[array.length];
boolean safe = false;
for (int i = 0; i < array.length; i++) {
if (safe) {
array2[i] = array[i - shiftStep];
}
else {
array2[i] = array[array.length - shiftStep + i];
safe = (i+1) - shiftStep >= 0;
}
}
return array2;
}
The code is working great, but is it possible to achieve this without creating a helper array (which is array2 in the code above)?
Thanks!
You can do it without creating as big an array:
// void return type as it shifts in-place
private static void shiftArray(int[] array, int stepSize) {
// TODO: Cope with negative step sizes etc
int[] tmp = new int[stepSize];
System.arraycopy(array, array.length - stepSize, tmp, 0, stepSize);
System.arraycopy(array, 0, array, stepSize, array.Length - stepSize);
System.arraycopy(tmp, 0, array, 0, stepSize);
}
So for a 100,000 array and a step size of 10, it creates a 10-element array, copies the last 10 elements into it, copies the first 999,990 elements to be later, then copies from the temporary array back to the start of the array.
Use not the i++, but i += shiftSize and several loops (amount of them would be equal to gcd of array.length and shifSize).
Then you'll need only one int as buffer and execution time will be almost the same.
You could do it with a couple of loops, but its not easy. Using recursion is simpler in this case.
public static void main(String... args) {
for (int i = 0; i < 12; i++) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
rotateLeft(ints, i);
System.out.println(Arrays.toString(ints));
}
}
public static void rotateLeft(int[] array, int num) {
rotateLeft(array, num, 0);
}
private static void rotateLeft(int[] array, int num, int index) {
if (index >= array.length) return;
int tmp = array[(index + num) % array.length];
rotateLeft(array, num, index + 1);
array[index] = tmp;
}
prints
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3]
[5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4]
[6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5]
[7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]
[8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7]
[9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8]
[10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Yes it's possible, you'd only need to temporary store one element additional to the array.
Basically what you want to do is to:
store last element in tmp var
shift all elements to the right by one starting with the second to last element
sotre tmp var as first element
repeat from step 1 depending on your stepsize
This is not tested ...
public void rotateByStep(int[] array, int step) {
step = step % array.length;
if (step == 0) {
return;
}
int pos = step;
int tmp = array[0];
boolean inc = array.length % step == 0;
for (int i = 0; i < array.length; i++) {
int tmp2 = array[pos];
array[pos] = tmp;
tmp = tmp2;
pos = (pos + step) % array.length;
if (inc && pos < step) {
array[pos] = tmp;
pos++;
tmp = array[pos];
}
}
}
The idea I'm trying to implement is as follows:
If step isn't a factor of length, then incrementing an index (pos) by step modulo length starting from zero will visit every array element once after length iterations.
If step is a factor of length, then index (incremented as above) will get back to its starting point after length / step iterations. But if you then increment by one, you can process the cycle starting at 1, and then at 2, and so on. After length iterations, we'll have visited every array element once.
The rest is just rippling the element values as we cycle through the element indexes ... with some adjustment when we increment to the next cycle.
The other complete solutions have the advantage that they are much easier to understand, but this one requires no extra heap storage (i.e. no temporary array), and does the job in array.length loop iterations.
In n- 1 iterations
#include <stdio.h>
int main(int argc, char **argv) {
int k = 0, x = 0;
int a[] = {-5,-4,-1,0,1,2,30,43,52,68,700,800,9999};
int N = 0, R = 57; /*R = No of rotations*/
int temp = 0, temp2 = 0, start = 0, iter = 0;
x = 0;
temp2 = a[x];
N = sizeof(a) / sizeof(a[0]);
for ( k = 0; k < N - 1; k++) {
x = x + R;
while ( x >= N ) {
x = x - N;
}
temp = a[x];
a[x] = temp2;
temp2 = temp;
if ( x == start ) {
start = start + 1;
x = x + 1;
temp2 = a[x];
}
iter++;
}
a[start] = temp2;
for ( k = 0; k < N; k++) {
printf(" %d", a[k]);
}
printf("\n");
printf("Done in %d iteration\n", iter);
return 0;
}

How to remove a row from a 2d array?

I have a simple array, sort of like this:
1 2 3 4 5 6 7 8 9
6 2 7 2 9 6 8 10 5
2 6 4 7 8 4 3 2 5
9 8 7 5 9 7 4 1 10
5 3 6 8 2 7 3 7 2
So, let's call this matrix[5][9]. I wish to now remove every row within this matrix that contains a certain value, in this case 10, so I am left with...
1 2 3 4 5 6 7 8 9
2 6 4 7 8 4 3 2 5
5 3 6 8 2 7 3 7 2
Here's a sample class you can run that I believe does what you're looking for. Removing rows from 2D arrays is tricky business because like #KalebBrasee said, you can't really "remove" them, but rather you have to make a whole new 2D array instead. Hope this helps!
import java.util.ArrayList;
import java.util.List;
public class Matrix {
private double[][] data;
public Matrix(double[][] data) {
int r = data.length;
int c = data[0].length;
this.data = new double[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
this.data[i][j] = data[i][j];
}
}
}
/* convenience method for getting a
string representation of matrix */
public String toString() {
StringBuilder sb = new StringBuilder(1024);
for (double[] row : this.data) {
for (double val : row) {
sb.append(val);
sb.append(" ");
}
sb.append("\n");
}
return (sb.toString());
}
public void removeRowsWithValue(final double value) {
/* Use an array list to track of the rows we're going to want to
keep...arraylist makes it easy to grow dynamically so we don't
need to know up front how many rows we're keeping */
List<double[]> rowsToKeep = new ArrayList<double[]>(this.data.length);
for (double[] row : this.data) {
/* If you download Apache Commons, it has built-in array search
methods so you don't have to write your own */
boolean found = false;
for (double testValue : row) {
/* Using == to compares doubles is generally a bad idea
since they can be represented slightly off their actual
value in memory */
if (Double.compare(value, testValue) == 0) {
found = true;
break;
}
}
/* if we didn't find our value in the current row,
that must mean its a row we keep */
if (!found) {
rowsToKeep.add(row);
}
}
/* now that we know what rows we want to keep, make our
new 2D array with only those rows */
this.data = new double[rowsToKeep.size()][];
for (int i = 0; i < rowsToKeep.size(); i++) {
this.data[i] = rowsToKeep.get(i);
}
}
public static void main(String[] args) {
double[][] test = {
{1, 2, 3, 4, 5, 6, 7, 8, 9},
{6, 2, 7, 2, 9, 6, 8, 10, 5},
{2, 6, 4, 7, 8, 4, 3, 2, 5},
{9, 8, 7, 5, 9, 7, 4, 1, 10},
{5, 3, 6, 8, 2, 7, 3, 7, 2}};
//make the original array and print it out
Matrix m = new Matrix(test);
System.out.println(m);
//remove rows with the value "10" and then reprint the array
m.removeRowsWithValue(10);
System.out.println(m);
}
}
Use System.arraycopy or use java.util.List instead of arrays. ArrayList has fast access to random elements and a slow remove method, it's the opposite with LinkedList. You have to choose for yourself.
At the and you have to recreate the array and discard the old one. Changing the dimension of an existing array is not possible - if want this type of datastructure, then you should build the matrix based on Collections (ArrayList<ArrayList<Double>>), there you can remove a row easily.
Back to arrays - the idea is to collect all rows (double[] arrays) that you want to keep, create a result array with those rows and replace the old one with the new on on Matrix:
public void doSomethingWith(Matrix in) {
List<double[]> survivingRows = new ArrayList<double[]>();
for (double[] row:in.getRows()) {
if (isAGoodOne(row)) {
survivingRows.add(row);
}
}
double[][] result = new double[survivingRows][];
for (int i = 0; i < result.length; i++) {
result[i] = survivingRows.get(i);
}
in.setArray(result);
}
You can't remove elements from the Java built-in array data structure. You'll have to create a new array that has a length one less than the first array, and copy all the arrays into that array EXCEPT the one you want to remove.
My java syntax is a little rusty, but the following, if treated as pseudocode will work
public Matrix removeRows(Matrix input) {
int[][] output = new int[input.numRows][input.numColumns]();
int i = 0;
for (int[] row : input.rows()) { // Matrix.rows() is a method that returns an array of all the rows in the matrix
if (!row.contains(10)) {
output[i] = row;
}
}
return output
My take:
import java.util.Arrays;
public class RemoveArrayRow {
private static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
if (alen == 0) {
return b;
}
if (blen == 0) {
return a;
}
final T[] result = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
public static void main(String[] args) {
double[][] d = { {11, 2, 3, 4, 5, 6, 7, 8, 9, 0},
{12, 2, 3, 4, 5, 6, 7, 8, 9, 1},
{13, 2, 3, 4, 5, 6, 7, 8, 9, 2},
{14, 2, 3, 4, 5, 6, 7, 8, 9, 3},
{15, 2, 3, 4, 5, 6, 7, 8, 9, 4} };
//remove the fourth row:
// (1)
double[][] d1 = concat(Arrays.copyOf(d, 3), Arrays.copyOfRange(d, 4, 5));
// (2)
double[][] d2 = new double[d.length - 1][d[0].length];
System.arraycopy(d, 0, d2, 0, 3);
System.arraycopy(d, 4, d2, 3, 1);
System.out.print(d1.length);
System.out.print(d2.length);
}
}
(1)
If you exclude the concat() function used for concatenating two arrays, it's done in one line:
double[][] d1 = concat(Arrays.copyOf(d, 3), Arrays.copyOfRange(d, 4, 5));
See this question as well. That's where the code for the concat() function comes from.
(2)
This method is faster and only uses already available functions.
Since it cannot avoid creating new 2D array to contain the after-removed data, firstly, create a new 2D int[][] b with same dimension as a[][]. secondly, loop through a[][], assign a to b and move b row up when a contain specific value. and sanity check the last row, which can contain specific data.
public static int[][] remove(int[][] a, int v) {
int r = a.length;
int c = a[0].length;
int[][] b = new int[r][c];
int red = 0;
boolean s = false;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
b[i - red][j] = a[i][j];
if (a[i][j] == v) {
red += 1;
if(i==r-1){
s = true;
}
break;
}
}
}
//check last row
if(s){
for(int i = r-red;i <r-red +1; i++ )
for (int j = 0; j<c; j++){
b[i][j] = 0;
}
}
return b;
}
public static void main(String[] args){
int[][] a = { {1, 2, 3, 4, 5, 6, 7, 8, 1},
{6, 2, 7, 2, 9, 6, 8, 10, 5},
{2, 6, 4, 7, 8, 4, 2, 2, 5},
{9, 8, 7, 5, 9, 7, 4, 1, 1},
{5, 3, 6, 8, 2, 7, 3, 1, 1} };
print(remove(a, 10));
}
public static void print(int[][] a) {
int r = a.length;
int c = a[0].length;
int red = 0;
for (int i = 0; i < r; i++) {
System.out.printf("\nrow %d, \n", i);
for (int j = 0; j < c; j++) {
System.out.printf("%d, ", a[i][j]);
}
}
}
This may not be an exact solution but a concept of how you can achieve it using System.arraycopy.
In the example below, I want to copy all the rows except the first row. In your case, you can skip those rows which contain 10.
String[][] src = getSheetData(service, spreadSheetId, range);
String[][] dest = new String[src.length-1][src[0].length];
for (int i = 1; i < src.length; i++) {
System.arraycopy(src[i], 0, dest[i-1], 0, src[0].length-1);
}
Reference: https://docs.oracle.com/javase/6/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29
You can use IntStream.noneMatch method for this purpose:
int[][] arr1 = {
{1, 2, 3, 4, 5, 6, 7, 8, 9},
{6, 2, 7, 2, 9, 6, 8, 10, 5},
{2, 6, 4, 7, 8, 4, 3, 2, 5},
{9, 8, 7, 5, 9, 7, 4, 1, 10},
{5, 3, 6, 8, 2, 7, 3, 7, 2}};
int[][] arr2 = Arrays.stream(arr1)
.filter(row -> Arrays.stream(row).noneMatch(i -> i == 10))
.toArray(int[][]::new);
// output
Arrays.stream(arr2).map(Arrays::toString).forEach(System.out::println);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 6, 4, 7, 8, 4, 3, 2, 5]
[5, 3, 6, 8, 2, 7, 3, 7, 2]

Categories