Sellecting randomly from a range

Jesse Phillips JesseKPhillips at gmail.com
Sun May 17 15:08:26 PDT 2009


This is more a tutorial which I'll put up on a wiki, but one question I have is why can't 0..8 work in a randomCover, and wouldn't it be nice to use regex for creating a range ("[A-Z]" being all uppercase letters)?

Selecting randomly from a collection of elements is common and usually entails selecting random numbers and making sure they haven't been used before. D2 has several templated functions that when put together make this very easy.

The first thing to look at comes from std.random, randomCover(range, rnd). This takes the range of items and creates a new range that is a random representation of the elements.

Then found in std.range is take(count, range). This will give us the count items from our range giving us yet another range. From here we are able to use a foreach loop to grab each item, but what if we want to store this someplace for latter use?

This brings us to std.algorithms where we find fill(range1, range2). It is important to note that D arrays can be use as a range.

If we combine this with D's array slices you are able to fill the results from two ranges. The code below is an example using all of this and selecting a random number of elements from each list.

(If this ends up being poorly formatted I apologize http://paste.dprogramming.com/dpi1a1wn )

import std.algorithm;
import std.random;
import std.range;
import std.stdio;

string[] list =  ["one", "two", "three", "four", "five"];
string[] list2 = ["1", "2", "3", "4", "5"];

void main(string[] args) {
   auto rnd = new Random(unpredictableSeed);

   int count = uniform(1, list.length, rnd);

   string[] result = new string[count*2];

   fill(result[0..count], take(count, randomCover(list, rnd)));
   fill(result[count..$], take(count, randomCover(list2, rnd)));

   writeln(result);
}


More information about the Digitalmars-d-learn mailing list