Apr 11, 2011 07:40 PM
(This post was last modified: Apr 11, 2011 08:46 PM by tflo.)
Coded in literally 10 minutes, mainly experimenting with the '?:' operators.
Source (Added Comments):
Screen Shot:
Source (Added Comments):
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class StringGenerator
{
/* global field(s) */
private Random provider;
public StringGenerator(int seed = -1)
{ /* specifing a default value makes the parameter optional.
* if the seed is the default value (-1) we are setting our random
* generator seed to the current system time in milliseconds, otherwise
* we are setting the seed to the user inputted.
* The ? : operators works like this:
* (condition) ? expression is true : expression is false;
*/
provider = new Random( (seed == -1) ? DateTime.Now.Millisecond : seed );
}
private char newChar(bool useUpper) /* determine whether or not to use upper case letters */
{
return (char)((provider.Next(64, 90) + 1) + ((useUpper && provider.Next(2) == 0) ? 32 : 0));
/* if useUpper is true and the random value is 0 it will
* add 32 to make the decimal value in the upper case letter bounds.
*/
}
private char newNum()
{
return (provider.Next(10) + "").ToCharArray()[0];
/* adding a blank string automatically casts the expression to a string.
* converting to a char array and getting the first position is more simple
* then doing the ASCII value of the numbers.
*/
}
public string Generate(int length, bool useUpperCase = true)
{
string output = ""; /* declare the return string */
for (int pos = 0; pos < length; pos++) /* basic for syntax (declaration, condition, mutation) */
output += (provider.Next(2) == 0) ? newChar(useUpperCase) : newNum();
/* if our random value is 0 adds a new character otherwise it adds a new number. */
return output;
}
}Screen Shot:


