Anyone have any idea how to sort number by length?
Ex : (11,111,122,12,2,13,21,15,211,22,213,2004)
I wanted the sorted array to be:
11 12 13 15 111 122 2 21 22 213 2004
The desired output seems to indicate you don't just want to sort by the number of digits, but rather first sort by the first digit and then by the length.
The desired output you show omits 211
, so I just put it where it belonged according to my understanding.
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
my @source = (11, 111, 122, 12, 2, 13, 21, 15, 211, 22, 213, 2004);
my @desired = (11, 12, 13, 15, 111, 122, 2, 21, 22, 211, 213, 2004);
my @sorted =sort {
substr($a, 0, 1) <=> substr($b, 0, 1) ||
length($a) <=> length($b) ||
$a <=> $b # thanks @ikegami
} @source;
is_deeply(\@sorted, \@desired, 'Sorted and desired are the same');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With