I want to see how this solution stacks with the above Linq solutions. The trick here is changing the predicate, using the fact that the set (q % m) starting with s is (s + (s % m) + m*n) (where n represents the nth value in the set). In our case, s=q .
The only problem with this solution is that it has a side effect of making your implementation dependent on the template you choose (and not all templates have a suitable predicate). But this has the advantage that:
- There are always exactly n iterations
- Never work out like the solutions suggested above (refer to the limited
Range ).
In addition, no matter which template you choose, you will always need to change the predicate so that you can make it mathematically efficient:
static int[] givemeN(int n) { const int baseVal = 9; const int modVal = 3; int i = 0; return Array.ConvertAll<int, int>( new int[n], new Converter<int, int>( x => baseVal + (baseVal % modVal) + ((i++) * modVal) )); }
edit: I just want to illustrate how you can use this method with delegate to improve code reuse:
static int[] givemeN(int n, Func<int, int> func) { int i = 0; return Array.ConvertAll<int, int>(new int[n], new Converter<int, int>(a => func(i++))); }
You can use it with givemeN(5, i => 9 + 3 * i) . Note again that I changed the predicate, but you can do this with most simple templates as well.
source share