flux00
10-29-2006, 04:57 PM
I'm working on this n-dimensional array class in Java, wherein the data is actually stored in a one-dimensional array, and when data is accessed the indices are added to the length of the array in that particular dimension. So I've been wondering about the efficiency of this (because you'd have to do 2 additions for a 3-dimensional array) and whether or not standard multi-dimensional arrays have to do the same thing, because memory is linear even if the array is not.
Basically what I'm asking whether or not operations like addition are done 'under the hood' to get the indices linear.
int[][] x = new int[5][5];
x[2][3] = 1;
When accessing x[2][3] would it add 2, 5, and 3 and return what's in the memory there?
package util;
public final class NArray extends Object
{
public final float[] X;
public final int[] dimension;
public NArray(int[] d)
{
super();
dimension = d;
int n=1;
for (int i=0; i<dimension.length; ++i)
{
n*=dimension[i];
}
X = new float[n];
}
public NArray(int n, int d)
{
super();
dimension = new int[n];
int s = 1;
for (int i=0; i<dimension.length; ++i)
{
dimension[i] = d;
s *= d;
}
X = new float[s];
}
public void store(float f, int[] i)
{
if (i.length != dimension.length)
{
return;
}
int r = 0;
for (int i0=1; i0<i.length; ++i0)
{
r += dimension[i0-1]+i[i0];
}
X[r] = f;
}
public float load(int[] i)
{
if (i.length != dimension.length)
{
return Float.NaN;
}
int r = 0;
for (int i0=1; i0<i.length; ++i0)
{
r += dimension[i0-1]+i[i0];
}
return X[r];
}
}
Basically what I'm asking whether or not operations like addition are done 'under the hood' to get the indices linear.
int[][] x = new int[5][5];
x[2][3] = 1;
When accessing x[2][3] would it add 2, 5, and 3 and return what's in the memory there?
package util;
public final class NArray extends Object
{
public final float[] X;
public final int[] dimension;
public NArray(int[] d)
{
super();
dimension = d;
int n=1;
for (int i=0; i<dimension.length; ++i)
{
n*=dimension[i];
}
X = new float[n];
}
public NArray(int n, int d)
{
super();
dimension = new int[n];
int s = 1;
for (int i=0; i<dimension.length; ++i)
{
dimension[i] = d;
s *= d;
}
X = new float[s];
}
public void store(float f, int[] i)
{
if (i.length != dimension.length)
{
return;
}
int r = 0;
for (int i0=1; i0<i.length; ++i0)
{
r += dimension[i0-1]+i[i0];
}
X[r] = f;
}
public float load(int[] i)
{
if (i.length != dimension.length)
{
return Float.NaN;
}
int r = 0;
for (int i0=1; i0<i.length; ++i0)
{
r += dimension[i0-1]+i[i0];
}
return X[r];
}
}