yonetpkbji
yonetpkbji

Reputation: 1019

Perl Inserting at incremented points in a sequence

I have a problem I am hoping someone could help with.

Using the following...

 my @sequence = (1..9);
 my $newSequence = join " - ", @sequence;

...I can print a hyphen seperated sequence of numbers 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9

The thing I am having problem with, and do not quite know the best logical way to solve, is a loop to increment the position of a variable string in the number sequence on each iteration (to produce the kind of output shown below).

my $varString = "DOG"

The output I am looking to achieve:

DOG - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - DOG - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - DOG - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - DOG - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - DOG - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - DOG - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - DOG - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - DOG - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - DOG

What would be the best way to go about doing this? Your help with this would be much appreciated, many thanks

Upvotes: 1

Views: 107

Answers (2)

Borodin
Borodin

Reputation: 126742

Am I missing something? Surely this is all that is required.

use strict;
use warnings;

my @sequence = 1 .. 9;

for my $i (0 .. $#sequence) {
  my @newseq = @sequence;
  $newseq[$i] = 'DOG';
  print join(' - ', @newseq), "\n";
}

output

DOG - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - DOG - 3 - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - DOG - 4 - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - DOG - 5 - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - DOG - 6 - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - DOG - 7 - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - DOG - 8 - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - DOG - 9
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - DOG

Update

Here's an alternative for people who are preoccupied about increasing the idle time time of their CPU. I offer it because it is clearer as well as faster than either solution presented so far. The output is identical.

use strict;
use warnings;

my @sequence = 1 .. 9;

for my $i (0 .. $#sequence) {
  local $sequence[$i] = 'DOG';
  my $s = join(' - ', @sequence);
}

Upvotes: 7

choroba
choroba

Reputation: 241968

A solution using array slices:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);

my $size = 9;
my @sequence = 1 .. $size;
for my $pos (0 .. $size - 1) {
    say join ' - ', @sequence[ 0 .. $pos - 1 ],
                    'DOG',
                    @sequence[ $pos + 1 .. $size - 1 ];
}

Upvotes: 3

Related Questions