How to generate a vector using Random to assign values, but to make it never have repeated values? [duplicate]

1

I'm working on a Bingo in C # for a facul job and I need to do a vector of so many values and do not ever repeat those values, I'm using the following procedure to generate the raffle values ↓

public static void GeraBingo(int[] v)
    {
        Random r = new Random();
        for (int i = 0; i < v.Count(); i++)
        {
            v[i] = r.Next(1, 10); // gera 1 a 10 e vai gerar quantos o v.Count() mandar
            Thread.Sleep(1000);  // pausa 1000 miliseg.
        }
    }

This code generates the vector, but I am not able to assimilate a method for not entering repeated.

With this code above I can get a vector like this: and as it is visible it repeats some values. | 9 | 2 | 5 | 6 | 5 | 4 | 2 | 4 | 6 | 5 | This method is for working with only an array of int values and not letting it repeat values.

    
asked by anonymous 10.05.2016 / 18:35

2 answers

1

You can use an auxiliary array with all available values.:

public static int[] CriarLista(int min, int max) 
{
    var lista = new int[max - min + 1];
    for (var valor = min; valor <= max; valor++)
        lista[valor - min] = valor;
}

public static void GeraBingo(int[] v)
{
    Random r = new Random();
    var valores = CriarLista(1, 10);
    for (int i = 0; i < v.Count(); i++)
    {
        var indice = r.Next(1, 10) - 1;
        var valor = valores[indice];
        valores[indice] = valores[0];
        valores[0] = valor;

        v[i] = r.Next(1, 10); // gera 1 a 10 e vai gerar quantos o v.Count() mandar
        Thread.Sleep(1000);  // pausa 1000 miliseg.
    }
}
    
10.05.2016 / 18:54
1

It seems to me that what you want is to put the numbers one through ten into a vector of ten positions, at random. If so, what you need is an auxiliary structure from which the numbers will be randomly drawn similar to that bingo machine from which we get the numbers.

private int[10] _vetorResultado;
private List<int> _todosOsNumeros;

public int[] GeraBingo()
{
    Random r = new Random();
    for (int i = _vetorResultado.Length; i >= 0; i--)
    {
        _todosOsNumeros.add(i);
    }

    for (i = 0; i < _vetorResultado.length; i++)
    {
        int bolaDaVez = _todosOsNumeros[r.Next(0, _todosOsNumeros.Count - 1)];

        _vetorResultado[i] = _todosOsNumeros.Remove(boladaVez); // Isso reduz o tamanho da fila de números pendentes
    }
    return _vetorResultado;
}

Note that you can change the size of the structure that the algorithm continues to function in the same way.

Also note that the Remove method of the generic list does not it just removes the item as well as returns the removed value.

    
10.05.2016 / 19:02