11 August 2014

Quiz 7: Expand the string- Alphabet followed by number to alphabet only

Problem:
Expand the string- Alphabet followed by number to alphabet only

Sample Input:
a2b11c3d5

Sample Output:
aabbbbbbbbbbbcccddddd

Solution:

my $a = "a2b11c3d5";
my @arr = split(/(\d+)/, $a);
for(my $i=0;$i<@arr;$i++)
    {
     for(my $j=0;$j<$arr[$i+1];$j++)
         {
         print "$arr[$i]";
         }
     $i++;
     }

Tips:
  • parenthesis() preserves digits also, without it split will only return alphabets

9 comments:

  1. my $input = 'a2b11c3d5';
    my @input = split /(\d+)/, $input;

    while (my($letter, $count) = splice @input, 0, 2) {
    print $letter x $count;
    }

    ReplyDelete
  2. $input =~ s{(\w+)(\d+)}{$1 x $2}eg;

    ReplyDelete
    Replies
    1. Very nice. Better than what I came up with

      sub r { my( $l, $n, $cdr ) = ( shift =~ /^(.)(\d+)(.*)/ ); $l x $n . ($cdr ? r( $cdr ) : ""); }

      Delete
    2. @Anonymous: what is your print?

      Delete
  3. perl -e '$a = "a2b11c3d5"; $a =~ s/\d+//g; print "$a\n";'

    ReplyDelete
  4. Another Method:

    #!/usr/bin/perl -w
    use strict;


    print "Enter the alphabet followed by number:";
    my %input = split(/\s+/,<>);

    my @key1 = keys %input;
    my @values1 = values %input;

    chomp(@key1);
    chomp(@values1);
    foreach my $r(@key1)
    {
    for(my $i=0;$i<$input{$r};$i++)
    {
    push(my @final,$r);
    print "@final";
    }
    }

    ReplyDelete
    Replies
    1. @Santosh: please check for syntax errors, i am not able to check your solution.

      Delete