Skipping or Stepping Through an Array?
Ferhat Kurtulmuş
aferust at gmail.com
Wed Oct 21 13:04:40 UTC 2020
On Wednesday, 21 October 2020 at 11:55:54 UTC, DMon wrote:
> What is the simplest way to output every nth element of an
> array?
>
> I can do it using a for loop:
> void main()
> {
> int[5] a = [1,2,3,4,5];
>
> for (int i = 0 ; i <= 4 ; i += 2)
> {
> writeln(a[i]);
> }
> }
>
> Basically, I am wondering if I missed something.
In addition to the drug's solution, this reminds me of the chunks
of std.range.
import std.range;
import std.stdio;
void main(){
auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto chunks = chunks(source, 2);
writeln(chunks[0]); // [1, 2]
foreach(c; chunks)
writeln(c[1]);
}
output:
2
4
6
8
10
More information about the Digitalmars-d-learn
mailing list