in reply to Scrambling help

Using substr and reverse ?

I read that, as a puzzle to solve it without substr and reverse.

Enjoy.

sub scramble { (my $str, my $toshuf) = @_; my $len = length($str); if($toshuf * 2 > $len){ return "!error-rorre!"; } $str = lc($str); my @idx = (); my $i = $toshuf; push(@idx, $i--) while $i; push(@idx, ($toshuf + 1) .. ($len - $toshuf)); push(@idx, $len - $i++) while $i < $toshuf; return sprintf(join("", map({"%$_\$s"} @idx)), split(//, $str)); }

Replies are listed 'Best First'.
Re^2: Scrambling help
by Anonymous Monk on Jan 27, 2015 at 21:53 UTC
    Come on! That smells like C. Not enough line noise, IMO! We obviously need regex :)
    use strict; use warnings; sub scramble { lc $_[0] =~ s{(^.{$_[1]}|.{$_[1]}$)} {join '', (split '', $1)[map -$_, 1..$_[1]]}reg; } print scramble( "Institute", 3 ), "\n"; print scramble( "Babraham", 2 ), "\n";