One obvious solution that comes to my mind, especially when I see your DeleteCases
- and Insert
-calls, is to use Internal`Bag
. This makes is somewhat easy to collect all elements of your result. Let's start with the compiled equivalent of
Flatten[Table[{i, j}, {i, r - 1}, {j, 0, i - 1}], 1];
Inside a compiled function, you would start by creating a new bag for your result. Important is that I'm storing your two-dimensional tensor into a one-dimensional list. This is not a problem, because we always add a pair e.g. {0,2}
so we know that your final result can easily be rebuilt by using Partition[..,2]
at the end:
f1 = Compile[{{r, _Integer}},
Module[{res = Internal`Bag[Most[{0}]]},
Do[Internal`StuffBag[res, {i, j}, 1], {i, r - 1}, {j, 0, i - 1}];
Partition[Internal`BagPart[res, All], 2]
]
]
Knowing this, makes the creation of your other list easy. Just replace the DeleteCases
and Insert
calls by appropriate conditional events:
f2 = Compile[{{r, _Integer}},
Module[{res = Internal`Bag[Most[{0}]], c = 0},
Do[
If[c++ == r, Internal`StuffBag[res, {0, r}, 1]];
If[i == 0 && j == 0, Continue[]];
Internal`StuffBag[res, {i, j}, 1], {i, 0, r - 1}, {j, i, r - 1}
];
Partition[Internal`BagPart[res, All], 2]
]
]
You can use CompilePrint
from the <<CompiledFunctionTools`
package to verify that everything is properly compiled down.