Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: move all 0s in an array to the beginning keeping other elements order same

by davido (Cardinal)
on May 01, 2014 at 22:10 UTC ( [id://1084697]=note: print w/replies, xml ) Need Help??


in reply to move all 0s in an array to the beginning keeping other elements order same

This is partitioning, and there's a utility in List::MoreUtils to facilitate it:

use feature 'say'; use List::MoreUtils 'part'; @array = (1, 2, 3, 4, 2, 1, 2, 0, 1, 0, 0); say join ' ', map { @$_ } part { !!$_ } @array;

The output will be:

0 0 0 1 2 3 4 2 1 2 1

Update: (Off topic) I supposed that there would be an equally elegant solution to this using Racket (a Lisp dialect based on Scheme). ...and there probably is, but with my limited vocabulary this is what I came up with:

(define array (list 1 2 3 4 2 1 2 0 1 0 0)) (let-values ([(x y) (partition (lambda (x) (< x 1)) array)]) (flatten (list x y)))

I'm wondering if there's a better WTDI.

Update2: As I look again a few hours later I do think the Racket/Scheme solution is fine. Read it from the inside outward: Start with a list named 'array', partition it based on the conditional within the lambda function (similar to the code-ref passed to "part" in Perl). That produces two lists, just like Perl's "part" generates two array refs. Finally gather into 'x' and 'y' those two lists ("let-values" does this, since the minimal syntax doesn't have anything analogous to Perl's "@{$aref}" , and flatten them into a single list, which is what map's coderef is doing for us in the Perl solution. The clutter is because Lisp has almost no syntax beyond ( parens ). This solution is so similar to the Perl one I wrote, perhaps it's proof that you can write Lisp in Perl. Or maybe that you can write Perl in Lisp. ;)

From the benchmarks posted below I see that the 'part' solution falls in the middle of the pack for performance, which probably lends support for the common expression, "Lisp programmers know the value of everything and the cost of nothing."


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2024-04-24 04:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found