for( int i = 0; i < wordList.length; i++ ) { //Get a word from the wordList char[] word = wordList[i].toCharArray(); //Increment the number of attempts to add this word to the puzzle attempts++; //Set added to true by default. It will change otherwise added = true; //Chose the direction that the word will take. Repeat the process //if both directions end up being 0 do { horizontal = (int)Math.round( Math.random() ); vertical = (int)Math.round( Math.random() ); if( (int)Math.round( Math.random() ) == 1 ) { horizontal = -horizontal; } if( (int)Math.round( Math.random() ) == 1 ) { vertical = -vertical; } } while( horizontal == 0 && vertical == 0 ); //Copy the current array into the backup array in case the current //word does not fit and needs to be removed for( int j = 0; j < puzzle.length; j++ ) { for( int k = 0; k < puzzle[j].length; k++ ) { oldPuzzle[j][k] = puzzle[j][k]; } } //Randomize the pointer's starting position pointerHoriz = (int)Math.round( Math.random() * columns ) % columns; pointerVert = (int)Math.round( Math.random() * rows ) % rows; //Attempt to place the word into the puzzle for( int j = 0; j < word.length; j++ ) { //If the pointer is pointing to a blank space or a space that //contains the letter that we're attempting to add, add the //letter to that space and increment the pointer if( Character.isWhitespace( puzzle[pointerHoriz][pointerVert] ) || puzzle[pointerHoriz][pointerVert] == word[j] ) { puzzle[pointerHoriz][pointerVert] = word[j]; pointerHoriz = ( pointerHoriz + horizontal ); pointerVert = ( pointerVert + vertical ); if( pointerHoriz < 0 ) { pointerHoriz = columns - 1; } else { pointerHoriz = pointerHoriz % columns; } if( pointerVert < 0 ) { pointerVert = rows - 1; } else { pointerVert = pointerVert % rows; } } //Otherwise, revert the puzzle back to its old state and //break out of the loop else { for( int k = 0; k < puzzle.length; k++ ) { for( int l = 0; l < puzzle[k].length; l++ ) { puzzle[k][l] = oldPuzzle[k][l]; } } added = false; } } //If the word was not added, try again, up until 10 attempts if( !added && attempts < 10 ) { i--; } //If 10 attempts have been reached, print word to standard error else if( !added && attempts == 10 ) { System.err.println( wordList[i] ); attempts = 0; } //Otherwise, update the oldPuzzle to include the new word else if ( added ) { for( int j = 0; j < puzzle.length; j++ ) { for( int k = 0; k < puzzle[j].length; k++ ) { oldPuzzle[j][k] = puzzle[j][k]; } } attempts = 0; } } //Once an attempt to add all the words has been made, fill any //remaining spaces on the board with random characters for( int i = 0; i < puzzle.length; i++ ) { for( int j = 0; j < puzzle[i].length; j++ ) { if( Character.isWhitespace( puzzle[i][j] ) ) { puzzle[i][j] = (char)( Math.random() * 26 + 'A' ); } } }