Home > Blockchain >  VB.NET - How to find all modes (most frequent occurring numbers) in an array
VB.NET - How to find all modes (most frequent occurring numbers) in an array

Time:04-11

So a Mode is the most frequent number in a dataset.

I've already managed to solve it, but it can only get 1 mode. Here's my code:

Dim mode = inputX.GroupBy(Function(n) n).Select(Function(g) New With {.Number = g.Key, .Quantity = g.Count}).OrderByDescending(Function(o) o.Quantity).FirstOrDefault
If mode.Quantity > 1 Then
  result = mode.Number.ToString()   "    Quantity: "   mode.Quantity.ToString()
Else
  result = "None."
End If

Now even though I inputted 29 29 35 30 30, which has 2 modes, it only shows 29, which is the first mode that it got. I want to get two modes or more.

I've been racking my brains and kept searching for answers, but I couldn't make it work.

I just started learning this language 2 days ago.

CodePudding user response:

Quoting myself from a comment in LINQ: Mean, Median, and Mode:

Dim inputX = {29, 29, 35, 30, 30}

Dim modes = From a In
                (From n In inputX
                 Group n By n Into g = Count()
                 Select g, n)
            Where a.g =
            (From n In inputX
             Group n By n Into g = Count() Select g).Max
            Select a.n

Console.WriteLine(String.Join(", ", modes))

Outputs:

29, 30
  • Related