title: Java- Mapping multi-dimensional arrays to single
body: <p>I am posting this in relation to another open question i have, however I thought that this deserved it's own question. </p>
  
  <p>Alternate question (for reference): <a href="https://stackoverflow.com/questions/29009921/java-proxy-discovering-bot">Java Proxy Discovering Bot</a></p>
  
  <p>Basically, I need to store a very large amount of data and have it accessible very quickly. This would work ideally in an unlimited memory situation:</p>
  
  <pre><code>boolean[][][][] sets = new boolean[256][256][256][256];
  boolean get(byte[] a) {
      return sets[a[0]][a[1]][a[2]][a[3]];
  }
  </code></pre>
  
  <p>However, this uses around 16gb of ram which is too much for my application. I figure that if using bits instead of booleans (stores as 4 bytes in Java) it would cut the memory usage to around 512MB. However, I can't seem to wrap my head around how to access the bits correctly. For example if you mapped each address something like this: position = a * b * c * d then it would map to the same bit as d * c * b * a etc.</p>
  
  <p>I found this thread covering how to convert 2D arrays into 1D arrays, but I can't seem to wrap my head around how to extend that to a 4D array. Can anyone explain this?
  <a href="https://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array-c">Map a 2D array onto a 1D array C</a></p>
  
  <p>The solution for 2D -> 1D arrays:</p>
  
  <pre><code>int array[width * height];
  int SetElement(int row, int col, int value)
  {
    array[width * row + col] = value;  
  }
  </code></pre>
  
  <p>I am just not sure of how to extend it to 4D -> 1D</p>
  
  <pre><code> int array[256 * 256 * 256 * 256];
   int setElement(int a, int b, int c, int d, boolean value)
   {
      array[?????????] = value;  
   }
  </code></pre>