The following warnings occurred:
Warning [2] Undefined array key 0 - Line: 1677 - File: showthread.php PHP 8.2.31 (Linux)
File Line Function
/inc/class_error.php 157 errorHandler->error
/showthread.php 1677 errorHandler->error_callback
/showthread.php 916 buildtree




Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What's wrong with this code?
#1
Okay, this is driving me mad. :-D

I wrote a little routine to 'shuffle' the numbers 1 to 10 into an array, randomly. It's not exactly the best way of doing this but it was supposed to be a quick test. Regardless, it doesn't work. Or rather, it does work - the first time you run it. The second loop of the same code never completes and I can't decide if I found a bug or if I've made a mistake.

Here's the code:
Code:
dim levelMap(10) as UBYTE randomize for x = 1 to 10 cls generateLevelMap() for n = 1 to 10: print levelMap(n): next n pause 0 next x SUB generateLevelMap() dim lm as UBYTE dim lmPos as UBYTE = 0 'clear the map first for lm = 1 to 10 levelMap(n) = 0 next lm 'debug code to print the map, to make sure it's empty print for lm = 1 to 10 print levelMap(n);","; next lm print pause 0 'now fill it randomly print for lm = 1 to 10 do 'get a random position in the array lmPos = int(rnd * 10) + 1 'debug code to print the number we randomly picked print lmPos;","; 'debug code to print the array element if it ISN'T empty if levelMap(lmPos) <> 0 then print ink 2;levelMap(lmPos);","; end if loop until levelMap(lmPos) = 0 'write the current number into the empty random element levelMap(lmPos) = lm 'debug code to show that we handled this number okay print inverse 1;lm next lm pause 0 cls END SUB

I've stuck a load of debug info in there so that you can see what it's doing.

Basically it does this:
1. Clear the array to all zeroes
2. For each number, 1 to 10....
3. Look in a random array position to see if it's zero.
3a. if it isn't, loop around to 3 and try a different one
3b. if it is, write the number into that array position and move on to the next number
4. The result should be the numbers 1 to 10 in a random order in the array, after a variable number of iterations.

First run, no problem.

Second run, although the debug code shows that the array was cleared, the do...loop until loop never completes - by the time it's checking the array within that loop it contains the OLD values again, despite me having zeroed them out just a few seconds earlier.

Am I missing an obvious goof? :-D
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)