[DGD] Resolve Path & Array Efficiency

Kris Van Hees aedil at alchar.org
Sat Feb 21 20:08:20 CET 2004


My contribution of my favourite algorithm to resolve relative paths into
absolute paths (after dealing with ~, and all):

    for (i = j = l = sizeof(parts = explode(path, "/")); i; )
        switch (parts[--i]) {
            case "":
            case ".":
                continue;
            case "..":
                skip++;
                continue;
            default:
                if (skip) {
                    skip--;
                    continue;
                }

                parts[--j] = parts[i];
        }

    return parts[j ..];

The advantage is that no new array is being created, nor is it doing any
slicing of the original array, until the return statement.  Note that it also
resolves from the back to the front of the path.

	Cheers,
	Kris

On Fri, Feb 20, 2004 at 07:52:20PM -0500, Michael McKiel wrote:
> I have come up with the follow way to resolve ".." in directory paths:
> /* Dirs has previously exploded path, and had "" & "." removed, as
>  * well as '~' /home/ recognition */
>     for (i=0, sz=sizeof(dirs); i < sz; )
>     {
>         if (dirs[i] == "..")
>         {
>             dirs[i] = nil;
>             sz -= (( i == 0 ) ? 1 : 2);
>             i  -= (( i == 0 ) ? 0 : 1);
>             dirs[i] = nil;
>             dirs -= ({ nil });
>         }
>         else
>         {
>             i++;
>         }
>     }
> 
> Now I know efficiency hardly matters when dealing with such a small number of
> elements of an array, but what I was wondering - when dealing with MUCH
> larger array's would it be more/less efficient to be removing ({ nil })
> elements or to rebuild the array's via concatenation: 
>     dirs = dirs[#1 .. #2] + dirs[#3 .. #4];
> 
> Or is there really any difference at all? 
> In this instance the code is much easier to read, and more recursive-like,
> than the resolve_path() that comes with Melville standard. Which perhaps can
> be a more relevant issue than efficiency sometimes I suppose :)
> 
> 
> 
> ______________________________________________________________________ 
> Post your free ad now! http://personals.yahoo.ca
> _________________________________________________________________
> List config page:  http://list.imaginary.com/mailman/listinfo/dgd

-- 
Never underestimate a Mage with:
 - the Intelligence to cast Magic Missile,
 - the Constitution to survive the first hit, and
 - the Dexterity to run fast enough to avoid being hit a second time.
_________________________________________________________________
List config page:  http://list.imaginary.com/mailman/listinfo/dgd



More information about the DGD mailing list