in reply to Transposition of each letter pair in string

Here's a Perl regexical way: s/(.)(.)/$2$1/g;

Update: If you must exchange them one by one to percolate the first character over to the last, I won't help. I'd just say: s/(.)(.*)/$2$1/; That's fairly close to my original.

Update2: What you say doesn't describe what you have. Nevermind, I'll let the psychics figure it out.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Transposition of each letter pair in string
by sauoq (Abbot) on Dec 27, 2002 at 05:00 UTC

    That doesn't match his example very well. I would think it was a fine solution except he said his example works. His example seems to return (or print really) a list consisting of every possible reversal of a single pair of neighboring letters. I.e. transposition_list('foobar') would be the list ('ofobar', 'foobar', 'foboar', 'foobra'). I'm not sure how to handle double letters like the 'oo' in 'foo' but his doesn't handle them specially.

    I don't know if I really would do it this way but here is my untested first crack at it:

    print "$_\n" for transposition_list('thisisatest'); sub transposition_list { my $string = shift; my @transpositions; for my $i (0 .. length($string)-2) { (my $tmp = $string) =~ s/(.{$i})(.)(.)/$1$3$2/; push @transpositions, $tmp; } return @transpositions; }
    -sauoq
    "My two cents aren't worth a dime.";