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:
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
good
ReplyDeletemy $input = 'a2b11c3d5';
ReplyDeletemy @input = split /(\d+)/, $input;
while (my($letter, $count) = splice @input, 0, 2) {
print $letter x $count;
}
$input =~ s{(\w+)(\d+)}{$1 x $2}eg;
ReplyDeleteVery nice. Better than what I came up with
Deletesub r { my( $l, $n, $cdr ) = ( shift =~ /^(.)(\d+)(.*)/ ); $l x $n . ($cdr ? r( $cdr ) : ""); }
@Anonymous: what is your print?
Deleteperl -e '$a = "a2b11c3d5"; $a =~ s/\d+//g; print "$a\n";'
ReplyDeleteit will print "abcd"
DeleteAnother Method:
ReplyDelete#!/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";
}
}
@Santosh: please check for syntax errors, i am not able to check your solution.
Delete