0

I am new to working with multidimensional arrays, and seem to not be able to get my head around this problem:

I am currently trying to create some code which increases the dimensions of a multidimensional array. The aim is to take an array named flat array, and add newDimensions. In the case I have in my test, an array is created: [0,20,10,30], which is an array of dimensions (2,2) and newDimensionssize(2) is to be added.

Now my code below creates a new flatArray of [0,0,10,10,5,5,15,15], but my issue is that the test does not pass because it is expected to be [0,0,5,5,10,10,15,15].

Am I maybe not understanding how nested arrays work, or is there something else that could be useful to help me achieve the desired result?

Many thanks for your help in advance!

@Override
public void addDimension(int newDimensionSize) {
    int[] arrayAddedDimensions = new int[flatArray.length * newDimensionSize];
    int arrayValue;
    int j = 0;
    int k = 0;

    for (int i = 0; (i < flatArray.length); i++) {
        arrayValue = flatArray[i];
        int newValue = (arrayValue / newDimensionSize);
        for (k = 0; (k < newDimensionSize); k++) {
                arrayAddedDimensions[j] = newValue;
                j++;
            }
    }
    flatArray = arrayAddedDimensions;
}
Fant
  • 1
  • 1
  • What you are doing is nothing related to dimensions. The problem statement might have state dimensions with their own definition of it. – Shashwat Kumar Aug 07 '18 at 15:28
  • So the problem is that you want your array sorted at the end? The code is working fine, as in `0 / 2 = 0`, `20 / 2 = 10`, `10 / 2 = 5`, and `30 / 2 = 15`. – Jimenemex Aug 07 '18 at 15:30
  • Is the result supposed to be a nested `array`? – GBlodgett Aug 07 '18 at 15:32
  • Yeah, it's all working fine in that respect. It just seems that the expected array is in a slightly different order, and I was wondering if I was having some problems visualising the flat array in comparison to a multidimensional array. I used an array sort but removed it, as this wouldn't be appropriate for all test cases. – Fant Aug 07 '18 at 15:35
  • Everything you're doing here is 1d array. You can use a 1d array to simulate a multidimensional array--is that what you're attempting to do? – ggorlen Aug 07 '18 at 15:36
  • The result is supposed to be flat array - but each element is in a position relative to its dimensions. – Fant Aug 07 '18 at 15:36
  • I am trying to simulate one in 1D, yeah :) – Fant Aug 07 '18 at 15:36
  • OK, well a 2d array in 1d array can be indexed into with `array[length * row + col]` and a 3d array is https://stackoverflow.com/questions/7367770/how-to-flatten-or-index-3d-array-in-1d-array – ggorlen Aug 07 '18 at 15:39
  • Thanks ggorlen, that's really helpful, thank you very much :) – Fant Aug 07 '18 at 15:43

0 Answers0