In my program I need to generate array with powers' (from 0 to 5) sum of numbers 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 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?
At first glance looks like you have simply misunderstood array dimension order. You have
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE]
and your code assumes directly opposite
ulong[MAX_ARRAY_SIZE][MAX_POWER_SIZE]
Also I am afraid 100 000 may be a bit too much, after above mentioned fix I get an internal compiler error. Works for smaller MAX_ARRAY_SIZE
values though.