array of randomly generated names

Jesse Phillips jessekphillips+D at gmail.com
Fri Oct 15 20:51:19 PDT 2010


First listen to Jonathan. Data should be accepted in as strings and returned as strings (supporting wstring, dstring is fine). Your function should then build on a local dchar[] and convert it to string when finished. There are some algorithms that will help with the method you are using. However, if you wish to generate names you'll likely want to have more than just random letters. The examples below do not compile on ideone because of a bug in the 2.042 compiler used. They work with 2.049.

http://ideone.com/7c6cr

import alg = std.algorithm;
import std.stdio;
import std.string;
import std.conv;
import std.random;
 
string makeName(uint wordSize) {
    auto rnd = Random(unpredictableSeed);
    dchar[] newWord = new dchar[wordSize];
 
    alg.fill(newWord[], randomCover(lowercase[], rnd));
 
    return to!string(newWord);
}

void main() {
    writeln(makeName(6));
}

As you can see I did not build you an array of words, but this is just to push you in the correct direction. The slices of newWord and lowercase (provided by std.string) are required. And now that you know of a few nice library functions (std.algorithm.fill) Let us move on to creating a Range of names so you can make use of this to fill an array of names instead of letters.

http://ideone.com/jtbtn

As it is a larger piece of code I do not wish to duplicate it here. The code is mostly the same just stored in a struct and the functions: front, empty, popFront, save. By doing this you can use an assortment of functions found in std.algorithm[1]. Not all of functions will work with the Range I have created, as there are many types of ranges[2]: InputRange, OutputRange, ForwardRange, BidirectionalRange, RandomAccessRange, Infinite (I only covered InputRange, ForwardRange, Infinite). However that is really just the list of named ranges, there are even more requirements that may come up.

At last I digress. I hope your interest has been obtained on some of this and maybe it explains why some things just don't work as you are expecting. Any questions on a specific item you can start a new thread for.

And comments about the code from other onlookers is also welcome.

1. http://digitalmars.com/d/2.0/phobos/std_algorithm.html
2. http://digitalmars.com/d/2.0/phobos/std_range.html



More information about the Digitalmars-d-learn mailing list