Skip to content

Commit

Permalink
Added Mode() extension method for int[] and double[] (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
lpeyr committed Apr 2, 2023
1 parent ad5731e commit 52f8e55
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
20 changes: 20 additions & 0 deletions PeyrSharp.Extensions/DoubleExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,5 +259,25 @@ public static double Median(this double[] values)
return median;
}

/// <summary>
/// Calculates the mode of a dataset.
/// </summary>
/// <param name="values">The dataset to calculate the mode of.</param>
/// <returns>The mode of the dataset.</returns>
/// <exception cref="ArgumentException">Thrown if the dataset is empty.</exception>
public static double Mode(this double[] values)
{
// Check for empty input
if (values.Length == 0)
{
throw new ArgumentException("Cannot calculate mode of empty dataset", "values");
}

// Group values by frequency
var frequencyGroups = values.GroupBy(x => x).OrderByDescending(g => g.Count());

// Return most common value (if more than one, return first)
return frequencyGroups.First().Key;
}
}
}
20 changes: 20 additions & 0 deletions PeyrSharp.Extensions/IntExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,25 @@ public static double Median(this int[] values)
return median;
}

/// <summary>
/// Calculates the mode of a dataset.
/// </summary>
/// <param name="values">The dataset to calculate the mode of.</param>
/// <returns>The mode of the dataset.</returns>
/// <exception cref="ArgumentException">Thrown if the dataset is empty.</exception>
public static double Mode(this int[] values)
{
// Check for empty input
if (values.Length == 0)
{
throw new ArgumentException("Cannot calculate mode of empty dataset", "values");
}

// Group values by frequency
var frequencyGroups = values.GroupBy(x => x).OrderByDescending(g => g.Count());

// Return most common value (if more than one, return first)
return frequencyGroups.First().Key;
}
}
}

0 comments on commit 52f8e55

Please sign in to comment.