Adjacent item in a array

Seb seb at wilzba.ch
Sat Feb 3 19:28:01 UTC 2018


On Saturday, 3 February 2018 at 19:13:05 UTC, Vino wrote:
> Hi All,
>
>  Request you help on printing an array in below,
>
> Eg:
>
> Array ("T1", "T2", "T3", "T4", "T5")
>
> Output required as below
>
> T1,T2
> T2,T3
> T3,T4
> T4,T5
>
>
> From,
> Vino.B

2.079 [1, 2] will ship with slide:

---
auto arr = ["T1", "T2", "T3", "T4", "T5"];
arr.slide(2).each!writeln;
---

https://run.dlang.io/is/YZsQCf

slide is super-powered with a lot of nice things to generate 
sliding windows lazily, but for this simple case, it's enough to 
do:

---
auto arr = ["T1", "T2", "T3", "T4", "T5"];
arr.zip(arr.dropOne).each!(a => writefln("%s,%s", a[0], a[1]));
---

https://run.dlang.io/is/R6IyYV


or of course, as Adam pointed out, good 'ld array iteration works 
too:

---
auto arr = ["T1", "T2", "T3", "T4", "T5"];
foreach (i; 0 .. arr.length - 1)
     writefln("%s,%s", arr[i], arr[i + 1]);
---
https://run.dlang.io/is/fb3JYI

[1] https://dlang.org/changelog/pending.html#std-range-slide
[2] https://dlang.org/phobos-prerelease/std_range.html#slide


More information about the Digitalmars-d-learn mailing list