Skip to content

Instantly share code, notes, and snippets.

@gravejester
Last active February 10, 2016 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gravejester/752764ed9886f0df7077 to your computer and use it in GitHub Desktop.
Save gravejester/752764ed9886f0df7077 to your computer and use it in GitHub Desktop.
function Measure-Frequency {
<#
.SYNOPSIS
Get the frequency distribution of a set.
.DESCRIPTION
This function will get the frequency distribution of a set (array) of data.
It supports array types, as well as strings.
.EXAMPLE
Measure-Frequency $array
.EXAMPLE
Measure-Frequency $string -CaseSensitive
.NOTES
Author: Øyvind Kallstad
Date: 10.02.2016
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
$InputObject,
[Parameter()]
[switch] $CaseSensitive
)
try {
if ($InputObject.GetType().Name -eq 'String') {
if ($CaseSensitive) {
$inputArray = $InputObject.ToCharArray()
}
else {
$inputArray = $InputObject.ToLower().ToCharArray()
}
}
else {
$inputArray = $InputObject
}
$inputArray | Group-Object | Sort-Object -Descending -Property Count | ForEach-Object {
$frequency = $_.Count / $inputArray.Length
$percent = '{0:P0}' -f $frequency
Write-Output ([PSCustomObject] [Ordered] @{
Value = $_.Name
Count = $_.Count
Percent = $percent
Frequency = $frequency
})
}
}
catch {
Write-Warning $_.Exception.Message
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment