' *
' * The project site is at: http://sourceforge.jp/projects/fishbornas/
' *
' * First author tiritomato 2012.
' *
' * Distributed under the FishbornArchiveShelf License (See
' *  file "Licenses/License.txt" contained in a project, or the following link.
' *  http://sourceforge.jp/projects/fishbornas/scm/svn/blobs/head/trunk/Licenses/License.txt)
' *
' * 2012.06.07 Initial Revision (tiritomato)
' *

Partial Public Class Logic

    Partial Public Class Math

        Public Shared Function RoundUneven(ByVal v As Double) As Double
            If -Double.Epsilon < v And v < Double.Epsilon Then Return v
            Return Fix(v * 0.5) * 2.0 + IIf(0 < v, 1.0, -1.0)
        End Function

        Public Shared Function Average(Of TValue As IConvertible)(ByVal collections As System.Collections.Generic.IEnumerable(Of TValue), Optional ByVal cul As Globalization.CultureInfo = Nothing) As Double
            If collections Is Nothing Then Return Nothing
            If cul Is Nothing Then cul = Globalization.CultureInfo.CurrentCulture
            Dim ct As Integer = 0, SumValue As Double = 0
            For Each v As TValue In collections
                SumValue += v.ToDouble(cul)
                ct += 1
            Next
            If 0 < ct Then SumValue /= CDbl(ct)
            Return SumValue
        End Function

        Public Shared Function Max(Of TValue As IComparable)(ByVal collections As System.Collections.Generic.IEnumerable(Of TValue)) As TValue
            If collections Is Nothing Then Return Nothing
            Dim idx As Integer = 0
            For Each v As TValue In collections
                If idx = 0 OrElse 0 < v.CompareTo(Max) Then Max = v
                idx += 1
            Next
        End Function

        Public Shared Function Min(Of TValue As IComparable)(ByVal collections As System.Collections.Generic.IEnumerable(Of TValue)) As TValue
            If collections Is Nothing Then Return Nothing
            Dim idx As Integer = 0
            For Each v As TValue In collections
                If idx = 0 OrElse v.CompareTo(Min) < 0 Then Min = v
                idx += 1
            Next
        End Function

    End Class ' Math
End Class ' CustomLogic
