#!/usr/bin/perl # 2024-0111: From the node: "Eliminate consecutive duplicates of list # elements. If a list contains repeated elements they should be # replaced with a single copy of the element. The order of the # elements should not be changed." use strict; use warnings; { my @orig = qw/a a a a b c c a a d e e e e/; my @correct = qw/a b c a d e/; my @soln; for ( push ( @soln, shift @orig ); @orig; ) { my $val = shift @orig; if ( $soln[-1] ne $val ) { push ( @soln, $val ); } } print "Correct solution is @correct;\n"; print "My solution is @soln.\n"; }

Because my background (before Perl) is in C, that automatically looks like a for loop problem to me. In other words, you need to prime the pump so that you're not forced into doing something Really Clever for the first element.

And I could have written

push ( @soln, $val ) if ( $soln[-1] ne $val );
to make it more Perl-ish, but I'm not a fan of the postfix syntax. My OldSchool brain wants to see an if statement at the beginning of the line.

And, yes, this assumes that the list is string values (or stringable values), and does not deal with the undef value. That reminds me of a Google interview that I had a while back ("What about this ridiculous limitation to the solution?" "And how about this even more insane exception?").

Alex / talexb / Toronto

Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.


In reply to Re: reduce like iterators by talexb
in thread reduce like iterators by LanX

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.