简体   繁体   中英

Array sometimes doesn't work as expected

I've got a game in development for Android. I've got most of it up and running, but have just noticed a bug, that I can't always replicate, which (as you know) makes it a nightmare to debug! I'm sure its a logic problem, but I've been staring at it for so long I can't see it. This is the code that sorts the arrays:

    // RANDOMISE UP SOME LETTERS //
    for(int i=0; i<MAX_LETTERS; i++)
    {
        int r = rand.nextInt(25);       

        // SAVE THIS LETTER //
        lettersToUse[i] = letters[r];           
    }       

    // NOW MAKE SURE WE COPY IN OUR WORD //
    for(int i=0; i<nameLen; i++)
    {
        int r = rand.nextInt(MAX_LETTERS);

        Letter tmpLetter = new Letter();
        tmpLetter = letters[lettersInName[i]];                      

        while(in_array(lastElementsUsed, r))
        {
            r = rand.nextInt(MAX_LETTERS);
        }

        lastElementsUsed[i] = r;            

        if(!in_array(lettersToUse, tmpLetter.getLetter()))
        {               
            lettersToUse[r] = tmpLetter;
        }
    }

I've got an array of 18 allowed letters (in the app). The first loop (obviously) just picks a load of random letters. The second loop, then ensures that at least one letter of the word to be guessed is included in the final 18 letters.

The trouble is: Most of the time it works flawlessly. At seemingly random intervals, the final array will be missing a letter from the word to be guessed. It's not always in the same place in the word either.

Can anyone see a problem with my logic? I'm happy to give more information and code, if I've missed a vital piece of the puzzle!

TIA.

This method seems a lot simpler:

for (int i=0; i<(MAX_LETTERS-wordLength); i++)
{
    int r = rand.nextInt(25);       

    // SAVE THIS RANDOM LETTER //
    lettersToUse[i] = letters[r];           
}   
for (int i=MAX_LETTERS-wordLength; i<MAX_LETTERS; i++)
{
    // SAVE THIS LETTER OF THE WORD //
    lettersToUse[i] = lettersInName[r]; //I think that lettersInName is the right variable name to use, hopefully you understand what I'm trying to do here           
}   
lettersToUse.shuffle() //or similar method for whatever array type you're using

Which then ensures you have your word plus the rest of the 18 are filled with random ones, and they've been shuffled

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM