I added some test cases.
- I assume that some sequence that starts with 6 but never has a "terminating" "7" means that those numbers appear in the result.
- sequence starts on the "first 6" and ends on "next 7" (if it ends at all, see previous)
- A "7" that occurs without a previous matching "6" is part of the results
I wasn't sure if using splice was an absolute requirement, so I didn't use it. Also, as a general rule, I try to avoid using indicies. Code using indicies tends to be more error prone due to the dreaded "off by one" error which even very experienced programmers are prone to make.
In the code below, once a 6 is seen, I keep the numbers on a stack so that I can use them later if no matching 7 is found. The scalar value of @stack also does double duty as the "seen a 6 - inside of a potential sequence flag". I think the logic here is clear albeit a bit wordy. However well spaced out, simple code tends to run very quickly and I don't consider a bunch of white space a "problem"
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
#http://www.perlmonks.org/?node_id=1193467
my $aref = [1, 7, 6, 2, 2, 7, 1, 6, 99, 99,7,88, 7, 6,1,2,3];
my @result;
my @stack = ();
foreach my $candidate (@$aref)
{
if ($candidate == 6) # starting flag
{
push @stack,6;
}
elsif ($candidate == 7) #potential ending flag
{
if (@stack)
{
@stack=(); #throw away between 6, x, y, 7
}
else
{
push @result, 7; # a singleton 7 was seen
}
}
elsif (@stack) # inside of sequence starting with 6
{
push @stack, $candidate;
}
else
{
push @result, $candidate;
}
}
push @result, @stack if @stack; # unfinished sequence starting with 6?
print Dumper \@result;
__END__
prints:
$VAR1 = [
1,
7,
1,
88,
7,
6,
1,
2,
3
];
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.