-1

At the minute I am able to add values into a textbox and then save those values into an array, I want to calculate the Mode/Most frequent values, for this array and output into another textbox or something to display on my web-page.

e.g. I enter 2,2,2,3,3,3,1. the output to webpage will be 2 3.

string[] list = TextBox1.Text.Split(new string[] { "," },
        StringSplitOptions.RemoveEmptyEntries);
        int[] numbers = new int[list.Length];
        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = Convert.ToInt32(list[i].Trim());
        }

        int mode = numbers
  .GroupBy(x => x)
  .OrderByDescending(g => g.Count())
  .First() 
  .Key;
        TextBox2.Text = mode.ToString();
Nathan Werry
  • 876
  • 7
  • 18
Swail
  • 1
  • 2
  • Are you getting an error? or are you looking at a way to get a frequency of the arrays? – mahlatse Nov 29 '18 at 20:09
  • At the minute this code using .First() and .Key only prints out 1 value and e.g. 2,2,2,3,3,3,1 would only print out 2. However I want it to print out both values. Cant get my head around it and if their is an an easier method I would use that instead. – Swail Nov 29 '18 at 20:12
  • Why not concatenate both of those values then? – mahlatse Nov 29 '18 at 20:24
  • Possible duplicate of [Calculate Mode Using LINQ C#](https://stackoverflow.com/questions/53541578/calculate-mode-using-linq-c-sharp) – Nathan Werry Nov 29 '18 at 22:26

2 Answers2

0

I think you're really close... Once you've populated the numbers array, I think you can do this to get the desired result:

var frequencies = numbers.GroupBy(x => x).ToList();
var maxFrequency = frequencies.Max(n => n.Count());
var modes = frequencies
                .Where(n => n.Count() == maxFrequency)
                .Select(n => n.Key)
                .OrderBy(n => n);
TextBox2.Text = String.Join(",", modes);
KintoborML
  • 65
  • 5
-1

It sounds like you want the mean (2+2+2+3+3+3+1)/7 = 2.2857 == 2.3 ????

You could do that like so:

   var numbers = new[] { "2", "2 " ,"2", "3", "3", "3", "1" };
   var average = numbers.Select(x => Convert.ToInt32(x.Trim())).Average();

   MeanTextBox.Text = average.ToString("#.#");

The "#.#" formats to one decimal place.

In your case, if you're grabbing those values from a UI, you should probably use a TryParse in case someone feeds you values like "a".

int.TryParse documentation

You should also do a check up front for any elements in the list. An array with 0 elements will throw an exception when calling Average()

  • mean and mode arent the same. Mode is the number that appears most in an array. It just so happens 2 and 3 are the modes since they appear the most and the same number of times but if it was {2,2,2,2,3,3,3,1} then 2 would be the mode. – Ecordero Nov 29 '18 at 20:45
  • I saw 2 3 as 2.3. This answer can be ignored. – Scott Bennington Nov 29 '18 at 20:56