Shuffling numbers from a list?

Asked

Viewed 2,971 times

1

Well, initially, I don’t know much about a C-list, but I have a list like int that will always have 4 elements that are: 1, 2, 3 e 4, I’m assigning them with the .Add, If anyone knows any other way, give me a hand..

I wanted to shuffle the items on this list always, that is, have a function to shuffle the items on the list and return me the shuffled list so I can use it.

Example:

A list: 1, 2, 3, 4

Return: 2, 1, 4 ,3 (randomly)

And after that, I have to use the elements of that list, how do I do that? In the example list the scrambled was 2, 1, 4, 3 how do I use each value of that in the code as an integer variable? Example: I want to assign a variable soma the value of the 1st and 3rd element of the shuffled list, as indicated by the 1st and 3rd element for the soma?

  • 1

    It was a duplicate because the previous one was not duplicate in my opinion, until the simplest answer was not the same, so for me it is not duplicate, were different situations.

  • It’s a duplicate of the one you asked that is a duplicate of the other because it gives the same answer. When the answers to an already asked question do not satisfy you, you put a reward. But it didn’t satisfy you there because it produces exactly the result you expect? The simplest also solves in a way that you who are starting has no idea what this lot of stuff is, ñ is ready for use in any code. If you wanted something simpler you would have said you read there and wanted something "simpler" (although simpler is a subjective concept),then people would know what you are looking for.

  • There is nothing, for many i term shuffle can be defined in other words as exchange, change etc and not by searching the site you find, just think you should comment with the link of the other question that seems to be the same before marking as duplicate, because maybe that question didn’t solve the doubt that person has.

  • 3

    Perhaps it is not enough. the fact is that it supposes. And the fact that it does not have the term does not mean that the question is not duplicated. Duplication does not mean having the same terms, it just means wanting the same result.

3 answers

3


Here’s a simple solution:

var list = new List<int> {1, 2, 3, 4};
var rnd = new Random();

var query =
    from i in list
    let r = rnd.Next()
    orderby r
    select i;

var shuffled = query.ToList();
  • It was the simplest and it worked perfectly, only now I implant in a function. Thanks there, and the others, I did not know that it was equal to the vector of C

  • 1

    @Leonardovilarinho But it is not the same. It has some similar behaviors (use as index, for example), but the similarities end there.

  • @Leonardovilarinho The best and' read to documentation of List<T>. At the bottom of the page there are useful examples.

  • Yeah, it’s not like kk is more or less like Python right.. You can’t compare it to C because vector stores an item at a given position, so string list would be completely different.. @dcastro thanks for the link, I’ll take a look

1

This answer teaches how to make some algorithms, such as Fisher-Yates, but it is important to note that this algorithm is not 100% random, according to the answer itself. The answer gives other more reliable solutions, but for simplicity purposes, I will keep only the first:

private static Random rnd = new Random();  

public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rnd.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}

Use:

List<int> numeros = new List<int> { 1, 2, 3, 4 };
numeros.Shuffle();

To add the first to the third element, you can do as follows:

var soma = numeros[0] + numeros[2]; // 0 é a primeira posição, 2 é a terceira.

1

This reply already exists on the site since 21/05/2014. Actually this question is the duplicate. As it was opened and answered, I will answer too.

Note that I didn’t change the solution (here I took the part that improved the method to be able to choose which data range you want, but doesn’t change the execution itself), which is the important thing. I just took the example of the strings. If the problem is not knowing how to add elements of array, then the question should be this.

using static System.Console;
using System.Collections.Generic;

public static class Sorteio {
    public static void Main() {
        int[] array = { 1, 2, 3, 4 };
        array.Shuffle();
        foreach (var valor in array) WriteLine(valor);
        WriteLine("Soma: {0}", array[0] + array[2]); // soma 1o. e 3o. elemento
        //vamos de novo
        array.Shuffle(); //com poucos númros tem chance de repetir
        WriteLine($"Soma novo sorteio: {array[0] + array[2]}"); // soma 1o. e 3o. elemento
    }
}

namespace System.Collections.Generic {
    public static class IListExt {
        static Random r = new Random(DateTime.Now.Millisecond);

        public static void Shuffle<T>(this IList<T> list, int lowerItem, int upperItem) {
            upperItem = upperItem > list.Count ? list.Count : upperItem;
            lowerItem = lowerItem < 0 ? 0 : lowerItem;
            for (int i = lowerItem; i < upperItem; i++) {
                int j = r.Next(i, upperItem);
                T tmp = list[j];
                list[j] = list[i];
                list[i] = tmp;
            }
        }

        public static void Shuffle<T>(this IList<T> list, int upperItem) => list.Shuffle(0, upperItem);

        public static void Shuffle<T>(this IList<T> list) => list.Shuffle(0, list.Count);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

To assign to a variable just do this:

var soma = array[0] + array[2]; //listas começam em zero então o elemento sempre é -1 ao desejado

For more details, see the answers already existing there in the original question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.