[Gambas-user] A random sort of listview

Simonart Dominique simonart.dominique at ...11...
Tue Apr 7 17:20:09 CEST 2009


Hi,

jbskaggs a écrit :
> When I ran the code it ran fine- why is it important to have it  count
> backwards in the random swap?
> 
> ie for i =199 to 0 step -1 instead of for i=0 to 199 step 1?
> 
> JB SKaggs
> 
Strange, because it should not  :)
run a test with 10 numbers 0-9 and fixe the seed with 
RANDOMIZE 12345
If you run the forward FOR NEXT you will get:
0 0 2 3 1 1 2 6 3 8
which is wrong!
but if you run the backward FOR NEXT you will get:
5 1 9 6 0 3 8 7 2 4
which is right!

May be you did not notice it because 200 is long enough 
before you get the same number twice, and before you remark 
that some are missing?

Dominique Simonart

> 
> Simonart Dominique wrote:
>> Hi,
>>
>> Hmm, did you run exactly this code? If so, there is 
>> something wrong with the second FOR NEXT loop
>>
>> jbskaggs a écrit :
>>> using your suggestions and the swap command vs manual swapping this is my
>>> code:
>>>
>>> public b as string  'optional string used to hold the array data for file
>>> or
>>> split later
>>>
>>> PUBLIC SUB button4_click() ' initialize array
>>> DIM myArray AS Integer[200]
>>> DIM a AS Integer
>>> DIM i AS Integer
>>>
>>> FOR i = 0 TO 199 STEP 1 'add array items 
>>>  myArray[i] = i 
>>> NEXT 
>>>
>>> FOR i = 0 TO 199 STEP 1 ' random swap array items
>>> a = Int(Rnd(i + 1))
>>> SWAP myArray[i], myArray[a]
>>> NEXT 
>>>
>> the right code is:
>>
>> FOR i = 199 TO 0 STEP -1
>>     ...
>> NEXT
>>
>>> FOR i = 0 TO 199 STEP 1 ' write items in listview2
>>> listview1.MoveTo(myArray[i])
>>> c = listview1.Item.Key
>>> listview2.add(c, listview1.item.text) 
>>> NEXT 
>>>
>>>
>>>
>>> FOR i = 0 TO 199 STEP 1 'optional step to write array as a string for
>>> file
>>> or whatever use
>>> b &= "slot" & myArray[i] & ","
>>> NEXT 
>>> PRINT b
>>> END
>>>
>>> PUBLIC SUB Button1_Click() 'an optional way to load the array values from
>>> the variable b and / or a file if b was file loaded
>>> DIM egg AS String[]
>>> DIM c AS String
>>>  listview1.Clear
>>>  egg = Split(b, ",")
>>>  FOR EACH c IN egg 
>>> TRY listview1.Add(c, c) 
>>> IF ERROR THEN RETURN 
>>> NEXT 
>>> IF listview1.Count >= 200 THEN RETURN 
>>> END
>>>
>>> JB Skaggs
>>>
>> Dominique Simonart
>>
Dominique Simonart





More information about the User mailing list