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

Reply via email to