Android Question Fisher - Yates Shuffle

Discussion in 'Android Questions' started by juniorteacher, Apr 30, 2015.

  1. juniorteacher

    juniorteacher Member Licensed User

    i make button with random number no repeat, but get error
    it's my code

    Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim btn(8) As Button
    Dim i, k, x,j As Int
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")

    For i = 0 To 7
    btn(i).Initialize("btn")
    Activity.AddView(btn(i),5%x,15dip + i*75,80%x,60dip)
    btn(i).Text = i
    Next
    For j = 0 To 7
    k = Rnd(j, 7) 'error in this section
    x = btn(j).Text
    btn(j).Text = btn(k).Text
    btn(k).Text = x
    Next

    End Sub

    please help, thank you
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    Please use [code]code here...[/code] tags when posting code.

    You should also post the error message.

    Rnd upper limit is exclusive. You should change it to 8.
     
  3. RandomCoder

    RandomCoder Well-Known Member Licensed User

    I see what you are trying to do and your thought process but it is wrong. As Erel has pointed out, there will be occasions when the random function will be Rnd(7,7) which is probably the reason for your error. But even if you change the Max random value to 8 it still won't give you the result your looking for. You are just limiting the randomness of your values with each iteration.
    The way I personally prefer to do this type of thing is to add all the values you need to a list then randomly remove from the list. That way you get a random order and it's impossible to get duplicates unless of course you add duplicates to the list. ;)
     
    DonManfred likes this.
  4. juniorteacher

    juniorteacher Member Licensed User

    fix thanks all
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice