SO rotate question
Pelle
pelle.mansson at gmail.com
Thu Sep 2 23:48:09 PDT 2010
On 09/02/2010 10:24 PM, bearophile wrote:
> simendsjo:
>> Suggestions for D-ifying the code is welcome.
>
> Your unit tests are not good enough, they miss some important corner cases.
> This my first version in D2:
>
> import std.string: indexOf;
>
> /// return True if s1 is a rotated version of s2
> bool isRotated(T)(T[] s1, T[] s2) {
> return (s1.length + s2.length == 0) ||
> (s1.length == s2.length&& indexOf(s1 ~ s1, s2) != -1);
> }
>
> unittest { // of isRotated
> assert(isRotated("", ""));
> assert(!isRotated("", "x"));
> assert(!isRotated("x", ""));
> assert(isRotated("x", "x"));
>
> string s = "rotato";
> assert(isRotated(s, "rotato"));
> assert(isRotated(s, "otator"));
> assert(isRotated(s, "tatoro"));
> assert(isRotated(s, "atorot"));
> assert(isRotated(s, "torota"));
> assert(isRotated(s, "orotat"));
>
> assert(!isRotated(s, "rotator"));
> assert(!isRotated(s, "rotat"));
> assert(!isRotated(s, "rotata"));
> }
>
> void main() {}
>
> Bye,
> bearophile
This is what I wrote:
bool isRotated(T)(T[] a, T[] b) {
return a.length == b.length && (a.length == 0 ||
canFind(chain(a,a), b));
}
Use chain to avoid allocation.
canFind isn't really the best possible name, is it?
More information about the Digitalmars-d-learn
mailing list