how to get random item from array

daryl4356

Member
Joined
May 30, 2006
Messages
13
Programming Experience
Beginner
Hi There,

thanks for the response.

What I am actually doing with this array is randomizing it and using a random value in a hperlink.

Is this still the same, and would I use the Array List?

if so how would i call it in my code? I currently have

My Array(autoRand.Next(102))

Thanks

Daryl
 
based on the code shown in green all you're doing is randomly selecting an element in the array, which can be down with an ArrayList as well
VB.NET:
Dim TextFileArray As New ArrayList
'Fill the array

TextFileArray.Item(autoRand.Next(0, TextFileArray.Count))
what that does is gets the value in the array list based on a random index (just like what you did with a regular array) i've also included code that ensures that the number returned from autoRand isnt greater than the arraylist size, so if the array size changes because things are added or removed from the textfile, you dont have to change your program
 
Last edited:
very small point of note.. in Juggalo's code, he called his ArrayList with the name "TextFileArray" - i generally consider that if a name contains a type (e.g. Array, ArrayList) then it should be of the type of the object. For Juggalo to give his ArrayList object a name of "TextFileArray" might suggest that it is an Array, not an ArrayList. As you said in your original post, youre looking to make maintenance more easy, and this also goes for code maintenance. Giving the arraylist a name that suggests it is an ArrayList would be a good step in making your code more maintainable :)

(It might not matter for this project, but it s a sensible coding practice to adopt. Try to write witha perspective that, if another programmer were to come to your code, would he be able to understand a) what a variable is for, and b) what a variable type is, just from the name? If not, strive so that he could


types may be inferred or stated. for example, you should be able to guess what these are for:

ConnectionIsEstablished
(boolean, indicating an established connection)

_strFileContents
(string, of the contents of a file)

i
(used as a temporary integer, scope of a few lines max)

UnsupportedTranslationLanguageException
(error object thrown when a source language cannot be translated)

FailureCounter
(integer or numerical type counting failures)

EnumeratorForList(List l)
(method that should provide an enumerator for the specified list)



I doubt these exist anywhere in the framework.. just a few examples pulled out of my head and of course open to interpretation and different coding styles/standards in use.. but generally the way to go :)
 
JuggaloBrotha, or anyone else for that matter.

I am just testing my application and keep receiving an error message as follows.

ArgumentOutOfRangeException

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

I only sometimes receive this message though.

Would it be something to do with the amount of times it is called because I am using it in an application where I am generating 20,000 HTML pages and If I try generating a smaller amount I do not seem to get this.

Could it also be something to do with the amount of entries in my list? I am not testing with a large number of entries in the text file and if i increase the entries it seems to allow me to create more.

If anyone could clarify this it would be great. In a live enviroment I would envisage having 500 entries in the text file.

I am also using 3 different arrays like this to populate 3 different areas from 3 different files, could this be the reason also?

Thanks

Daryl
 
mmh, naw.. It's merely that occasionally the collection is being requested to provide an index outside it's known range

For example, if we say:

Dim s(0 to 9) as String


we have an array with 10 indexes, numbered from 0 to 9. If we now say:

s(10)

or s(237), s(984) or s(-12)


They are all illegal values for this context.. the array cannot provide item number 10, or 237 etc because it is out of the range 0 to 9



If your collection contains 100 items, then you need to generate a random number between 0 and 99. if for any reason your random routine generates a number outside this range, an ArgumentOutOfRangeException will be encountered
 
incidentally, you get it when you make 20000 and not when you make 2, simply because if you run 20000 times youre 10000 times more likely to generate a duff number (per run) and just generating 2

i.e.

for array size 100, if your routine randomly and evenly generates 101 numbers then 1 in every 101 attempts will fail. multiply this by 2 and your chances that a failure will occur in a run of 2 is 2/101. your chances of failure in a run of 20000 is 20000/101 -> i.e. a dead certain (if all numbers are generated with an even random distribution)
 
Hi Cjard,

Thanks for your past few posts.

Just to clarify with your last two.

I am currently using an array list as shown earlier in the post.

My code is as follows:-

Dim ExampleArrayList As New ArrayList
Dim sr As New StreamReader("C:\example.txt")
Do While sr.peek <> -1
ExampleArrayList.add (sr.ReadLine)
Loop
sr.close()

And when I am filling out my HTML page I am using...
Dim autorand as New Random()
TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count + 1))

Is it my code above that is incorrect?


Or is it a problem that lies with the Array List being randomized so many times?
When I first posted my problem I did not make myself clear with the amount of files etc I would be creating.

Or should I be giving my Array List a size and I have mis-interpereted JuggaloBrotha's post?

Thanks

Daryl

 
Looking back at my code Should I maybe be using

TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count - 1)) rather than
TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count + 1))

as by putting the + would i not be creating this duff number that I keep calling?
 
I'm new to this too, but I think you're right there. It seems that most things in VB are zero based, so if you have ten things in your list, you actually want 0 to 9, not 1 to 10. So, Count would give you a number one higher than you actually want. Go with Count - 1.
 
Seems to work.. so far so good.

Thanks for all your help, it's working now and also have picked up a little more experience on the way so double bonus
 
daryl4356 said:
Looking back at my code Should I maybe be using

TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count - 1)) rather than
TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count + 1))

as by putting the + would i not be creating this duff number that I keep calling?

this is called cardboard analysis :) (in asking a question, you think aout how to explain the problem, and you realise the solution)

However, as a little lateral thinking excercise, you are told this:

"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

and you know, from intellisense (code completion) in VS, that the signature for getting soemthing out of an arraylist is MyArrayList.Item(index as Integer)


So, given that the INDEX must be LESS than the SIZE of the collection, and the ArrayList.Count is the size of the collection (the count of the number of items in it) then the logical conclusion is that Count-1 is what you want :)

typically in zero-based languages, valid ranges are "0 to Length-1" for a container.. where Length is whatever method of the container tells you how much the continer holds
 
yea, my bad

here's what is happening, the random class has a known flaw and that's the fact that the random class will never pick the highest value when calling it's next() method, so to counter this you need to add a "+ 1" to the end of the highest value for it to pick

i had neglected the fact that arraylist's count object already takes care of the "+ 1" because 99.999% of everything in .Net is zero based (stupid vb6 habbit of mine, unfortunatly i learned vb6 first) so the count property was already 1 higher than the max value for the arraylist and i had you adding + 1 to the end of the count property which means the random class would occasionally pick an index that's 1 higher than the bounds of the arraylist

instead of this:
TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count +1)

it should be:
TopAffiliate.Item(autorand.Next(0, TopAffiliate.Count)

also if you want your random class to be truely random, you should seed it with: CInt(Date.Now.Ticks Mod Integer.MaxValue) so it'd be:
Dim autoRand As New Random(CInt(Date.Now.Ticks Mod Integer.MaxValue))
 
doh.. my bad too.. i should have known that, like most other modern languages (including the java on which it is based) .net generates random numbers such that a number X has the domain:

0 <= x < MAX


as juggalo points out, you should use the collection.Lenght as the max

A colelction of lenght 10 is indexed 0 to 9, and you can be sure that rand will generate 0 <= x < 10, so x will never be 10, and x will never go beyond the end of the collection
 
Back
Top