Re: [Nolug] php: list sorting algorithm help

From: Clinton R. Nixon <crnixon_at_anvilwerks.com>
Date: Tue, 23 Dec 2003 22:45:14 -0600
Message-Id: <200312232245.14456.crnixon@anvilwerks.com>

On Tue December 23 2003 23:03, Christopher M. Jones wrote:
> I need an algorithm to sort a list in the following way (in php):

Cripes. I re-read your e-mail and it made more sense.

Ok. Let's assume that your data structure is an array of arrays. Without more
information, that's all I can figure. This is PHP/Perl-esque pseudo-code.

@a = ( (1, 0),
            (2, 1),
            (8, 1),
      (3, 2),
      (7, 2),
      (4, 3),
      (5, 3),
      (6, 3),
      (9, 8),
      (10, 9)

Now, barring the fact that a simple sort of the first value will produce a
correct list, let's look at what you need to do. I'm going to do something
that you really didn't ask for, but watch - I think it's what you're going
for.

for $elem (@a) {
        push @b{$a[1]}, $a[0];
}

What I'm doing here is making an array of the elements that belong to each
topic and putting them all in a hash. What you should end up with is:

@b{0} = (1)
@b{1} = (2, 8)
@b{2} = (3, 7)
@b{3} = (4, 5, 6)
@b{8} = (9)
@b{9} = (10)

If you want to get a printed list like you have there, this should work:

sub print_list (%list, $top, $indent) {
        for $sublist (@list{$top}) {
                print $indent . $sublist . " / " . $top;
                if (exists @list{$sublist}) {
                        print_list(%list, $sublist, $indent . "---")
                }
        }
}

A little data structure and recursive programming magic, and you're there.
Warning: all of this is off the top of my head; I didn't check PHP syntax,
since I can't remember it; and it can't be completely right. Still, I hope
this points you in the right direction.

- Clinton
___________________
Nolug mailing list
nolug@nolug.org
Received on 12/23/03

This archive was generated by hypermail 2.2.0 : 12/19/08 EST