public class MultiDimArray {
private static int MAX_ARRAY_DIM = 8;//数组最大维数
int[] base;//数组元素基地址
int dim;//数组维数
int[] bounds; //数组维界基地址
int[] constants;//数组映像函数 常量基址
//初始化n维数组
public void initArray(int dim,int... args) {
print("dim:"+dim);
if(dim < 1 || dim > MAX_ARRAY_DIM) {
System.out.println("dim is illegal");
return;
}
this.dim = dim;
this.bounds = new int[dim];
int elemtotal = 1;//求出数组元素的总数
if(args.length != dim) {
System.out.println("args is illegal");
return;
}
for(int i = 0; i < dim; i++) {
this.bounds[i] = args[i];
elemtotal*= this.bounds[i];
}
this.base = new int[elemtotal];
//求映像函数常数Ci
this.constants = new int[dim];
this.constants[dim -1] = 1;
for(int i = dim -2; i >= 0; i--) {
this.constants[i] = this.bounds[i+1]*this.constants[i+1];
}
for(int i = 0; i < this.constants.length; i++) {
print("constants["+i+"]="+constants[i]);
}
}
//销毁n维数组
public void destroyArray() {
this.base = null;
this.bounds = null;
this.constants = null;
this.dim = 0;
}
//求元素在多维数组的相对地址off
public int locate(int ...index ) {
int off = 0;
for(int i = 0; i < dim; i++) {
int ind = index[i];
off+=constants[i]*ind;
}
print("locate:"+off);
return off;
}
//获取n维数组某个元素的值
public int value(int ... index) {
int result = locate(index);
if(result <= 0) {
return result;
}
return this.base[result];
}
//给n维数组 某个下标元素赋值
public void assign(int value,int ... index) {
int off = locate(index);
if(off <= 0) {
return ;
}
this.base[off] = value;
}
private void print(String str) {
System.out.println(str);
}
}
package com.gac;
public class Test {
public static void main(String[] args) {
MultiDimArray dimArray = new MultiDimArray();
dimArray.initArray(3, 4,2,3);
dimArray.locate(1,2,1);
dimArray.assign(15, 1,1,2);
print("value:"+dimArray.value(1,2,2));
}
public static void print(String str) {
System.out.println(str);
}
}
多维数组的实现 (java 表示)
最新推荐文章于 2024-07-09 22:58:35 发布