Hi,
I’m currently doing a fun project, where I stumble upon the quite annoying fact, that between some methods the arrays (they are the parameters) are passed by reference, which screws up the logic.
does anyone have an idea, how I can pass the arrays by value?
btw. tested in FF 3.6, Chrome (Opera quit due to Date.now()) / Mac
I’m currently doing a fun project, where I stumble upon the quite annoying fact, that between some methods the arrays (they are the parameters) are passed by reference, which screws up the logic.
does anyone have an idea, how I can pass the arrays by value?
Code:
GAME.MagicSquare.prototype.createTable = function ()
{
var doc = document,
// create various HTMLElements
rows = this.rows,
cols = this.columns,
arr = [],
i, j, tr_i, td_j, num, range, values;
range = (rows * cols);
// create the result array necessary for win test
this.result = [];
for (i = 1; i < range; i += 1) {
this.result.push(i);
}
// create mixed and valid configuration
do {
// couldn't get it to be passed by value
for (i = 0; i < range; i += 1) { // fix for problem #1
arr.push(i);
}
[B]values = this.scramble(arr);[/B] // <-- problem #1
}
[B]while (this.unsolvable(values));[/B] // <-- problem #2
// create the table
return table;
};
GAME.MagicSquare.prototype.scramble = function (a)
{
var i, index,
values = [];
for (i = a.length; i--;) {
index = Math.round(Math.random() * 100 * i) % i;
values.push(a.splice(index, 1)[0]);
}
// [I]a[/I] is now [] and in the calling function [I]arr[/I] also is []
return values;
};
GAME.MagicSquare.prototype.unsolvable = function (a)
{
var i, j,
inversion = 0,
l = a.length,
zero = a.indexOf(0),
cols = this.columns;
// move the 0 to the last row
j = l - cols;
while (zero < j) {
a[zero] = a[zero + cols];
a[zero + cols] = 0;
zero += cols;
}
// again, in the calling function, the array (named [I]values[/I]) always has the 0 in the last "row"
// determine number of values, that are placed after its successors
for (i = 0; i < l; i += 1) {
for (j = i + 1; j < l; j += 1) {
if (a[i] > a[j] && a[j] > 0) {
inversion += 1;
}
}
}
// even number of "inversion" means solvable
if (1 === (inversion % 2)) {
return true;
}
return false;
};
Comment