Jump to content
PCI

Generate random numbers with validation check digits

Recommended Posts

PCI

Hi everyone 

I've read all yesterday forums , i think it's me , but i could not find a clue for this :

I need to generate large numbers and output into csv format or excel format

- Range between 3000000 and 9000000 

- Need 5000000 numbers

- Numbers should not be in series ( Mixed and Random )

- I would prefere to have a check digits at the end

Anyone could help please ?

 

Thank you

 

 

Share this post


Link to post
Share on other sites
Melba23

PCI,

Random will produce the numbers for you (although 5000000 will take a little time) - and formatting the results as .csv should not prove difficult. But what do you mean by check digits?

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
PCI

@Melba23 Thank you so much for your reply !

I need to produce set of 5 millions numbers the numbers , i need to make check digits at the end to validate the numbers with an algorithm like mod10 or luhrn .

I prefer to validate 8 digits

 

Please help

 

Thank you

Share this post


Link to post
Share on other sites
Melba23

PCI,

Do you mean something like this:

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>


; Create file
$sFile = "Test.csv"

$hFile = FileOpen($sFile, $FO_OVERWRITE)

$sLine = ""


; Produce numbers (100 here as an
 example)
For $i = 1 To 100

    ; Create a random number
    $sNumber = String(3000000 + Random(0, 6000000, 1))

    ; Calculate a check digit
    $iCheckSum = 0
    For $j = 1 To 7
        $iCheckSum += StringMid($sNumber, $j, 1)
    Next
    $iCheckDigit = Mod($iChecksum, 10)

    ; Add the number and check digit to the line
    $sLine &= $sNumber & "-" & $iCheckDigit & ","

    ; Write every a line to the file every 5 numbers
    If Mod($i, 5) = 0 Then
        $sLine = StringTrimRight($sLine, 1)
        FileWrite($hFile, $sLine & @CRLF)
        $sLine = ""
    EndIf

Next


; Close the file
FileClose($hFile)


; And here is the result
$sData = FileRead($sFile)
MsgBox($MB_SYSTEMMODAL, "Random", $sData)

Just out of interest, why do you need so many random numbers?

M23

Edit:

And here is the Luhn version (now I know what it is!):

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>

$sFile = "Test.csv"

$hFile = FileOpen($sFile, $FO_OVERWRITE)

$sLine = ""

For $i = 1 To 100

    $sNumber = String(3000000 + Random(0, 6000000, 1))
    $iCheckSum = 0
    For $j = 1 To 7
        $iCheckSum += StringMid($sNumber, $j, 1)
    Next
    $iCheckSum *= 9
    $sCheckDigit = StringRight(String($iCheckSum), 1)

    $sLine &= $sNumber & $sCheckDigit & ","

    If Mod($i, 5) = 0 Then
        $sLine = StringTrimRight($sLine, 1)
        FileWrite($hFile, $sLine & @CRLF)
        $sLine = ""
    EndIf

Next

FileClose($hFile)

$sData = FileRead($sFile)
MsgBox($MB_SYSTEMMODAL, "Random", $sData)

 

Edited by Melba23
  • Like 1

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
PCI


Thank you so much @Melba23 you ROCK !
I'm really suprized how clean and easy to read
I'm trying to distibute a unique code to random friends to access a web page
However i could not generate the results with these requirements
   - Fixed length if possible 
   - Range from 1000000(1M) to 40000000(40M)
   - Mod10 check
   - Could i add carriage return to the output so they are only 1 set per ligne ?
   
   Thank you for making me learn , this i will make a gui with prompt to enter low range and hi range and select mod10 with check then click on output
      
      Great Forum / Great work / Genius Autoit 

Share this post


Link to post
Share on other sites
Melba23

PCI,

Of course the numbers are not Mod 10 - you did not ask for them to be so.  The code produces a Mod 10 checksum and adds it to the end of the random value - as this checksum will vary between 0 and 9, the final digit will also vary between those values.

M23

  • Like 1

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
PCI

Thank you 

You are very helpful .

I will try and add mod10 calculation

I think it will be very hard for a newbie like me. :-)

Any suggestions where to start please ?

Regards

 

Share this post


Link to post
Share on other sites
czardas

Melba something looks wrong with your Luhn algorithm code. Here's my version. BTW your _ArrayDisplay range feature was very useful testing my code. :)

PCI - The numbers you want to generate seem rather a lot. The method I use below generates Luhn numbers of 8 digits. Using _ArrayShuffle to create larger numbers is not a simple procedure. The reason is that arrays have a maximum limit of approx 16000000 elements. Only some clever work-around will allow you to exceed this range limit: assuming the numbers must be unique, as random as possible (within the range) and appear in any order. I have suspicions that you don't actually need all these numbers, but hopefully the code below will help. If there's something you don't understand then ask.

#include <Array.au3>

; Maximum valid 8 digits Luhn Number = 99999997

; Generate numbers from 1000000 to 9999999
Local $iMin = 1000000
Local $iMax = 9999999
Local $iBound = $iMax - $iMin +1

Local $aArray[$iBound]
For $i = 0 To $iBound -1
    $aArray[$i] = $iMin + $i
Next

_ArrayShuffle($aArray) ; Shuffle the numbers

Local $iIterations = 1000 ; Suppose we only need 1000 random 8 digit Luhn numbers (for quick demonstration purposes)

ReDim $aArray[$iIterations] ; Delete most of the array

; Aquire the last digit: needed to convert each 7 digit number to a valid 8 digit Luhn number
For $i = 0 To $iIterations -1
    $aArray[$i] &= GenerateLastLuhnDigit($aArray[$i])
Next

_ArrayDisplay($aArray)

Func GenerateLastLuhnDigit($vNumber)
    Local $iSum = 0, $sCurrDigit
    For $i = StringLen($vNumber) To 1 Step -2 ; Every second number from the right will be doubled.
        $sCurrDigit = StringMid($vNumber, $i, 1) ; Read each digit to be doubled starting from the right.
        $sCurrDigit *= 2 ; Multiply by 2.
        If $sCurrDigit > 9 Then $sCurrDigit = StringLeft($sCurrDigit, 1) + StringRight($sCurrDigit, 1) ; Make sure $sCurrDigit is not greater than 9.
        $iSum += $sCurrDigit + StringMid($vNumber, $i -1, 1) ; Also add the odd step value (not multiplied by 2)
    Next
    $iSum *= 9 ; Multiply the result by 9.
    Return Mod($iSum, 10) ; This digit can be appended to $vNumber to create a valid Luhn number.
EndFunc

 

Edited by czardas
spelling

Share this post


Link to post
Share on other sites
PCI

Hi czardas 

You guys are Genius !!!

I'm testing as we speak , i'm trying to make a GUI to Input low range and High Range in this GUI also any possibility to have it output to a text file ?

Thank you so much

Share this post


Link to post
Share on other sites
czardas

No problem, I guess you might just want to use the function GenerateLastLuhnDigit() to generate the final digit. It should work on any number size, but very large numbers must be passed as strings. The rest of my code is really intended to give you some ideas to play around with. Good luck. :)

Edited by czardas

Share this post


Link to post
Share on other sites
PCI

Cool worked just fine :)

Very happy guys Thank you

However , i have limitations to the output due to the maximum row 65524 , any thing i could do to output this as text file ?

Thank you for the help 

God bless you

 

 

Share this post


Link to post
Share on other sites
czardas

_FileWriteFromArray() will do the job you need.

By the way I never thought about whether you wanted numbers to include leading zeros. The lowest first digit is 1 in the numbers I am generating in the code above.

Edited by czardas

Share this post


Link to post
Share on other sites
czardas

You can also change the iterations to a maximum of 9000000 (any higher and the code will give you an error), but I don't know how long it will take to generate all the numbers. Probably not too long - you can try it if you want. However you will not be able to display all of the array - only parts of it. Write to file as you yourself suggested.

Edited by czardas

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • JustinZandee
      By JustinZandee
      I need a random string generator which creates 15 letters/numbers.
      How can I make that?
    • nacerbaaziz
      By nacerbaaziz
      Hi dears
      How are you?
      I have a question, to you please.
      How do I create an edit box for numbers only and does not accept letters? using autoit
      greetings to all
      I hope you help ME
      Thanks to all in advance
    • Anas
      By Anas
      Hi,
      I've this script (removed unrelated parts) that generate a set of random chars for a password. It gets launched from a network share by Task Scheduler at a specific time for all PC's, then it relaunches itself from the local drive.
       
      Global $LocalToolsDir = @ProgramFilesDir & '\Tools' Start() Func Start() If Not StringInStr(@ScriptFullPath, $LocalToolsDir, 2) Then Exit RunLocaly() Sleep(Random(1, 1800, 1) * 1000) $NewPass = GeneratePass() EndFunc Func GeneratePass() Local $Pass For $i = 1 to 8 $R = Random(0,1.5) If $R > 1 Then $Chr = Random(0,9,1) ElseIf $R < 0.5 Then $Chr = Chr(Random(Asc("A"), Asc("Z"), 1)) Else $Chr = Chr(Random(Asc("a"), Asc("z"), 1)) Endif $Pass &= $Chr Next Return $Pass EndFunc Func RunLocaly() Local $Run = 1, $LocalApp = $LocalToolsDir & '\' & @ScriptName If Not FileExists($LocalApp) Then $Run = FileCopy(@ScriptFullPath, $LocalToolsDir, 1 + 8) If $Run Then Run($LocalApp, $LocalToolsDir) EndFunc  
      The problem is that many PC's ends up with the same password(s).
      e.g. 10 PC's have (abc123) as a Password, and another 10 have this (def456)
      Any idea why?
    • Dequality
      By Dequality
      Got a simple question is it possible to have lets say 10 functions and use the random function to randomly pick one of them? If so could anyone please make a tiny example?
       
      Tyvm in advance 
      -Dequality
    • CarlD
      By CarlD
      I'm a command-line kind of guy, and I write scripts primarily for myself.  Since many websites nowadays require strong passwords, I thought I'd write a simple password generator in AutoIt. I know that AutoIt mavens have written more elaborate pw generators; I offer mine for what it's worth. The compiled script, GenPass.exe, can be downloaded here. See below for Help text and source. Enjoy!
      Updates:
      2017-05-06: Default password changed to variable length of 13-22 characters; argument "1" no longer supported
                            When compiled as GenPW.exe, password is sent directly to the clipboard, no message box unless password generation fails.
      2017-05-05: Correction to bypass password generation if argument is ?|H|h
      2017-05-03: Added special argument 1 to generate a password of variable length (10-18 characters) including two (2) separator characters
      2017-05-02: Added option /S to set a (persistent) randomization seed
      Help:
      GenPass.exe|GenPW.exe -- CLD rev. 2017-05-06
      Generate a strong password and save it to the Windows clipboard
      Note: GenPW.exe has the same functionality as GenPass.exe, but
            sends the generated password directly to the clipboard.
            No message box is displayed (unless password generation fails).
        
      "Strong" means that the password contains random combinations of
      alphnumeric characters, including at least one uppercase letter
      (A-N,P-Z), one lowercase letter (a-k,m-z), and one number (0-9).
      (Generated passwords do not use uppercase O or lowercase l as
      these characters are easily confused with the numbers 0 and 1.)
      The length of the password is up to you (see Usage, below),
      but needless to say, the longer, the stronger.
      By default, GenPass generates a strong password of between 13
      and 22 characters that includes two of the following separator
      characters: $%&()*+,-./:;@[]_. Alternatively, you can supply a
      command-line argument in which any number n from 1 to 9 stands
      for a random sequence of alphanumeric characters of length
      n, and any other character stands for itself. Thus, you can
      include fixed words and other characters, such as separators,
      in the generated password. Spaces in the argument are converted
      to underscores. Here are some examples:
      Usage             Sample output
      -----             -------------
      GenPass           MqU26A*6dS-53r8
      GenPass 9         frdhPYDs9
      GenPass 58        weoXYHKxDI1uQ
      GenPass 5.5       UfA6j.43VBB
      GenPass 3-4-3     0I0-6gq4-njc
      GenPass 5,3.7     I2FSR,tRZ.fjeIsFy
      GenPass 3)5(3     UMf)m8513(CBq
      GenPass 3[haha]3  yLa[haha]P3y
      GenPass Yes way5  Yes_way1BsUh
      Seed Option (/S)
      ----------------
      Adding switch /S to the command-line argument causes GenPass to
      set a seed for the random generation of password characters. A
      bare /S sets a randomized seed which is written to disk in a file
      named GenPass.rnd; this seed is used for all subsequent launches
      of GenPass with the bare /S option. Alternatively, you can specify
      a seed (range -2^31 to 2^31-1) on the command line with /S [seed].
      Here are some examples:
      GenPass /S
      GenPass /S 33.3333
      GenPass 5,5,5 /S
      GenPass 5,5,5 /S 33.3333
      Note that any subsequent launch of GenPass without the /S option
      will cause GenPass.rnd to be deleted.
      Source:
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Outfile=GenPass.exe #AutoIt3Wrapper_UseUpx=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #cs GENPASS.AU3 -- AutoIt v3 CLD rev.2017-05-05 ------------------ Generate a strong password and save it to the clipboard >> Command GenPass ? for detailed help << ------------------------------------------------------- #ce #include <Clipboard.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include <StringConstants.au3> AutoItSetOption("WinTitleMatchMode", -4) FileInstall ("d:\path\GenPass.htm", @ScriptDir & "\GenPass.htm", $FC_OVERWRITE) ; Template/Seed Local $sTemp = "" Local $bSeed = False, $fSeed=False If $CmdLine[0] Then $sTemp = $CmdLineRaw If $CmdLine[$CmdLine[0]] = "/s" Then $bSeed = True $sTemp = StringTrimRight($sTemp, 2) $sTemp = StringStripWS($sTemp, $STR_STRIPTRAILING) EndIf If $CmdLine[$CmdLine[0] - 1] = "/s" Then $bSeed = True $fSeed = $CmdLine[$CmdLine[0]] $sTemp = StringTrimRight($sTemp, 3 + StringLen($fSeed)) $sTemp = StringStripWS($sTemp, $STR_STRIPTRAILING) EndIf EndIf If Not $sTemp Then $sTemp = "8" If $sTemp = "1" Then $aSeps = StringSplit("#$%&()*+,-./:;@[]_", "") $sTemp = String(Random(3,6,1)) & $aSeps[Random(1,$aSeps[0],1)] & _ String(Random(2,4,1)) & $aSeps[Random(1,$aSeps[0],1)] & _ String(Random(3,6,1)) EndIf $sFn = @ScriptDir&"\GenPass.rnd" If $bSeed Then If Not $fSeed Then If Not FileExists($sFn) Then $fSeed = Random(-1.999^31,1.999^31,0) $h=FileOpen($sFn,2) If $h > -1 Then FileWrite($h,$fSeed) FileClose($h) Else Exit MsgBox($MB_ICONWARNING, @ScriptName, "Error opening " & $sFn) EndIf Else $h=FileOpen($sFn) If $h > -1 Then $fSeed=FileRead($h) FileClose($h) Else Exit MsgBox($MB_ICONWARNING, @ScriptName, "Error opening " & $sFn) EndIf EndIf EndIf SRandom($fSeed) Else If FileExists($sFn) Then FileDelete($sFn) EndIf ; Show help If StringInStr("?Hh", $sTemp) Then If WinExists("[REGEXPTITLE:GenPass.exe:.*]") Then WinActivate("[REGEXPTITLE:GenPass.exe:.*]") Else ShellExecute(@ScriptDir & "\GenPass.htm") EndIf Exit EndIf ; Main $sTemp = StringReplace($sTemp, " ", "_") $iC = 1 While $iC < 10001 $sPW = GenPW($sTemp) If $sPW Then ClipPut($sPW) If Not StringInStr (@ScriptName, "GenPW") Then _ MsgBox($MB_ICONINFORMATION, @ScriptName, $sPW & _ " saved to clipboard" & @CRLF & @CRLF & _ @ScriptName & " ? shows detailed help") Exit Else $iC += 1 EndIf WEnd Exit MsgBox($MB_ICONWARNING, @ScriptName, "Password generation failed!") ;------------------------------- Func GenPw($sTemplate) Local $aIn = StringSplit($sTemplate,"") Local $sOut = "" Local $sABC = _ "0123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789" Local $aAB = StringSplit($sABC, "") Local $bUC = 0, $bLC = 0, $bNR = 0 For $i = 1 To $aIn[0] If Int($aIn[$i]) Then $iK = $aIn[$i] For $j = 1 To $iK $iR = Random(1, $aAB[0],1) Select Case StringInStr("0123456789", $aAB[$iR]) $bNR = 1 Case StringInStr("ABCDEFGHIJKLMNPQRSTUVWXYZ", _ $aAB[$iR], $STR_CASESENSE) $bUC = 1 Case StringInStr("abcdefghijklmnpqrstuvwxyz", _ $aAB[$iR], $STR_CASESENSE) $bLC = 1 EndSelect $sOut &= $aAB[$iR] Next Else $sOut &= $aIn[$i] EndIf Next If ($bUC And $bLC And $bNR) Then Return $sOut Else Return 0 EndIf EndFunc  
×