I want to sum up each i array and store it as an element of a new array.
I expect to get int[] sumUp={10,30}
What am I doing wrong?
My result is instead {0,10}
int[][] matrixOne= {{1,2,3,4},{10,20}};
int [] sumUp=new int[matrixOne.length];
int toSum=0;
for(int i=0;i<matrixOne.length;i++) {
sumUp[i]=toSum;
for(int j=0;j<matrixOne[i].length;j++) {
toSum+=matrixOne[i][j];
}
}
System.out.println(Arrays.toString(sumUp));
You're storing the result before you sum the numbers.
EDIT: forgot to reset the sum
toSum = 0;
for(int j=0;j<matrixOne[i].length;j++) {
toSum+=matrixOne[i][j];
}
sumUp[i]=toSum;
I would prefer a stream on the int[][] which you can map (and stream() to sum()) in one pass. Like,
int[][] matrixOne = { { 1, 2, 3, 4 }, { 10, 20 } };
int[] sumUp = Arrays.stream(matrixOne).mapToInt(x -> Arrays.stream(x).sum()).toArray();
System.out.println(Arrays.toString(sumUp));
Outputs (as expected)
[10, 30]
As the others are pointing out you are storing your sum in toSum not sumUp in your inner loop.
If you want to avoid these mistakes, and you are using Java 8, you could simply do something like:
int[][] matrixOne= {{1,2,3,4},{10,20}};
int [] sumUp=new int[matrixOne.length];
for(int i=0;i<matrixOne.length;i++) {
sumUp[i] = Arrays.stream(matrixOne[i]).sum();
}
You could even stream and map the outer array, but it becomes a bit more complicated.
Related
Frame of the question:
Write a class called CommonElements with a single method main that will:
Create and obtain two integer arrays (arrayA and arrayB) using RandomIntegerArrayCreator type objects and its methods,
find the number of common elements between arrayA and arrayB (say: if integer 2 appears in arrayA once and twice in arrayB, that counts as ONE common element between the two),
Constraints / notes:
All array elements are integers from the the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and can appear multiple times in each array,
Arrays A and B do NOT have to be of the same size,
Arrays A and B CAN be empty (no elements),
Arrays A and B will NOT be sorted.
The code that I have already created:
import java.util.Random;
public class RandomIntegerArrayCreator {
int[] arr;
RandomIntegerArrayCreator(){
Random rand = new Random();
int size = rand.nextInt(16);
arr = new int[size];
for(int i=0;i<size;i++){
arr[i] = rand.nextInt(11);
}
}
public int getArraySize(){
return this.arr.length;
}
public int[] getArray(){
return this.arr;
}
public static void main(String[] args) {
RandomIntegerArrayCreator r = new RandomIntegerArrayCreator();
System.out.println("Size = "+r.getArraySize());
int[] arr = r.getArray();
System.out.print("Generated array is ");
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
Here's the pseudo code for what you're looking for.
for i=0, i<size arrayA
for j=0, j<size arrayB
if arrayA[i] == arrayB[j]
if(arrayA is not in dummyarray)
dummyarray.append(arrayA[i])
counter++
Edit: Basically, you iterate through arrayA and go through each element in arrayB and check if there's something that matches (For instance, arrayA[3] = 4 and arrayB[2] = 4, then there's a match). You add the number to a dummy list which you can check later to see if there's been a duplicate match.
I am creating a program that removes duplicate values based on 10 user inputs. However instead of having distinct values such as [1,2,3,4,5,6] I have zeros in my output as such [0, 1, 0, 2, 0, 3, 0, 4, 5, 6]. Some kind assistance on this matter would be greatly appreciated!
import java.util.*;
public class SOB23_2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc= new Scanner(System.in);
int[]Array= new int[10];
for(int i=0;i<Array.length;i++)
{
System.out.println("Enter number"+(i+1)+":");
Array[i]=sc.nextInt();
}
System.out.println("The distinct values of the array are"+Arrays.toString(eliminateDuplicates(Array)));
}
public static int[]eliminateDuplicates(int[]list)
{
int [] temp=new int[list.length];
for(int i=0;i<list.length-1;i++)
{
if(list[i]!=list[i+1])
{
temp[i]=list[i];
}
}
temp[list.length-1]=list[list.length-1];
return temp;
}
}
First, you're assuming the duplicates will be adjacent. This may be correct (and can be achieved by sorting first).
But then in your loop you only maintain one position variable, i.
Think of the problem as involving reading from one array and writing to another. You need a "read position" in the input and a "write position" in the output.
Also your output array will be longer than needed, because you create it to be the length of the input array. So you might want to make two passes through the input array, the first pass being necessary to discover how many duplicates can be removed, and thus find out how long the output array needs to be.
Then in the second pass you could copy values from the read position in the input and store them in the write position in the output, but only if they are not the same value as the most recently stored output value.
If you were ask to do that manually you can count the zeros in your array, make a new array with length myArray.length-countZero and put every number that's not a zero in the new array, your array has zeros because java primitives (int in this case) can not be null.
public int countZero(int[] a){
int count=0;
for(int i=0;i<a.length;i++){
if(a[i]==0)
count++;
}
return count;
}
public int[] removeZero(int[] a){
int[] myArray=new int[a.length-countZero(a)];
int count=0;
for (int i=0;i<a.length;i++){
if(a[i]!=0)
myArray[count]=a[i];
}
return myArray;
}
But if don't need to do it manually you can just use ArrayList is much easier.
After you are finished you can then do this.
You can do this before or after the array is returned.
int[] array = { 0, 1, 0, 2, 0, 3, 0, 4, 5, 6
};
array = Arrays.stream(array).filter(val -> val != 0).toArray();
System.out.println(Arrays.toString(array));
Prints
[1, 2, 3, 4, 5, 6]
I have used the code below to create and populate an array, however, when it comes to printing the array I do not get the result I expect while using the Arrays.toString() function.
Rather than printing
newArray: [2, 4, 6]
newArray: [8, 10, 12]
etc..
it prints
newArray: [[I#15db9742, [I#6d06d69c, [I#7852e922, [I#4e25154f]
newArray: [[I#15db9742, [I#6d06d69c, [I#7852e922, [I#4e25154f]
etc..
The code:
public static void main(String[] args) {
int[][] newArray = new int[4][3];
int number = 2;
for (int rowCounter = 0; rowCounter < newArray.length; rowCounter++) {
for (int colCounter = 0; colCounter < newArray[rowCounter].length; colCounter++) {
newArray[rowCounter][colCounter] = number;
number += 2;
}
System.out.println("newArray: " + Arrays.toString(newArray));
}
}
Any help with this would be much appreciated.
You can use deepToString instead of toString:
System.out.println(Arrays.deepToString(newArray));
Try
Arrays.deepToString(newArray)
With the result you desire, make sure the array you are declaring is one-dimensional. You declared a two dimensional array which you are not using correctly.
Change int[][] newArray to int[] newArray
when you call toString(Object[] a) internally it will call Object.toString method.
(obj == null) ? "null" : obj.toString();
If you want to print all element then as mentioned you have to deepToString instead of toString method.Internally it will for a object type array will loop through the array and convert to string.
For an example every array element in your case is int array will call toString.
if (eClass.isArray()) {
if (eClass == int[].class)
buf.append(toString((int[]) element));
Basically what I am asking is given a square 2D array and a valid patch size (the size of the 2D subarrays) how would I go about doing this.
Ultimately I don't need to store the subarrays in any way, I just need to find the median of each subarray and store them in a 1D array. The median and storing to new array are simple for me, I just can't figure out how to go about the original 2D array and splitting it properly.
I've attempted this several times and keep getting out of bounds errors.
I have a 4x4:
[1,2,3,4]
[2,3,4,1]
[3,4,1,2]
[4,1,2,3]
I need to split it like so
[1,2] [3,4]
[2,3] [4,1]
[3,4] [1,2]
[4,1] [2,3]
And then take the median of each and store them into a new 1D array.
EDIT: Solved, thanks for the help!
You can use Arrays.copyOfRange(Object[] src, int from, int to) for this where:
src is the source 1D array
from is the initial index of the range to be copied, inclusive.
to is the final index of the range to be copied, exclusive.
I don't prefer your code because it seems that it's time complexity is too high.
Try below code:
public class Temp {
public static void main(String[] args) {
int[][] arr = { { 1,2,3,4 },
{ 2,3,4,1 },
{ 3,4,1,2 },
{ 4,1,2,3 } };
int patch = 2;
splitToSubArrays(arr, patch);
}
static void splitToSubArrays(int arr[][], int patch) {
for (int i = 0; i < arr[0].length; i++) {
int to = patch;
for (int from = 0; to <= arr.length;) {
int a[] = Arrays.copyOfRange(arr[i], from, to);
// instead of printing you can store in a separate array for later usage
System.out.println(Arrays.toString(a));
to += patch;
from += patch;
}
}
}
}
EDIT: N.B.: For n*n array if n%patch is not 0 i.e. dimension is not divisible by patch value then you would need to use proper if condition here int a[] = Arrays.copyOfRange(arr[i], from, to); to control the index bound. Hope you are aware of this.
Output
[1, 2]
[3, 4]
[2, 3]
[4, 1]
[3, 4]
[1, 2]
[4, 1]
[2, 3]
I think something like this could do, altough i didn't test it, but It should give you a good idea of how to do this scan
public int[] patchArray(int[][] img, int patch)
{
int size = img.length * (img[0].length / patch) ;
int[] pArray = new int[size];
int[] tmp = new int[patch];
for (int row_i = 0; row_i < img.length; row_i++)
{
for (int patch_start = 0; patch_start < img[i].length; patch_start += patch)
{
int x = 0;
for (int patch_i = patch_start; patch_i < (patch_start + patch); patch_i++)
{
tmp[patch_i - patch_start] = img[row_i][patch_i];
}
calculateMedian(tmp);
}
}
return pArray;
}
I have an assignment that requires me to create a method that takes an array of double named dArray as parameter and returns another array whose elements are squares of the elements of dArray.
For example,
if dArray is {1, 4, 6, 7}, the the returned array will be {1, 16, 36, 49}.
Any help would be greatly appreciated!
Here is what I have written so far, but it doesn't work right.
public static double[] squareArray(double[] dArray) {
double[] squareArray = new double[10];
for(int i = 0; i < dArray.length ; i++) {
dArray[] = dArray * dArray;
}
return squareArray;
}
class Test {
public static void main(String [ ] args) {
double[] scores = {3, 9, 3, 3};
double[] scoresSquared = squareArray(scores);
for (int i =0; i <scoresSquared.length; i++) {
System.out.println(scoresSquared[i] + " ");
}
}
public static double[] squareArray(double[] dArray){
double[] squareArray = new double[dArray.length];
for (int i = 0; i < dArray.length ; i++){
squareArray[i]= dArray[i] * dArray[i];
}
return squareArray;
}
}
It would appear that you are squaring the array more than you need to. If every element in the array needs to be squared, you should only have to loop over that array once, but in your code you have two loops.
That's part of the issue.
Another is that you're trying to multiply arrays, which isn't allowed. Inside that method, you need to loop over the array and square each element in it.
Try this:
In your squareArray(), create a List< Double> or something like that.
Iterate through each double in the double[] and add that double squared to the List.
Return (listname).toArray();
You're almost there.
Copy the contents of the array you're receiving and place them into your internal squareArray.
Iterate over squareArray and apply your algorithm (to access specific indexes while in the loop, use squareArray[i])
Return squareArray.