Snippets ( Math & Numbers )

From AutoIt Wiki
Jump to navigation Jump to search

Alert2.gif Please always credit an author in your script if you use their code. It is only polite.


_Boolean

Author: guinness








ConsoleWrite(_Boolean(True) & @CRLF) ; Returns True.
ConsoleWrite(_Boolean("This is a string with something True.") & @CRLF) ; Returns False if a string of text (excluding True/False or a number.)
ConsoleWrite(_Boolean("1") & @CRLF) ; Returns True as it is a string but a number.
ConsoleWrite(_Boolean("False") & @CRLF) ; Returns False.
ConsoleWrite(_Boolean("False") & @CRLF) ; Returns False.
ConsoleWrite(_Boolean(1) & @CRLF) ; Returns True.

; Convert a value to Boolean (True or False).
; If a number is passed then anything that is NOT 0 is True and if a string is the explicit word True, False or a number than it's equivilant boolean value is returned.
; Anthing else e.g. This is a string is False.
Func _Boolean($fValue)
    If IsBool($fValue) Then
        Return $fValue
    EndIf
    Return Number($fValue) >= 1
EndFunc   ;==>_Boolean

Return To Contents

BinToInt

Author: Malkey








ConsoleWrite(BinToInt(111000) & @CRLF)

Func BinToInt($bin) ;coded by Malkey
    Local $aArr = StringSplit($bin, "", 2)
    Local $dec = 0
    For $i = UBound($aArr) - 1 To 0 Step -1
        If $aArr[$i] = "1" Then
            $dec = BitXOR($dec, BitShift(1, -(UBound($aArr) - 1 - $i)))
        EndIf
    Next
    Return $dec
EndFunc   ;==>BinToInt

Return To Contents

IntToBin

Author: Malkey








ConsoleWrite(IntToBin(2048) & @CRLF)

Func IntToBin($iInt) ; coded by Malkey
    Local $b = ""
    For $i = 1 To 32
        $b = BitAND($iInt, 1) & $b
        $iInt = BitShift($iInt, 1)
    Next
    Return $b
EndFunc   ;==>IntToBin

Return To Contents

_BinToInt

Author: Spiff59








ConsoleWrite(_BinToInt(111000) & @CRLF)

Func _BinToInt($sValue)
    Local $iOut = 0, $aValue = StringSplit($sValue, "")
    For $i = 1 To $aValue[0]
        $aValue[0] -= 1
        If $aValue[$i] = "1" Then $iOut += 2 ^ ($aValue[0])
    Next
    Return Int($iOut)
EndFunc

Return To Contents

_BytesToBits

Author: ProgAndy








ConsoleWrite(_BytesToBits(1024) & @CRLF)

Func _BytesToBits($bBinary) ;coded by ProgAndy

    Local $byte, $bits="", $i, $j, $s
	#forceref $j
    For $i = 1 To BinaryLen($bBinary)
        $byte = BinaryMid($bBinary, $i, 1)
        For $j = 1 To 8
            $bits &= BitAND($byte, 1)
            $byte = BitShift($byte, 1)
        Next
    Next
    $s = StringSplit($bits, "")
    $bits = ""
    For $i = $s[0] To 1 Step -1
        $bits &= $s[$i]
    Next
    Return $bits
EndFunc

Return To Contents

_BitsToBytes

Author: ProgAndy








ConsoleWrite(_BitsToBytes(1000) & @CRLF)

Func _BitsToBytes($sBits) ; coded by ProgAndy
    Local $bBytes = Binary(''), $iLen = StringLen($sBits)
    Local $iCnt = 0, $iVal = 0
    For $i = 1 To $iLen
        $iCnt += 1
        $iVal = BitShift($iVal, -1)
        If "1" = StringMid($sBits, $i, 1) Then
            $iVal = BitOR($iVal, 1)
        EndIf
        If $iCnt = 8 Then
            $iCnt = 0
            $bBytes &= BinaryMid($iVal, 1, 1)
            $iVal = 0
        EndIf
    Next
    If $iCnt Then $bBytes &= BinaryMid(Binary(BitShift($iVal, -8+$iCnt)), 1, 1)
    Return $bBytes
EndFunc

Return To Contents

_ChkParamValue

Author: UEZ








$v = 79  ; Bitmask -> 1 + 2 + 4 + 8 + 64 = 79 =  0100 1111

ConsoleWrite(_ChkParamValue(7, $v) & @LF)
ConsoleWrite(_ChkParamValue(32, $v) & @LF)
ConsoleWrite(_ChkParamValue(77, $v) & @LF)
ConsoleWrite(_ChkParamValue(16, $v) & @LF)

;======================================================================================
; Function Name:    _ChkParamValue
; Description:          Check whether any combination of n parameter values is valid
; Parameters:           $iParam: an integer value to check
;                               $iBitmask: an integer value with the possible parameter values
; Return Value(s):  	True -> $iParam is a valid parameter
;                               False -> $iParam is NOT a valid parameter
;
; Error codes:          1: $iParam not an integer
;                               2: $iBitmask not an integer
; Author(s):            UEZ
; Version:              v0.99 Build 2012-05-10 Beta
; Example:
;                               $iBitmask = 79  ; Bitmask -> 1 + 2 + 4 + 8 + 64 = 79 =  0100 1111
;                               ConsoleWrite(_ChkParamValue(7, $iBitmask) & @LF)
;                               ConsoleWrite(_ChkParamValue(32, $iBitmask) & @LF)
;                               ConsoleWrite(_ChkParamValue(77, $iBitmask) & @LF)
;                               ConsoleWrite(_ChkParamValue(16, $iBitmask) & @LF)
;=======================================================================================
Func _ChkParamValue($iParam, $iBitmask)
    If Not IsInt($iParam) Then Return SetError(1, 0 , 0)
    If Not IsInt($iBitmask) Then Return SetError(2, 0 , 0)
    If Not $iParam Or $iParam > $iBitmask Then Return 0
    Local $c = BitXOR(BitAND($iBitmask, $iParam), $iParam)
    If Not $c Then Return True
    Return False
EndFunc ;===>_ChkParamValue

Return To Contents

_Distance

Author: SolidSnake26







Calculate the Distance between two points


; Calculate the Distance between two points
; Author - SolidSnake
ConsoleWrite(_Distance(210, 345, 273, 465) & @CRLF)

Func _Distance($iX1, $iY1, $iX2, $iY2)
    Return Sqrt(($iX1 - $iX2) ^ 2 + ($iY1 - $iY2) ^ 2)
EndFunc  ;==>_Distance

Return To Contents

_Generate

Author: monoceres







Pick a random set of numbers.


Local $aNumbers = _Generate(7, 1, 36)

Local $sString = ''

For $i = 0 To UBound($aNumbers) - 1
	$sString &= "Element " & $i & ": " & $aNumbers[$i] & @CRLF
Next

MsgBox(4096, '', $sString)

; Pick a random set of numbers.
Func _Generate($iSize = 7, $iMin = 1, $iMax = 36)
	Local $aArray[$iSize], $sReturn = ''
	$aArray[0] = Random($iMin, $iMax, 1)
	For $i = 0 To $iSize - 1
		While 1
			$sReturn = Random($iMin, $iMax, 1)
			For $j = 0 To $i - 1
				If $aArray[$j] = $sReturn Then
					ContinueLoop 2
				EndIf
			Next
			ExitLoop
		WEnd
		$aArray[$i] = $sReturn
	Next
	Return $aArray
EndFunc   ;==>_Generate

Return To Contents

Integer2Binary

Author: UEZ








#include <String.au3>

ConsoleWrite(Integer2Binary(2048) & @CRLF)

Func Integer2Binary($in) ;coded by UEZ
    If $in = 0 Then Return 0
    Local $bin
    While $in > 0
        $bin &= Mod($in, 2)
        $in = Floor($in / 2)
    WEnd
    Return(_StringReverse($bin))
EndFunc

Return To Contents

Binary2Integer

Author: UEZ








ConsoleWrite(Binary2Integer(111000) & @CRLF)

Func Binary2Integer($in) ;coded by UEZ
    Local $int, $x, $i = 1, $aTmp = StringSplit(_StringReverse($in), "")
    For $x = 1 To UBound($aTmp) - 1
        $int += $aTmp[$x] * $i
        $i *= 2
    Next
    $aTmp = 0
    Return StringFormat('%.0f', $int)
EndFunc

Return To Contents

Iterative Fibonacci

Author: Rutger83








; Iterative Fibonacci Sequence

Global $n, $n1, $n0
#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox (0,"Iterative Fibonacci ", it_febo($n0,$n1,$n))

Func it_febo($n_0,$n_1,$N)
   Local $first = $n_0
   Local $second = $n_1
   Local $next = $first + $second
   Local $febo = 0
   For $i = 1 To $N-3
      $first = $second
      $second = $next
      $next = $first + $second
   Next
   if $n==0 Then
      $febo = 0
   ElseIf $n==1 Then
      $febo = $n_0
   ElseIf $n==2 Then
      $febo = $n_1
   Else
      $febo = $next
   EndIf
   Return $febo
EndFunc

Return To Contents

_MilesToKilometres

Author: guinness







Usage _MilesToKilometres( Number Of Miles To Calculate By )


; Usage _MilesToKilometres( Number Of Miles To Calculate By )  &

ConsoleWrite(_MilesToKilometres(1) & @CRLF) ; Change the (1) to the distance required

Func _MilesToKilometres($iLength)
    Return $iLength * 1.609
EndFunc   ;==>_MilesToKilometres

Return To Contents

_KilometresToMiles

Author: guinness







_KilometresToMiles( Number Of Kilometers To Calculate By )


; _KilometresToMiles( Number Of Kilometers To Calculate By )
ConsoleWrite(_KilometresToMiles(1) & @CRLF) ; Change the (1) to the distance required

Func _KilometresToMiles($iLength)
    Return $iLength * 0.6214
EndFunc   ;==>_KilometresToMiles

Return To Contents

_Random

Author: guinness







_Random(Minimum, Maximum, [Integer]) ~ ( Generates a random number within a given range )


; Usage = _Random(Minimum, Maximum, [Integer]) ~ ( Generates a random number within a given range )

ConsoleWrite(_Random(0, 1) & @CRLF) ; Will return a float number between 0 & 1.
ConsoleWrite(_Random(42, 42) & @CRLF) ; Will return 42, as both values are the same.
ConsoleWrite(_Random(1, 99, 1) & @CRLF) ; Will return an integer number between 1 & 99.

Func _Random($iMin, $iMax, $iInteger = 0)
    Local $iRandom = Random($iMin, $iMax, $iInteger)
    If @error Then
        Return $iMin
    EndIf
    Return $iRandom
EndFunc   ;==>_Random

Return To Contents

_RandomCharGen

Author: Marlo








MsgBox(0, "", _RandomCharGen(50))

Func _RandomCharGen($iLength)
    Local $sReturn
    Local $aChars[62] = [ _
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', _
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', _
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    For $i = 0 To $iLength
        $sReturn &= $aChars[Random(0, 61)]
    Next
    Return $sReturn
EndFunc ;==>_RandomCharGen

Return To Contents

_RandomNumber

Author: guinness








ConsoleWrite(_RandomNumber() & @CRLF) ; Generates a random number

Func _RandomNumber($iStart = 0, $iEnd = 10000000000)
    Return Random($iStart, $iEnd, 1)
EndFunc   ;==>_RandomNumber

Return To Contents

Recursive Fibonacci

Author: Rutger83








; Recursive Fibonacci Sequence

Global $n, $n1, $n0
#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox (0,"Recursive Fibonacci ", rec_febo($n0,$n1,$n))
Func rec_febo($r_0,$r_1,$R)
   if  $R<3 Then
      if $R==2 Then
     Return $r_1
      ElseIf $R==1 Then
     Return $r_0
      ElseIf $R==0 Then
     Return 0
      EndIf
      Return $R
   Else
      Return rec_febo($r_0,$r_1,$R-1) + rec_febo($r_0,$r_1,$R-2)
   EndIf
EndFunc

Return To Contents

_Ternary

Author: guinness








ConsoleWrite(_Ternary(10, 'Is True.', 'Is False.') & @CRLF)
ConsoleWrite(_Ternary(0, 'Is True.', 'Is False.') & @CRLF)

; Version: 1.00. AutoIt: V3.3.8.1
Func _Ternary($iValue, $vTrue, $vFalse) ; Like _Iif but uses 0 or non-zero e.g. 1 or above instead of a boolean result.
    Local $aArray[2] = [$vFalse, $vTrue]
    Return $aArray[Number(Number($iValue) > 0)]
EndFunc   ;==>_Ternary

Return To Contents