Splitting a range into a range of tuples
Dennis Ritchie via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jun 1 16:33:40 PDT 2015
On Monday, 1 June 2015 at 22:31:38 UTC, Adam wrote:
> Hi,
>
> I have a string of pairs of integers, where pairs are delimited
> from each other by commas, and members of the pair are
> delimited by a space. I'd like to end up with something like a
> range of 2-tuples
I can offer this option:
import std.stdio, std.algorithm, std.array, std.range,
std.format, std.typecons;
void main() {
string s = "192 14, 301 3, 578 0, 0 17";
int[] arr; int tmp;
foreach (el; s.split) {
formattedRead(el, "%s", &tmp);
arr ~= tmp;
}
Tuple!(int, int)[] tup;
foreach (el; zip(arr.stride(2), arr.dropOne.stride(2))) {
tup ~= tuple(el[0], el[1]);
}
tup.sort!"a[0] > b[0]";
writeln(tup);
}
/*[Tuple!(int, int)(578, 0), Tuple!(int, int)(301, 3),
Tuple!(int, int)(192, 14), Tuple!(int, int)(0, 17)]*/
More information about the Digitalmars-d-learn
mailing list