I have a list of words that dynamically generate a grid.
The problem is I need a 6×6 grid and if there is not enough words in the list to facilitate a 6×6 (12 words) then it won’t.
How can I make it so it always produces a 6×6 grid, randomly generates positions for the words and fills the gaps with empty cells?
var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"];
var shuffledWords = listOfWords.slice(0).sort(function() {
return 0.5 - Math.random();
}).slice(0, 6);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
for (var k = 0; k < word.length; k++) {
var cell = document.createElement('td');
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
Updated JSFiddle
I added:
So if there are not enough words, it appends the array with empty ‘words’ (3 spaces) and that gets shuffled, which results in random blank spaces
EDIT
JSFiddle with 12 words
EDIT2
I think this is what you want:
JSFiddle with 6 words, filled with spaces