Tuple Array Sorting
Biotronic
simen.kjaras at gmail.com
Tue Dec 12 19:00:01 UTC 2017
On Tuesday, 12 December 2017 at 15:19:35 UTC, Vino wrote:
> import std.algorithm: filter, map, sort;
> import std.container.array;
> import std.file: SpanMode, dirEntries, isDir ;
> import std.stdio: writefln;
> import std.typecons: Tuple, tuple;
> import std.datetime.systime: SysTime;
>
> void main () {
> auto FFs = ["C:\\Temp\\sapnas2\\BACKUP",
> "C:\\Temp\\sapnas2\\EXPORT", "C:\\Temp\\sapnas2\\PROD_TEAM"];
> Array!(Tuple!(string, SysTime)) Result;
> foreach(d; FFs[]) {
> auto dFiles = Array!(Tuple!(string, SysTime))(dirEntries(d,
> SpanMode.shallow).filter!(a => a.isDir).map!(a => tuple(a.name,
> a.timeCreated)));
> foreach(e; dFiles) { Result ~= e; } }
> writefln("%(%-(%-63s %.20s %)\n%)", Result[].sort!((a, b)
> => a[1] < b[1]));
> }
Since there's little need to extract timeCreated and name before
sorting, here's a version that doesn't:
import std.algorithm : map, filter, sort;
import std.array : array;
import std.range : join;
import std.file : SpanMode, dirEntries, isDir;
import std.stdio : writefln;
import std.typecons : tuple;
void main() {
auto folders = [`C:\Windows`, `C:\Program Files`, `C:\Users`];
auto sorted = folders
.map!(f => f.dirEntries(SpanMode.shallow))
.join
.filter!(e => e.isDir)
.array
.sort!((a,b) => a.timeCreated < b.timeCreated)
.map!(e => tuple(e.name, e.timeCreated.toSimpleString[0
.. 20]));
writefln("%(%-(%-63s %s %)\n%)", sorted);
}
And a version with normal loops, since the heavily range-based
version above can be a bit dense. These programs do essentially
the same thing:
import std.algorithm : sort;
import std.array : array;
import std.file : SpanMode, dirEntries, DirEntry, isDir;
import std.stdio : writefln;
import std.typecons : tuple, Tuple;
void main() {
auto folders = [`C:\Windows`, `C:\Program Files`, `C:\Users`];
DirEntry[] subFolders;
foreach (folder; folders) {
auto children = dirEntries(folder, SpanMode.shallow);
foreach (child; children) {
if (child.isDir) subFolders ~= child;
}
}
subFolders.sort!((a,b) => a.timeCreated < b.timeCreated);
Tuple!(string, string)[] interestingParts;
foreach (subFolder; subFolders) {
interestingParts ~= tuple(subFolder.name,
subFolder.timeCreated.toSimpleString[0..20]);
}
writefln("%(%-(%-63s %s %)\n%)", interestingParts);
}
As you can see, I'm just chopping off the parts I don't like from
toSimpleString. It seems a good format function for dates does
not exist in Phobos.
--
Biotronic
More information about the Digitalmars-d-learn
mailing list