質問

Basically, in a textbox (txtEl) I'm writing the length of the vector, then add it random numbers (from 1 to 500), showing all of them in a listbox. But I don't know how to get the mode from all those numbers.

        Random Aleatorio = new Random();
        int x = Convert.ToInt16(txtEl.Text);

        int[] elementos = new int [x];

        int moda = 0;

        for (int i = 0; i < elementos.Length; i++)
        {
            elementos[i] = Aleatorio.Next(1, 500);
            listEl.Items.Add(elementos[i].ToString());



        }
役に立ちましたか?

解決

You can do something like this Im not real sure what listEl is but you should be able to use it here. If not just add them to a basic list also.

var mode = (from item in listEl.Items
                         group item by item into g
                         orderby g.Count() descending
                         select g.Key).First();

他のヒント

You can use this code, after your for loop:

var lookup = elementos.ToLookup(n => n);
int maxCount = lookup.Max(g => g.Count());
var modes = lookup.Where(g => g.Count() == maxCount).Select(g => g.Key);

Note that there can be multiple modes in your data, so it doesn't really make sense to expect just one int, but an enumerable or list of ints.

If you want just one mode, you can do .First() on the enumerable. If you need to ensure that one mode is selected randomly from the list of modes, do not use .First(), but use another random number to select one randomly.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top