Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am working on ad an app...In this app I need to get a random number among some provided numbers..I want the computer the give a number itself from the options given and with each time different number....For example i give the computer some numbers in code like 1,2,3,4,5,6 and it randomly chooses different numbers in every execution. i.e sometimes it give 3 sometimes 4 or any other...I hope i make myself clear.....Thanks in advance.....


Regards,
Ahsan Naveed
Posted
Comments
Ahsan98 15-Feb-14 3:11am    
everyone plz take a look at my another question and plz help if you can i shall be very thankful........The other question

There are ways to do this, but...it takes a little work.
The whole idea of random numbers is that they are just that: random over a specified phase space. So the chances are that the same number can be repeated in successive "throws", just line a coin can come up heads six times in a row, or a dice throw a "2" repeatedly.

If you want to issue numbers only from a particular set, and with no repeats, then you have to keep a list of all "possible" numbers, and copy it into a separate list from which a number is selected at random. The selected number is then removed from the list so it can't be drawn again. When the list is empty, you copy the original numbers back and start again.

It's not complex - a list can handle it easily, or even an array for small sample sets if you manually "shuffle" the ones above the one you remove - but it does take a little work.


"i just want simple random number....The repetition of no. does not matter unless its comes different....Please just tell my a simple example an easy method by code to get random no......just give me a little example of code i dont know the use of arrays much plz tell me the siple and easy way some repetition is totally fine....."

Try this:
C#
private int[] AllowedValues = new int[] { 1, 2, 3, 5, 7, 11 };
private Random rand = new Random();

private int GetRandomNumber()
    {
    return AllowedValues[rand.Next(AllowedValues.Length)];
    }

private void myButton_Click(object sender, EventArgs e)
    {
    for (int i = 0; i < 20; i++)
        {
        Console.WriteLine(GetRandomNumber());
        }
    }
 
Share this answer
 
v2
Comments
Ahsan98 15-Feb-14 3:45am    
i just want simple random number....The repetition of no. does not matter unless its comes different....Please just tell my a simple example an easy method by code to get random no......just give me a little example of code i dont know the use of arrays much plz tell me the siple and easy way some repetition is totally fine.....
OriginalGriff 15-Feb-14 4:07am    
Answer updated.
Ahsan98 15-Feb-14 6:35am    
thanks very much...
OriginalGriff 15-Feb-14 6:46am    
You're welcome!
Place the numbers in array, then pick them from the array through random position number. You should be able to get the ideas here: how-to-get-random-values-from-array-in-c-sharp[^]
 
Share this answer
 
v3
Try this:
C#
var chars = "ABCDEFGHIJKLMNOPQRSTUVWX0123456789";//or TextBox1.Text
var Randomchar = new Random();

var reschar = new string(Enumerable.Repeat(chars, 10).Select(n => n[Randomchar.Next(n.Length)]).ToArray());
 
Share this answer
 
If you want a series of random numbers drawn from a group of numbers not in sequence, with no repetition, then you can try this:
C#
Random randomGenerator = new Random();

private List<int> selectRandomFrom = new List<int>
{
    1, 24, 13, 12, 9, 3, 5, 8, 2, 499
};

// for analyzing the number of hits for each list item
private Dictionary<int,> nHits = new Dictionary<int,>();

private void TestRandomSelection()
{
    foreach (var i in selectRandomFrom) nHits.Add(i, 0);
    
    int lastRandomInt = -999;
    
    int x = 0;
    
    int numberOfReTries = 0;
    
    // 100k selections
    for (int i = 0; i < 100000; i++)    
    {
        while (true)
        {
            x = selectRandomFrom[randomGenerator.Next(0, selectRandomFrom.Count)];
    
            if (x != lastRandomInt)
            {
                lastRandomInt = x;
                break;
            }
            else
            {
                numberOfReTries++;
            }
        }
    
        nHits[x] ++;
    }
    
    foreach (var itemHit in nHits)
    {
        Console.WriteLine("item:\t{0}\t\tnumber of hits:\t{1}", itemHit.Key, itemHit.Value );
    }
    
    Console.WriteLine();
    Console.WriteLine("number of re-tries: {0}", numberOfReTries);
}
Here's the output of testing this example:

item: 1 number of hits: 10089
item: 24 number of hits: 9971
item: 13 number of hits: 9910
item: 12 number of hits: 9884
item: 9 number of hits: 10117
item: 3 number of hits: 9926
item: 5 number of hits: 9962
item: 8 number of hits: 10108
item: 2 number of hits: 10062
item: 499 number of hits: 9971

number of re-tries: 11236

Least number of selections: 9910; most selections: 10117.

This is an example of eliminating random selection repetitions without having to copy a source list; I have not compared the performance of this technique to a similar example using the technique of removing items from a list with each selection, and, then, refreshing the list by copying from a master-list as necessary.

Obviously, as the source list is longer: then the number of retries as a proportion of the total selection will decrease. Doubling the number of items in the source list to #20 resulted in a more than 50% decrease in retries. Reducing the number of items to #5, roughly doubled the number of retries compared to using #10 items. A few tests strongly suggest the number of retries is linearly related to the number of items in the source list.

My tests (using Stopwatch) indicate using the technique shown here averages over 100% faster than using an approach where you remove items from the source list, and re-initialize the source list as needed, for both large and small source lists. (Code on request)
 
Share this answer
 
v3
C#
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 10)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());
            hidActivationKey.Value = result;



place your provided number in chars
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900