in reply to Ignore a range of numbers ina List
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 ];
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Ignore a range of numbers ina List
by AnomalousMonk (Archbishop) on Jun 25, 2017 at 07:04 UTC | |
Re^2: Ignore a range of numbers ina List
by pr33 (Scribe) on Jun 25, 2017 at 07:11 UTC | |
by Marshall (Canon) on Jun 25, 2017 at 18:57 UTC | |
by Laurent_R (Canon) on Jun 25, 2017 at 22:52 UTC | |
by choroba (Cardinal) on Jun 25, 2017 at 23:05 UTC | |
by Laurent_R (Canon) on Jun 26, 2017 at 06:11 UTC | |
| |
by shmem (Chancellor) on Jun 25, 2017 at 19:28 UTC | |
by Anonymous Monk on Jun 25, 2017 at 19:53 UTC | |
by shmem (Chancellor) on Jun 25, 2017 at 20:28 UTC | |
Re^2: Ignore a range of numbers ina List
by pr33 (Scribe) on Jun 25, 2017 at 06:34 UTC |