c# - n-dimensional Array -
i want create n-dimensional array of doubles. @ compile-time, number of dimensions n not known.
i ended defining array dictionary, key being array of ints corresponding different axes (so in 3-dimensional array, i'd supply [5, 2, 3] double @ (5, 2, 3) in array.
however, need populate dictionary doubles (0, 0, ... 0) (m1, m2, ... mn), m1 mn length of each axis.
my initial idea create nested for-loops, still don't know how many i'd need (1 each dimension), can't @ compile-time.
i hope i've formulated question in understandable manner, feel free ask me elaborate parts.
to create n-dimensional array, can use array.createinstance
method:
array array = array.createinstance(typeof(double), 5, 3, 2, 8, 7, 32)); array.setvalue(0.5d, 0, 0, 0, 0, 0, 0); double val1 = (double)array.getvalue(0, 0, 0, 0, 0, 0); array.setvalue(1.5d, 1, 2, 1, 6, 0, 30); double val2 = (double)array.getvalue(1, 2, 1, 6, 0, 30);
to populate arrays, can use rank
property , getlength
method return length of current dimension, using couple of nested loops o(n^m) algo (warning - untested):
private bool increment(array array, int[] idxs, int dim) { if (dim >= array.rank) return false; if (++idxs[idxs.length-dim-1] == array.getlength(dim)) { idxs[idxs.length-dim-1] = 0; return increment(array, idxs, dim+1); } return true; } array array = array.createinstance(typeof(double), ...); int[] idxs = new int[array.rank]; while (increment(array, idxs, 0)) { array.setvalue(1d, idxs); }
Comments
Post a Comment