Swapping nibbles range style

bearophile bearophileHUGS at lycos.com
Tue Dec 10 15:39:02 PST 2013


A nibble is 4 bits. Working with strings like this is not so 
efficient.

Two more versions of the OP code, the second is a little more 
efficient:


import std.stdio, std.algorithm, std.range, std.string;

string swapAdjacent(in string s) pure
in {
     assert(s.length % 2 == 0);
     assert(s.all!(c => c < 128));
} out(result) {
     assert(result.length == s.length);
} body {
     return s
            .chunks(2)
            .map!(c => [cast(char)c.dropOne.front, 
cast(char)c.front])
            .join;
}

string swapAdjacent2(in string s) pure
in {
     assert(s.length % 2 == 0);
     assert(s.all!(c => c < 128));
} out(result) {
     assert(result.length == s.length);
} body {
     auto result = new char[s.length];
     foreach (immutable i, ref c; result)
         c = s[i + (i & 1 ? -1 : 1)];
     return result;
}

void main() {
     "0123456789ABCDEF".swapAdjacent.writeln;
     "0123456789ABCDEF".swapAdjacent2.writeln;
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list