tags:

views:

66

answers:

1

Hi folks,

this code is part of NBuilder. I'm having a bad day .. and to prove it, I don't understand what this (simple) code is trying to do.

Here are the answers, with the code after it.

GetRandom.Phrase(5) == null or et or ut or do or elit or amet.. 
                       (nothing over 4 characters)
GetRandom.Phrase(4) == null or sit or sed or do .. 
                       (nothing over 3 characters)
GetRandom.Phrase(3) == null or et or ut or do  (nothing over 2 characters)
GetRandom.Phrase(2) == null 
GetRandom.Phrase(1) == null 

and the code...

private static readonly string[] latinWords = { "lorem", "ipsum", "dolor", 
    "sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do",
    "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore",
    "magna", "aliqua" };

public virtual string Phrase(int length)
{
    var count = latinWords.Length;
    var result = string.Empty;
    var done = false;
    while (!done)
    {
        var word = latinWords[Next(0, count - 1)];
        if (result.Length + word.Length + 1 > length)
        {
            done = true;
        }
        else
        {
            result += word + " ";
        }
    }
    return result.Trim();
}

I would have thought that the method should return x number of phrases or a random phrase of at least the length specified?

+2  A: 

The code returns a random phrase less than or equal to the length specified, in characters. The key is this line:

if (result.Length + word.Length + 1 > length)

This guarantees that the length in characters of the result (including the newly-added word) doesn't exceed the value of length.

JSBangs
so if i have pass in the number '50' .. would that keep adding phrases until it tries to add a phrase that EXCEEDS 50 and then stops?
Pure.Krome
I don't see where the randomness comes in to play tho.
griegs
@Pure.Krome, it would keep adding *words* until the next *word* would cause the *phrase* to exceed the specified length. At this point, the single *phrase* is returned.
Anthony Pegram
@griegs, it is in the unprovided `Next(int, int)` method.
Anthony Pegram
What an aptly named method Next is then. :)
griegs
@griegs, the Next method is part of C#'s Random class.
Lachlan
@JSBangs - awesome :) thanks heaps gents. much appreciated.
Pure.Krome