That's a nice problem. :) You may also want to show the code you've used to solve the first part of the problem, since I'm sure the Monks would relish the opportunity to see if they can come up with better/faster/cleaner solutions to that.
For the second part, my approach would be to model it as a state machine. There are two states: state 0 "we're looking at a section of numbers", and state 1 "we're looking at a section of X's". In state 0 we want to replace the number with the appropriate letter A or B; in state 1 we want to leave the X as X; and at one of the transitions - I've chosen the "up" transition from state 0 to state 1 - we want to flip the letter we will replace with between A and B:
# transition: -up- -down- -up- -down- -up- +-down- # state: 0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 + 1 0 0 my $input = "1-2-3-4-X-X-X-X-X-X-11-12-13-X-X-X-X-X-19-20-21-X-X-X-X-X +-X-28-29"; my $output = part2($input); print "$output\n"; sub part2 { my($input) = @_; my $state = 1; my @replace = ("A", "B"); my $replace_index = 0; # start at 'A' $input =~ s{ ( \d+ | X ) (?# match a number or X) (?= - | \z) (?# followed by '-' or end of string) }{ # capture the old state, to detect transitions my $prev_state = $state; # decide the new state $state = ($1 eq 'X') ? 1 : 0; if ($state == 0) { # state 0: return the replacement character $replace[$replace_index]; } else { # state 1: did we transition? if ($prev_state == 0) { # flip the replacement character between 'A' and 'B' $replace_index = 1 - $replace_index; } # return the matched value, ie don't change anything $1; } }exg; return $input; }
Note that I initialize the state machine to be in state 1, so that if the input starts with a section of Xs we will still use "A" as the first replacement character - "X-2" will be translated to "X-A". If I had started in state 0, the initial X would be seen as a transition so we would immediately flip the replacement character to be B, and "X-2" would be translated to "X-B". (This is also the reason I chose to flip on the 0-to-1 transition rather than on the 1-to-0 transition.) If you would rather have "X-2" become "X-B", then just change the initial state to be 0.
In reply to Re: Help making this substitutions on a strin
by hv
in thread Help making this substitutions on a strin
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |