go ahead... be a heretic | |
PerlMonks |
Re: move all 0s in an array to the beginning keeping other elements order sameby davido (Cardinal) |
on May 01, 2014 at 22:10 UTC ( [id://1084697]=note: print w/replies, xml ) | Need Help?? |
This is partitioning, and there's a utility in List::MoreUtils to facilitate it:
The output will be:
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:
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
In Section
Seekers of Perl Wisdom
|
|