in reply to reduce like iterators
#!/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
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.push ( @soln, $val ) if ( $soln[-1] ne $val );
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?").
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: reduce like iterators
by hippo (Archbishop) on Jan 11, 2024 at 17:37 UTC | |
by talexb (Chancellor) on Jan 11, 2024 at 23:28 UTC | |
by tybalt89 (Monsignor) on Jan 12, 2024 at 00:32 UTC |