Hello,

The solution of @Athanasius will have problems if you switch place bw 50 and 100 at the input data. My solution below is quite ugly but i think it will be more complete

NOTE: This solution requires that the columns of each input data must be aligned by the end character. But you can change my algorithm a little bit to adapt if you want.

Data Example:

Data Not Ok 100 123 1.......1 Data Ok 100 123 1.........1

Here is my solution:

use strict; use warnings; my @row; while(my $line = <DATA>) { my @arr; while(my ($elem) = $line =~ /(\s*\d+)/g) { push @arr, $elem; $line =~ s/(\s*$elem)/' ' x length($1)/e; } #Data 1014 1 10 #becomes 3 element "1014", " 1", " + 10" push @row, \@arr; } #Sort element with same length, exchange position foreach my $r1 (0 .. $#row) { #Take 1 row as base, check other rows my @remain = grep !/$r1/,(0 .. $#row); foreach my $r2 (0..$#remain) { #Foreach element in row, find element with same length #in different row (mean same column) -> check value and exchang +e foreach my $c1 (0..$#{$row[$r1]}) { foreach my $c2 (0..$#{$row[$r2]}) { compare_wrap($row[$r1][$c1], $row[$r2][$c2]); + } } } } map {print merge_str(@$_),"\n"} @row; #SUPPORT FUNCTION sub compare_wrap { if( length($_[0]) == length($_[1]) && eval($_[0]) < eval($_[1])) + { @_[0, 1] = @_[1, 0]; } } sub merge_str { foreach my $i (1 .. $#_) { my $temp = ' ' x length($_[$i-1]); $_[$i] =~ s/$temp/$_[$i-1]/; } $_[-1]; } __DATA__ 1014 1 10 1015 51 100 20 1016 11 101 1017 15 101

P/S: Update compare_wrap() as suggestion from kcott, sorry for that mis-spelling :]] !

Hope this could help :)

Regards,

ThBo


In reply to Re: Sorting a matrix based on the values of columns by redbull2012
in thread Sorting a matrix based on the values of columns by raghuprasad241

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.