Solved

iDLE_MIND Random array of numbers yields negative one

Posted on 2004-09-20
10
172 Views
Last Modified: 2010-05-02
Private Sub mnuShuffleIdleMind_Click()

'Create a new project and add a button.
'Paste the code below into the form, as it is.
'The "selected" variable has been declared as a Variant.
'This means that it can basically hold anything
'(similar to object). After the call to generateSet(),
'the "selected" variable will be holding an array of
'integers. The For...Next loop just below that call
'shows how to get to every item in the array.
'The generateSet() function returns the created array
'via the Variant return type.
'NOW YOU PROGRAM DOES WORK AND I SEEM TO UNDERSTAND IT
'MY COMMENTS FOR VISIBILITY ARE CAPITALIZED
'>>>NOTE FOR LISTSIZE = 40 AND 400 AND PCKVAL = 15 AND 150 A NEGATIVE 1 APPEARS
     Dim selected As Variant
     Dim i As Integer
     Dim LISTSIZE As Integer
     Dim PCKVAL As Integer
     
 
        ' compute the size of the range
               
       LISTSIZE = 400   'CHANGED PARAMETERS TO BE ABLE TO
                       'EASILY SEE THE RESULTS ON THE TEMPLATE.
       PCKVAL = 150
           
   
        ' pick 'PCKVAL' values from 1 to LIST SIZE
    selected = generateSet(1, LISTSIZE, PCKVAL) 'UNDERSTAND. INTERESTING COMMAND. NOT FOUND IN
                                      'MSDN NOR MY LIBRARY
    For i = LBound(selected) To UBound(selected) 'OK, LOWER BOUNDRY AND UPPER BOUNDRY
                                                 'CAN VARY
        'Debug.Print i & " = " & selected(i) 'DEBUG DOES NOT WORK BUT PRINT ETC DOES
        Print i & " = " & selected(i) 'ARRAY OF NON REPETIVE RANDOM NUMBERS BASED ON
                                      'THE FUNCTION CALLED
    Next i
End Sub
           
           




Private Function generateSet(ByVal rangeMin As Integer, ByVal rangeMax As Integer, ByVal setSize As Integer) As Variant
        'GENERATESET(RANGEMIN, RANGEMAX, SETSIZE)
    Dim rangesize As Integer
    Dim rangeSet() As Integer
   
    Dim i As Integer
    Dim r As Byte
    Dim swapWith As Integer
    Dim tempInt As Integer

        ' compute the size of the range
    rangesize = rangeMax - rangeMin + 1  '40 - 1 + 1 = 40
       
    ' make sure the input parameters make sense...
    ' CONSTANTS WILL NOT CHANGE
    If rangeMax < rangeMin Then
        MsgBox "rangeMax must be greater than or equal to rangeMin"
                     ' Exit Function
    End If
    If setSize <= 0 Or setSize > rangesize Then
        MsgBox "setsize must be greater than zero and less than or equal to the range size"
                    ' Exit Function
    End If
   
    ' resize our array
    ReDim rangeSet(rangesize - 1) 'REDIM RANGE SET(39)
   
    ' build the range set
    For i = 0 To rangesize - 1  '0 TO 39
        rangeSet(i) = i + rangeMin
        rangeSet(0) = 0 + 1 = 1
        rangeSet(1) = 1 + 1 = 2
       
    Next i
   
    ' shuffle the range set 7 times
    For r = 1 To 7
            ' for each item in the set,
        ' pick another item and
        ' swap them
        For i = 0 To rangesize - 1  'I = 0 TO 39           ARR NO1  NO2 RESULT
            swapWith = Int(rangesize * Rnd) 'ASSUME 2,7
            'SWAPWITH = 2
            'SWAPWITH = 7
            tempInt = rangeSet(i)
            'TEMPINT = 1
            'TEMPINT = 2
            rangeSet(i) = rangeSet(swapWith) 'RANGESET(2), RANGESET(7)
            'RANGESET(0) = RANGESET(2)
            'RANGESET(1) = RAANGESET(7)
            rangeSet(swapWith) = tempInt
            'RANGESET(2) = 1
            'RANGESET(7) = 2
        Next i
    Next r
                 
    ' return the selected set
    ReDim Preserve rangeSet(setSize - 1)
    generateSet = rangeSet
End Function
0
Comment
Question by:gonzal13
  • 5
  • 3
  • 2
10 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 50 total points
Comment Utility
Hi gonzal13,

The problem is right here:

    ' build the range set
    For i = 0 To rangesize - 1  '0 TO 39
        rangeSet(i) = i + rangeMin
        rangeSet(0) = 0 + 1 = 1                         <---- You forgot to put the single apostrophe making it a comment
        rangeSet(1) = 1 + 1 = 2                         <---- You forgot to put the single apostrophe making it a comment
    Next i

If you change it to this:

    ' build the range set
    For i = 0 To rangesize - 1  '0 TO 39
        rangeSet(i) = i + rangeMin
        rangeSet(0) = 0 + 1 = 1
        rangeSet(1) = 1 + 1 = 2
        If i = 0 Then
            MsgBox "rangeSet(0) = " & rangeSet(0)
            MsgBox "rangeSet(1) = " & rangeSet(1)
        End If
    Next i

You will see that rangeSet(0) and rangeSet(1) are both -1, and those values then get swapped in with the regular values.  I'm not quite sure how they become -1.  I think that it is a conversion of the boolean values returned by the comparison with the equals sign in there:

    rangeSet(0) = 0 + 1 = 1

Starting from the right, does 1 = 1? Yes, so it returns True.  Then we have 0 + True and I'm not sure how that is -1 but it doesn't make sense anyways.  =)

So, make those two lines comments and the -1 problem will go away.

As for this comment:

    'Debug.Print i & " = " & selected(i) 'DEBUG DOES NOT WORK BUT PRINT ETC DOES

You can view things printed with Debug.Print in the Immediate window in the IDE.  If you don't see the Immediate window in your IDE (it's usually at the bottom), click on View --> Immediate Window or just press <Ctrl-G> to turn it back on.  I like the immediate window because it can hold more than the form does.  You can scroll up and down to see the outputted values.  It does have limit however, you just have to experiment to find out what it is.

Regards,

Idle_Mind
0
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
the reasin that this line:

 rangeSet(0) = 0 + 1 = 1


produces -1 is that RangeSet() is Dimmed as Integer and the line is evaluated as :

 rangeSet(0) = (0 + 1 = 1)  

which sets the value of RangeSet to the 'TRUTH' value (True = -1, False =0) of the BOOLEAN expression (0+1 = 1) which is OBVIOUSLY TRUE, as is the Truth value of (1+1 = 2).  Hence RangeSet(0) and RangeSet(1) both get set to the Integer value of TRUE which is -1.

AW
0
 
LVL 13

Author Comment

by:gonzal13
Comment Utility
Authur: Thanks for the comment:

Here is the history on the question:

First I am new at VB6. I took a semester course and the teacher only taught 1 of the two classes he was supposed to lecture at. The other he made a lab. Anyway I got cheated. Not giving up and wanting to learn visual basic since it is beter than watching television or better than chess I embarked on a large project that would incorporate many features of VB6. Being a retired engineer, I always in my career was given project that normally I had absolutely no knoweledge about since they were based only on laboratory experiments that had to be turned into production lines. So I am used to pushing the envelope comfortably. Being retired at 60,(retired at 50), I have the luxury of enjoying myself in such projects.

Anyway Idle Mind presented me with a more complicate solution which I wanted to learn the details. Finally I split the points evenly and decided to take the easy way out. Idle_Mind offered to help me understand his code. Thus I opened up another question for such discussions.

I originally needed a set of code to produce non repetive random  numbers in a given range. I received one that was very simple and one from Idle_mind that was complicated. I eventually raised the points as the answers kept coming back to 400 points.

gonzal13(joe)
0
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
non-repetitive 'random' numbers in a given range sounds like shuffling a deck of cards - that gives you a 'random' set of 52 values (1 - 52 in RANDOM ORDER).  This is different from generating random numbers.  It does NOT require using the Random Number generator at all, but rather simple 'scrambling' the values in the selected range, so that they come up in what appears to be a random order.

check out this link:


http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=35248&lngWId=1

by the way,
 
http://www.planet-source-code.com/

is a great resource for code, and for learning.

AW
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Arthur_Wood,

That is exactly what my code is doing, except that it is generically written so that you can have any start/stop values instead of 1 to 52.  You can request the entire set shuffled or return just the first "x" values from the shuffled set.

The code you see above has extra code added in it by gonzal13 during his attempts to understand how it works.  You can see the original thread and code here:
http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_21132867.html

Regards,

Idle_Mind
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 13

Author Comment

by:gonzal13
Comment Utility
Arthur: I went to the sites that you listed. Very interesting
At this moment, I prefer the VB method instead of the symplistic method.

gonzal13(joe)
0
 
LVL 13

Author Comment

by:gonzal13
Comment Utility
Idl_Mind:

Your code works perfectly and I do now understand allot of it. I put your comments attached to the code.

Now I have another rather simple question as least what it looked like.

What I wanted to do is to save and read a two dimensional array by calling it from a function. I am still learning th fundamentals. I realize that I must do more of ths type of coding to make lfe symple.

http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_21148733.html#12216844

The above is the site. the last comment I received was that I needed to do more studying. Well if I do dot have the code for a specific activity then it is hard for me to learn.. I have in the comments portion two sample methods which do nt work. In any case I need to do it from a function:

Dim ABC(400, 2)

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
code generates a list of  numbers in the form shown ABC(k,2)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

With this I need the exact code to put into the module

Next I need the exact code to Call the function.

DO not worry, I am studying VB on my own now. It is better than chess. Besides at 60 it is a wonderful method to keep the brain active.

Joe


I would love your expertise and patience in teaching me this item. It is at 500 points.
0
 
LVL 13

Author Comment

by:gonzal13
Comment Utility
Close
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Hi Joe,

I have taken a quick look at your other question referenced above.  There is a lot of information to sift through in there...

I'll come up with an example for you and make a post in that thread.  Give me some time to read the other posts more carefully though.

~IM
0
 
LVL 13

Author Comment

by:gonzal13
Comment Utility
Thanks:
no hurry

Joe
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now