-1

Ultimately I'm making a slider puzzle with a table, but at the moment I am generating a new puzzle and shuffling the tiles, but it appears that something in my code is making this work incorrectly. (not all the table cells are populated, etc.) Any idea what could be causing this?

In the program I am writing, I am using body onload to build the puzzle but for some reason that won't work in the Fiddle:

</head>
<body onload="newPuzzle(_r, _c)">
</body>

Fiddle Example

user5407906
  • 87
  • 1
  • 8

1 Answers1

0

Try changing

//declare and populate array
 var _array = new Array();

 for (var i = 0; i <= r*c; i++)
 {
   _array[i] = i;
 }

to

//declare and populate array
 var _array = new Array();

 for (var i = 1; i < r*c; i++)
 {
   _array[i] = i;
 }
   _array[0] = "";

AND changing this:

var rand = Math.floor(Math.random() * _array.length) + i;

to this:

var rand = Math.floor(Math.random() * _array.length);

Just a note, as you're shuffling with a new array, there is not point in the first configuration (0 to 8), that way you can remove two FORs and just set a fixed value when generating it (before shuffle). Like so:

gridTable[0].rows[i].cells[j].innerHTML = "0";
FirstOne
  • 6,033
  • 7
  • 26
  • 45
  • I made the changes you suggested and a couple of other minor fixes, but unfortunately I'm still having the same problem. I'm not sure what you meant by that last bit? Which two should I remove? – user5407906 Oct 06 '15 at 03:54
  • That last part is just a hint. Think about it, why do you need to populate the puzzle with `0 to 8` when you are generating it if you're not reading those values? When you shuffle, you are defining a `new array`, non related to the values of the game. So, it won't matter if you set `0 to 8` or `FOO`, or `BAR` to it before shuffle. – FirstOne Oct 06 '15 at 04:00
  • Basically, you don't have to go through all the work of `loop` inside `loop` just to create a matrix to have `0 to 8` if these values won't be even used later when shuffling. – FirstOne Oct 06 '15 at 04:02
  • Oh! Yes, in the newPuzzle function. Thank you for your help! – user5407906 Oct 06 '15 at 04:12
  • Is the problem solved? If not, can you elaborate? @user5407906 – FirstOne Oct 08 '15 at 02:24
  • I figured it out - your solution worked when I changed my array to start at 1 and count up to 8 :) Thank you! – user5407906 Oct 09 '15 at 22:48