Jump to content
Sign in to follow this  
Chimaera

Small Array Problem (Negative Numbers)

Recommended Posts

Chimaera

Hi i was practicing with an array trying to generate a random fictitious name for a company like this

#include <Array.au3>
; [ 0 1 2 3 4 ] [ 0 1 2 3 4 ] [ 0 1 2 3 4 ]
Local $avArray[3][5] = [["Cloud", "Harvard", "Downtown", "Trent", "Compton"],["Transport Ltd", "Paper Ltd", "Construction", "Builders", "Tarmac Co"],["Invoice", "Statement", "Quote", "Bill", "Demand"]]

;~ _ArrayDisplay($avArray, "$avArray as a 2D array, transposed", -1, 1)
$no = Round(Random(Default, 4),0)
ConsoleWrite($no & @CRLF)
$no1 = Round(Random(Default, 4),0)
ConsoleWrite($no1 & @CRLF)
$no2 = Round(Random(Default, 4),0)
ConsoleWrite($no2 & @CRLF)
ConsoleWrite( $avArray[0][$no] & " " & $avArray[1][$no1] & " " & $avArray[2][$no2] & @CRLF)

Which works and returns the name but occasionaly i get a result like this

2
2
-1
C:\Users\J\Desktop\_ArrayTest.au3 (14) : ==> Array variable subscript badly formatted.:
ConsoleWrite( $avArray[0][$no] & " " & $avArray[1][$no1] & " " & $avArray[2][$no2] & @CRLF)
ConsoleWrite( $avArray[0][$no] & " " & $avArray[1][$no1] & " " & $avArray[2][^ ERROR

Is there a way to prevent this negative number ?

What im trying to end up with is a randomly generated name for a file, obviously there will be larger lists of names in the final working model

Share this post


Link to post
Share on other sites
xXlowXx

the answer is simple just change the Flag of random to 1.

Random ( [Min [, Max [, Flag]]] )

Flag: If this is set to 1 then an integer result will be returned. Default is a floating point number.

for random stuff i do always like:

$no = Random(0,UBound($avArray)-1,1)

Edited by xXlowXx

Share this post


Link to post
Share on other sites
Chimaera

When i tried the first time i had set flag to 1 but i still got negative number

So this broken down is accessing the array dirctly?

$no = Random(0,UBound($avArray)-1,1)

EDIT

Upon testing ive realised this way only access the first number of the array and never exceeds 2, ill prob end up having to split the arrays to make them manegable ;(

Edited by Chimaera

Share this post


Link to post
Share on other sites
guinness

-1 is a whole integer, this will prevent numbers such as 1.9. To prevent a negative number look at Abs, but then again just re-arrange your method...

Local $aArray[3][5] = [['Cloud', 'Harvard', 'Downtown', 'Trent', 'Compton'], _
        ['Transport Ltd', 'Paper Ltd', 'Construction', 'Builders', 'Tarmac Co'], _
        ['Invoice', 'Statement', 'Quote', 'Bill', 'Demand']]

Local $iUBoundCols = UBound($aArray, 2) - 1
Local $iValue = Random(0, $iUBoundCols, 1)
ConsoleWrite($iValue & @CRLF)

Local $iValue1 = Random(0, $iUBoundCols, 1)
ConsoleWrite($iValue1 & @CRLF)

Local $iValue2 = Random(0, $iUBoundCols, 1)
ConsoleWrite($iValue2 & @CRLF)

ConsoleWrite($aArray[0][$iValue] & ' ' & $aArray[1][$iValue1] & ' ' & $aArray[2][$iValue2] & @CRLF)

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
czardas

Not necessarily a solution for this, but perhaps worth mentioning: _ArrayLoopSelect does not have a problem with negative numbers. It only works with one dimensional arrays though. Includes are

Edited by czardas

Share this post


Link to post
Share on other sites
Chimaera

Just out of curiosity is it possible to have irregular array's

For example

array section 1 has 50 names

array section 2 has 50 names

array section 3 has 20 names

Just thought id ask :)

EDIT

I assume single arrays would be the only way

Edited by Chimaera

Share this post


Link to post
Share on other sites
guinness

Yes.


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
czardas

You will have empty array elements if you do this. It's fine for small arrays, but can get silly sometimes. If there is a need to lay everything out in a grid then okay. Here it isn't necessary because you are selecting randomly from three lists. Scaling things up can sometimes be a problem - like having several million empty array elements is not particularly cool.

Share this post


Link to post
Share on other sites
kylomas

Chimaera,

This is a technique that I use to populate test DB's for demo's. See comments in code.

; create 2D array of varying row lengths.  Element 0 will contain the count of elements in the row.  Element 1 is just an eye-catcher for me while coding functions

local $aTestData[20][100] = [ _
    [0,'fname','Jon','Mark','Luke','Joe','Tom','Bob','Alan','Sue','Mary','Alice','Nancy','Lisa','Joan','Linda','Yolanda','Grace'], _
    [0,'lname','Smith','Fuzzy','Kylomas','Doe','Fritch','Wanker','Blooze','Wrzyski','Shlepp','Miller','Steinberger','Alenxander','Woo','Yang','Chaing','Zork'], _
    [0,'company','IBM','GM','Widgets, Inc.','Balloons, Balls and Bingo','EDS','Windows To Go','Home Repair','Landscaping','Remodelers Today'], _
    [0,'addr','Monroe','Washington','Wiconsin','Circular','Kansas Dry','Moon Scape','Frontage','Somewhere','Fools','WhereAmI'], _
    [0,'attn','Shipping','Receiving','Billing','Collections','Lower Level','Manager','Subscriptions','Mr. Smith','Mail Room','Pediatrics','Plant Manager','Anyone'], _
    [0,'city','West End','Chicago','Plano','Waupaca','L.A.','New york','Bristol','London','Moon Base Alpha','Omaha','San Diego','Hamburg','Sydney','Melbourne'], _
    [0,'state','Oregon','utah','Ohio','Iowa','Idaho','Wisconsin','Illinois','New Mexico','Texas','Arizona','Kentucky','Florida','Maine','Rhode Island','Alaska'], _
    [0,'country','USA','Norway','England','Scotland','Belgium','Ethiopia','Republic of Congo','Chile','Peru','Canada','Kuwait','Iran','China','Brazil','Russia'], _
    [0,'prod','Balloons','Glass','Foreign Cars','Kitchen Ware','Hammers','Milk','Carpeting','Camping Goods','Mitchel Reels,','Pipe','Gin','Lawn Mower','Eggs','Blow'], _
    [0,'description','One size fits all','Home Owners Delight','Modern Design','Cutting Edge','Must have for Fathers Day','Superior Quality','Easy To Install','Good'], _
    [0,'supp','Suppliers, Inc.','Good Homes Remodeling','GFS','World Wide Widgets','Wazzabbeeee','Pelts To Go','Pet Supplies','SuperSaver','Fluid Depot'], _
    [0,'addr2','Suite','Room','Floor','Appartment'] _
    ]

; now count the number of elements in each row and set element 0 to that number

for $1 = 0 to ubound($aTestData,1) - 1
    if stringlen($aTestData[$1][0]) = 0 then exitloop
    for $2 = 0 to ubound($aTestData,2) - 1
        if stringlen($aTestData[$1][$2]) = 0 then
            $aTestData[$1][0] = $2 - 1
            ExitLoop
        EndIf
    next
next

; This is how the array gets used to return a random element (in this case a company name)

func company($tbl)

    return  stringstripws($aTestData[2][random(2,$aTestData[2][0],1)],3)

endfunc

kylomas

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

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
Sign in to follow this  

×