我最初的想法是创建嵌套的for循环,但是由于我仍然不知道需要多少个(每个维度1个),因此在编译时无法做到这一点.我希望我已经以一种可以理解的方式提出了这个问题,但是请让我详细阐述一下.解决方案对此事的快速跟进:我们成功地使用了Array.CreateInstance方法,但是正如有人预言的那样,它效率很低,并且还会带来可读性问题.相反,我们开发了一种方法,其中将n维数组转换为1维(常规)数组.public static int NDToOneD(int[] indices, int[] lengths){ int ID = 0; for (int i = 0; i < indices.Length; i++) { int offset = 1; for (int j = 0; j < i; j++){ offset *= lengths[j];} ID += indices[i] * offset; } return ID;}1DtoND(int[] indices, int[] arrayLengths){ int[] indices = new int[lengths.Length]; for (int i = lengths.Length - 1; i >= 0; i--) { int offset = 1; for (int j = 0; j < i; j++) { offset *= lengths[j]; } int remainder = ID % offset; indices[i] = (ID - remainder) / offset; ID = remainder; } return indices;}这本质上是将笛卡尔坐标转换为单个整数然后再次转换的概括.我们的测试尚未形式化,因此我们获得的任何提速完全是轶事,但对于我的机器,它的提速大约为30-50%(具体取决于样本大小),并且代码的可读性得到了提高很大的利润.希望这对遇到这个问题的人有所帮助.I want to create an n-dimensional array of doubles. At compile-time, the number of dimensions n is not known.I ended up defining the array as a dictionary, with the key being an array of ints corresponding to the different axes (so in a 3-dimensional array, I'd supply [5, 2, 3] to get the double at (5, 2, 3) in the array.However, I also need to populate the dictionary with doubles from (0, 0, ... 0) to (m1, m2, ... mn), where m1 to mn is the length of each axis.My initial idea was to create nested for-loops, but as I still don't know how many I'd need (1 for each dimension), I can't do this at compile-time.I hope I've formulated the question in an understandable manner, but feel free to ask me to elaborate parts. 解决方案 A quick followup on this matter:We used the Array.CreateInstance method with success, but as someone predicted, it was fairly inefficient, and additionally created readability problems.Instead, we have developed a method, where the n-dimensional array is converted into a 1-dimensional (normal) array.public static int NDToOneD(int[] indices, int[] lengths){ int ID = 0; for (int i = 0; i < indices.Length; i++) { int offset = 1; for (int j = 0; j < i; j++){ offset *= lengths[j];} ID += indices[i] * offset; } return ID;}1DtoND(int[] indices, int[] arrayLengths){ int[] indices = new int[lengths.Length]; for (int i = lengths.Length - 1; i >= 0; i--) { int offset = 1; for (int j = 0; j < i; j++) { offset *= lengths[j]; } int remainder = ID % offset; indices[i] = (ID - remainder) / offset; ID = remainder; } return indices;}This is essentially a generalisation on the conversion of cartesian coordinates to a single integer and back again.Our testing is not formalized, so any speedup we have gained is entirely anecdotal, but for my machine, it has given about a 30-50% speedup, depending on the sample size, and the readability of the code has improved by a wide margin.Hope this helps anyone who stumbles upon this question. 这篇关于n维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-25 12:03