Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Most shuffled array

by Athanasius (Archbishop)
on Aug 24, 2014 at 15:42 UTC ( [id://1098461]=note: print w/replies, xml ) Need Help??


in reply to Most shuffled array

Hello vagabonding electron,

Good job! In playing around with the code, I found that the @tmp array can be removed, along with half of the “ugly hack” —

#! perl use strict; use warnings FATAL => 'all'; use experimental 'smartmatch'; use List::MoreUtils 'zip'; use Test::More tests => 7; while (<DATA>) { my ($left, $right) = split /->/; my @array = split ' ', $left; my @expected = split ' ', $right; my $aa = unsort(\@array); ok( @$aa ~~ @expected ); } sub unsort { my $aref = shift; @$aref = sort { $a <=> $b } @$aref; my %nums = map { $_ => undef } @$aref; return $aref if scalar keys %nums == 1; my $half = int(($#$aref + 2) / 2); if (scalar keys %nums == 2) { if ($aref->[$half - 1] == $aref->[$#$aref]) { @$aref = (@$aref[$half .. $#$aref ], @$aref[0 .. $half - 1]); @$aref[$half - 1, $#$aref] = @$aref[$#$aref, $half - 1]; } } else { for my $i (0 .. $half - 1) { last if $i + $half > $#$aref; if ($aref->[$i] == $aref->[$i + $half - 1]) { @$aref = (@$aref[$i .. $#$aref], @$aref[0 .. $i - 1]); } } } my @first = @$aref[0 .. $half - 1]; my @second = @$aref[$half .. $#$aref ]; @$aref = zip @first, @second; pop @$aref unless defined $aref->[-1]; return $aref; } __DATA__ 0 0 1 -> 0 1 0 0 1 1 -> 1 0 1 1 2 3 3 2 2 1 -> 1 2 1 3 2 3 2 3 2 1 2 1 3 2 -> 1 2 1 3 2 3 2 1 3 3 3 3 1 1 -> 3 1 3 1 3 1 3 1 1 1 2 3 -> 1 2 1 3 1 1 1 1 2 3 3 2 2 1 -> 1 2 1 2 1 3 1 3 2

Hope this is of interest,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Most shuffled array
by vagabonding electron (Curate) on Aug 24, 2014 at 16:36 UTC

    Hi Athanasius , and many thanks for improving the code! I see now that @tmp can indeed be removed... and the ugly hack as well :-)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-19 09:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found