Home > Back-end >  Generate a random number or null
Generate a random number or null

Time:07-11

I want to generate a random number or null. So lets say i have the option to fill in a number or leave a field blank (null) and now i wna tot generate one of the two. Generating a random number is easy using the Random class but i'm not sure how to let mij function return null occasionally. I hope someone has a good idea in stead of always return null if the number generated is divisable through lets say 3 or another static number. the number that are generated will be used for indexes of arrays and the arrays are reasonably small. Lets say between 2 and 10 items.

CodePudding user response:

User for example a negative one for null. Maybe like this:

Random r = new Random();
int? randomNumber;

randomNumber = r.Next(-1, 3); //put whatever range you want in here from negative to positive
            
if(randomNumber == -1)
{
    randomNumber = null;
}

CodePudding user response:

Following my comment above, I would suggest you generate a first random number between n options (based on how many odds you want the number to be null) and based on that outcome, decide to return null or a random number.

The function since can return a nullable int, must declare the type as nullable using int?.

this is an example using that strategy:

private void caller(){
    Random rnd = new Random();
    //generate 100 random numbers from a caller
    for(int i=0;i<100;i  )
        this.getNumber(rnd);
}    

private int? getNumber(Random rnd, int oddsOfBeingNull = 2){
    int nullOrNumber  = rnd.Next(1, oddsOfBeingNull);
    //if it's == 1, return null
    if(nullOrNumber == 1)
      return null;
    //else return a random number between 1-100
    return rnd.Next(1, 100);        
}

}

CodePudding user response:

This is a special edge case. The null scenario you wish to add to the possible results is something you will have to define its probability. I think it is reasonable and quite easy to pre-define a range for which you will return null to the user. Define this range based on the desired probability and add a simple range check after querying the random function. something like this:

private double? Random()
{
    var r = new Random();
    var result = r.NextDouble();
    if (result > 0.9)
        return null;
    return result;
}
  •  Tags:  
  • c#
  • Related