Home > Back-end >  How do I copy part of a row of a 2d array into a 1d array?
How do I copy part of a row of a 2d array into a 1d array?

Time:11-06

I have a double 2d array that is filled with weather data. Each row is formatted in the same way, the first two numbers are the longitude and latitude of a location and the remaining numbers of the row is the actual weather data of that location. How should I go about finding a specific row and copying only the remaining numbers after index 1 of the row into a 1d array (basically ignoring the first two indexes)?

So far I tried:

int x = 0; //index for new 1d array
   for(int i = 0; i <= weather.length; i  ) {
        for(int j = 0; j < weather[i].length; j  ) {

//checks if this row's data is for the correct location
            if(weather[i][j] == longitude && weather[i 1][j 1] == latitude) {

/* if the current element is the latitude, that means all of the values after the ith 
index is the relevant data and can be copied into the new 1d array*/ 
                data[x] = weather[i 1][j 1];
                x  ;
            }
        }
    }

But this obviously doesn't work. I can't seem to wrap my head around the logic for doing this. I would appreciate any feedback

CodePudding user response:

You access a specific row using the element index:

double[] specificRow = weather[index];

You copy everything after index 1 using something like Arrays.copyOfRange:

double[] copy = Arrays.copyOfRange(specificRow, 2, specificRow.length);

CodePudding user response:

There seem to be several bugs in the implementation:

  • i <= weather.length - likely to cause ArrayIndexOutOfBoundsException
  • (weather[i][j] == longitude && weather[i 1][j 1] == latitude) - the data from different rows are compared; also comparing doubles should be implemented with a threshold.

If Arrays.copyOfRange cannot be used due to some reasons, the copy array should be retrieved this way:

// utility method to compare doubles
static boolean doubleEquals(double d1, double d2) {
    return Math.abs(d1 - d2) < 1e-10d;
}


double[] row = null;

for (int i = 0; i < weather.length; i  ) {
    if (doubleEquals(weather[i][0], longitude) 
     && doubleEquals(weather[i][1], latitude )) {
        row = new double[weather[i].length - 2];
        for (int j = 0; j < weather.length; j  ) {
            row[j] = weather[i][j   2];
        }
        // or just row = Arrays.copyOfRange(weather[i], 2, weather[i].length);
        break; // row found
    }
}
  • Related