Random string samples & unicode - Reprise

bearophile bearophileHUGS at lycos.com
Sun Sep 12 18:58:09 PDT 2010


Andrei Alexandrescu:
> > from random import sample
> > d = "0123456789"
> > print "".join(sample(d, 2))
> 
> Well it's not that common code. How often would one need to generate a 
> string that contains two random but distinct digits?

It's not easy to give a good answer to this question. In Python it's normal code, almost common.
Google Code Search gives 27 answers:
http://www.google.com/codesearch?hl=en&lr=&q=%22.join%28sample%28%22+lang%3Apython&sbtn=Search

Think about a "Bulls and cows" game (it's a task of Rosettacode site), it's similar to MasterMind, at the beginning you need to generate the secret key, four random distinct digits, that later are used in the program, the user has to guess them using the number of right items in the right place, or right items in the wrong place. To generate the key in Python you may use "".join(sample(d, 4)).


> The code compiles and runs as written on my system.

Sorry. I have used the normal DMD 2.048, I don't use the svn head :-)


> I think it's David 
> Simcha who changed the return type to ForEachType!Range[]. I'm not sure 
> I agree with that, as it takes an oddity of foreach that I hoped would 
> go away some time and propagates it.

I see. If there is something you don't like about this situation, then I think it's a good moment to discuss it :-)


> About the original problem: strings are bidirectional ranges of dchar, 
> which is the way they ought to be. Algorithms used on top of strings 
> will inherently traffic in dchar. If you want to get a string back, this 
> should work:
> 
> string res = to!string(take(randomCover(d, rndGen), 2));

OK, I accept this (but what you have just said has some consequences). Thank you for your answer.

With one of my suggestions:
http://d.puremagic.com/issues/show_bug.cgi?id=4851
that line becomes
string res = to!string(take(randomCover(d), 2));


> That doesn't work for a different reason, and is a bug worth filing. In 
> fact - no need, I just submitted a fix 
> (http://www.dsource.org/projects/phobos/changeset/1988). Thanks for 
> bringing this up!

You are welcome and thank you for the answers and the fix.

Bye,
bearophile


More information about the Digitalmars-d mailing list