Compiled 2D array compiled to D
In my program, I need to generate an array with cardinality values ββ(0 to 5) from 1 to 100,000.
So, I tried to compile this code:
const enum size_t MAX_ARRAY_SIZE = 100_000 + 1;
const enum size_t MAX_POWER_SIZE = 5 + 1;
const enum power_sum = calc_power_sum();
// some unimportant code here
pure ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] calc_power_sum() {
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] power_sum;
power_sum[0][] = 1;
foreach (x, ref element; power_sum[1]) {
element = x;
}
foreach (n; 2 .. MAX_POWER_SIZE) {
foreach (x, ref element; power_sum[n]) {
element = power_sum[n - 1][x] * power_sum[1][x];
}
}
foreach (ref power; power_sum) {
foreach (x; 1 .. MAX_ARRAY_SIZE) {
power[x] += power[x - 1]; // error appears here
}
}
return power_sum;
}
But the compiler says:
$ dmd problem.d
problem.d(130): Error: array index 6 is out of bounds [1LU, 2LU, 3LU, 4LU, 5LU, 6LU][0 .. 6]
problem.d(15): called from here: calc_power_sum()
What am I doing wrong?
source to share
At first glance, it looks like you just misunderstood the order of the array sizes. You
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE]
and your code assumes exactly the opposite
ulong[MAX_ARRAY_SIZE][MAX_POWER_SIZE]
Also I'm afraid 100,000 might be too much, after the above fix I get an internal compiler error. Works with lower values MAX_ARRAY_SIZE
.
source to share
As Michael said, you have to change the order of the dimensions.
However, you most likely won't be able to do what you plan for all sizes, because the maximum size of a static array is limited in D ( http://dlang.org/arrays.html ):
The total size of a static array cannot exceed 16 MB.
source to share