Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Re-ordering data branches in a [Tree::DAG_Node] tree

by kcott (Archbishop)
on Apr 23, 2018 at 10:36 UTC ( [id://1213420]=note: print w/replies, xml ) Need Help??


in reply to Re-ordering data branches in a [Tree::DAG_Node] tree

G'day atcroft,

Here's a method using non-destructive transliteration. It requires 5.14 (see perl5140delta: Non-destructive substitution). The guts of the solution is:

sort { $a =~ y/ //dr cmp $b =~ y/ //dr } @data

I've tested with your OP data and tybalt's offering:

#!/usr/bin/env perl use 5.014; use warnings; my @test_data = ( [ atcroft => [ 'a', # ' b', # ' e', # ' f', # ' g', # ' c', # ' d', # 'h', # ' i', # ' j', # ]], [ tybalt => [ 'j', # ' i', # ' h', # ' g', # ' f', # ' e', # ' d', # 'c', # ' b', # ' a', # ]], ); say_sorted(@$_) for @test_data; sub say_sorted { my ($who, $data) = @_; say "Data from $who"; say '-' x 20; say for @$data; say '-' x 20; say for sort { $a =~ y/ //dr cmp $b =~ y/ //dr } @$data; say '=' x 20; }

Output:

Data from atcroft -------------------- a b e f g c d h i j -------------------- a b c d e f g h i j ==================== Data from tybalt -------------------- j i h g f e d c b a -------------------- a b c d e f g h i j ====================

— Ken

Replies are listed 'Best First'.
Re^2: Re-ordering data branches in a [Tree::DAG_Node] tree
by tybalt89 (Monsignor) on Apr 23, 2018 at 14:38 UTC

    My understanding is the tree structure should be preserved - only sibling nodes can be swapped to sorted order.
    For instance, node 'b' is a child of node 'c' in my original data, and should still be a node of 'c' in the result. It is not.

    I think the result should be

    c b a j e d h g f i

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1213420]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (12)
As of 2024-04-23 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found