Tuple Array Sorting

Biotronic simen.kjaras at gmail.com
Fri Dec 15 22:05:58 UTC 2017


On Friday, 15 December 2017 at 17:24:33 UTC, Vino wrote:
> Hi Biotronic,
>
>  I was able to find a solution using container array and also 
> date formatting, below is the code, please do let me know if 
> you find any issue, as i have tested the script and it is 
> working as expected.
>
> Program:
> import std.algorithm: filter, map, sort, each;
> import std.container.array;
> import std.file: SpanMode, dirEntries, isDir ;
> import std.stdio: writeln,writefln;
> import std.typecons: Tuple, tuple;
> import std.datetime.systime: SysTime;
> import std.conv;
> void main () {
> auto FFs =  ["C:\\Temp\\sapnas2\\BACKUP", 
> "C:\\Temp\\sapnas2\\EXPORT"];
> Array!(Tuple!(string, SysTime)) Sorted;
> foreach(d; FFs[]) {
> auto dFiles = Array!(Tuple!(string, SysTime))(dirEntries(d,

Why specify Array!(Tuple!(string, SysTime)) here? The return 
value from map should be perfectly fine, and if you really want 
an array I'd suggest writing
dirEntries(d, SpanMode.shallow)
     .filter!(a => a.isDir)
     .map!(a => tuple(a.name, a.timeCreated)))
     .array;
It's shorter, easier to read, and the speed difference should be 
miniscule at best. The same comment applies to Sorted, above, 
which could be defined as Tuple!(string, SysTime)[].

> SpanMode.shallow).filter!(a => a.isDir).map!(a => tuple(a.name, 
> a.timeCreated)));
> foreach(i; dFiles[]){ Sorted ~= i; }

No need for a foreach here, you can just do Sorted ~= dFiles.

> Sorted[].sort!((a,b) => a[1] > b[1]).each!(e => writefln!"%-63s 
> %.20s"(e[0], e[1].to!string));

You seem to be sorting and printing the Sorted array once per 
folder. Going back to [3,5,1], [6,2,4] example, this will print 
1,3,5,1,2,3,4,5,6. That is, it sorts [3,5,1], then prints the 
result. Then it sorts [1,3,5,6,2,4], and prints that. If you move 
the sorting and priting outside the loop (so it's the last line 
before leaving main), you should get the correct result, and and 
not waste time sorting the array multiple times.

> }
> }

In total, the changes I propose would lead to this code:

import std.algorithm: filter, map, sort, each;
import std.array : array;
import std.file: SpanMode, dirEntries, isDir ;
import std.stdio: writefln;
import std.typecons: Tuple, tuple;
import std.datetime.systime: SysTime;
import std.conv : to;
void main () {
     auto FFs =  ["C:\\Temp\\sapnas2\\BACKUP", 
"C:\\Temp\\sapnas2\\EXPORT"];
     Tuple!(string, SysTime)[] Sorted;
     foreach(d; FFs[]) {
         auto dFiles = dirEntries(d, SpanMode.shallow)
             .filter!(a => a.isDir)
             .map!(a => tuple(a.name, a.timeCreated))
             .array;
         Sorted ~= dFiles;
     }
     Sorted[].sort!((a,b) => a[1] > b[1])
         .each!(e => writefln!"%-63s %.20s"(e[0], e[1].to!string));
}

--
   Biotronic


More information about the Digitalmars-d-learn mailing list