[MPlayer-dev-eng] Quiz
Felix Buenemann
atmosfear at users.sourceforge.net
Fri Nov 7 00:53:48 CET 2003
Hi Jonas,
On Thursday 06 November 2003 10:36, Jonas Fällman wrote:
> Why a so long and strange code (such as split:ing @_ to @_) when it can
> be done shorter (and probably a lot shorter than this one also):
>
> sub A{my($i)=@_;$i if(length($i)<4);@c=();while($i=~s/(.)//){$c[++$#c]=
> $1};for($i=0;$i<=($#c*20);$i++){$a=int(rand($#c)+1);$b=int(rand($#c)+1
> );next if $a==$b;$t=$c[$a];$c[$a]=$c[$b];$c[$b]=$t};return join("", at c)
> };while(<>){chomp();$z="";s/\b(\w)(\w*?)(\w)\b/sprintf("%s%s%s",$1,
> A($2),$3)/eg;print"$_\n"}
Well, first your code is more obfuscated (which wasn't my goal), but has bugs:
I guess you wanna write ... return $i if(length($i)<4); Although it really
should be 3 not 4 so it directly returns on strings of length 2. This has the
disadvantage that your code never exchanges strings of length 2 (it won't
even if you remove that line).
Then it should be my @c=(); and my $t=$c[$a] otherwise it won't compile with
use strict. The bogus $z var can be removed. I think your code mangles line
breaks (eg. \r\n ones).
Nicely formatted your code is 28 lines vs. my 23 lines and 400% slower =)
(320% with length($i)<4, even slower with 2 which would be correct, but isn't
handled correctly by your code, eg. 2 char string is never shuffled)
Btw. the splitting of $_[0] to @_ solves the purpose of creating an array of
chars from a string, it won't work without that line.
> /tarp
>
> (ps. yes I'm highly aware of how offtopic this is ;) )
/me too.
--
Best Regards,
Atmos
____________________________________________
- MPlayer Developer - http://mplayerhq.hu/ -
____________________________________________
---snip---
#!/usr/bin/perl -w
use strict;
#use locale;
sub A{
my($i)=@_;
return $i if(length($i)<3);
my @c=();
while($i =~ s/(.)//){
$c[++$#c]=$1;
}
for($i=0; $i <= ($#c*20); $i++){
$a=int(rand($#c)+1);
$b=int(rand($#c)+1);
next if $a==$b;
my $t=$c[$a];
$c[$a]=$c[$b];
$c[$b]=$t;
}
return join("", at c);
}
while(<>){
chomp();
s/\b(\w)(\w*?)(\w)\b/sprintf("%s%s%s",$1,A($2),$3)/eg;
print"$_\n"
}
---snip---
More information about the MPlayer-dev-eng
mailing list