0
Random r = new Random();
int randomvalue = r.Next(1,20);
*
*
if(randomvalue == 1) something
if(randomvalue == 2) something
*
*
if(randomvalue == 19) something

What is the best way to make that randomvalue without repeat? Btw: Its WPF, not console.

  • 5
    Create your range of 20 and shuffle. Then you can use the randomized values in order. http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp – Anthony Pegram Apr 14 '16 at 16:41
  • Do you mean _consecutive_ repeats or never use the same number twice _ever_? – D Stanley Apr 14 '16 at 17:02
  • Possible duplicate of [Calling random function without duplicates](http://stackoverflow.com/questions/21194306/calling-random-function-without-duplicates) – TaW Apr 14 '16 at 17:36

6 Answers6

1

Try something like below :

Random randomInstance = new Random();

        List<int> NumList = new List<int>();
        NumList.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7,
            8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
            22, 23, 24, 25, 26, 27, 28, 29, 30 });

        int index = randomInstance.Next(0, NumList.Count - 1);
        int randomNumber = NumList[index];
        NumList.RemoveAt(index);
Maddy
  • 774
  • 5
  • 14
  • 1
    Quick way to populate the list (requires System.Linq)... NumList.AddRange(Enumerable.Range(startValue, endValue); – Marc Apr 14 '16 at 17:08
  • If the desired outcome is to only use each number once (ex. asking a bunch of quiz questions in a random order) then I think this is the best solution as it only requires n loops. Using the other methods of keeping track of random numbers already used will result in many loops that do nothing just trying to find an unused random number. Although unlikely, it would be possible for the loop to never end. – Marc Apr 14 '16 at 17:15
  • Exactly Mark. This is one approach wherein your list can have a list of continous numbers or any element – Maddy Apr 14 '16 at 19:07
  • @Maddy - If you make the call `.Next(0, NumList.Count - 1)` then you will never get the last item in the list. The second parameter in the call to `.Next(...)` is an **exclusive** upper bound. – Enigmativity Jun 16 '16 at 11:31
0

// This will work

class Program { static void Main(string[] args) {

        List<int> i = new List<int>(new int[] { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20});
        List<int> r;

        r = ShuffleList(i);


    }


    private static List<E> ShuffleList<E>(List<E> unshuffledList)
    {
        List<E> sList = new List<E>();

        Random r = new Random();
        int randomIndex = 0;
        while (unshuffledList.Count > 0)
        {
            randomIndex = r.Next(0, unshuffledList.Count); 
            sList.Add(unshuffledList[randomIndex]);
            unshuffledList.RemoveAt(randomIndex); //remove so wont be added a second time
        }

        return sList; //return the new shuffled list
    }
}
GreatJobBob
  • 271
  • 1
  • 8
0

Try this:

var rnd = new Random();

var shuffled =
    Enumerable
        .Range(1, 20)
        .OrderBy(x => rnd.Next())
        .ToArray();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
-1

It is not clear what you mean by repeat. If you don't want to see the same number in a row then just keep a hash table or Dictionary<int,int> which keeps the last integer that came out. Then check if the next number is same with last number. If not, remove last number from dictionary and put the current one. If they are same then request another random integer from Random.

var myDictionary = new Dictionary<int,int>;
var randomvalue = r.Next(1,20);
while(myDictionary.ContainsKey(randomvalue))
{
   randomvalue = r.Next(1,20);
}
myDictionary.Clear();
myDictionary.Add(randomvalue, 123); //123 is just a number. Doesn't matter.

This guarantees that two same integer will never come consecutively.

NOTE:: Other answers are creative, but "know your data structure". Don't use a list for look up. Hash is what we use for it.

ozgur
  • 2,549
  • 4
  • 25
  • 40
-1

You need to store random value is the only way to make it unique.

Try this:

Random r = new Random(); 
public List<int> randomList = new List<int>();
int randomvalue = 0;
Public void newNumber()
{
    randomvalue = r.Next(0, 20);

    if (!randomList.Contains(randomvalue))
    {
        randomList.Add(randomvalue);
        if(randomvalue == 1) 
          //do something
        if(randomvalue == N)
          // do something
    }
}
-1
using System;
using System.Collections;
using System.Collections.Generic;

namespace SOFAcrobatics
{
    public static class Launcher
    {
        public static void Main ()
        {
            // 1 to 20 without duplicates
            List<Int32> ns = new List<Int32>();
            Random r = new Random();
            Int32 ph = 0;
            while (ns.Count < 20)
            {
                while (ns.Contains (ph = r.Next(1, 21))) {}
                ns.Add(ph);
            }
            // ns is now populated with random unique numbers (1 to 20)
        }
    }
}
marsouf
  • 1,107
  • 8
  • 15