I have wrote a lot of recursive functions which are worked well, But I have a problem with this one. I have a module containing two matrix. So inside the recursive function I use these matrix using this
keyword. First call work well, but then this
content is different and I cannot access my matrix!
here is my codes:
index.js:
var TileAttack = require('./lib/problem/AttackedTier/TileAttack').TileAttack;
this.board = [
[0, 1, 0],
[1, 0, 0],
[0, 0, 1]
];
this.attackBoard = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
this.tileAttack = TileAttack;
this.tileAttack.init(this.board);
this.tileAttack.checkDown(0, 0, this.tileAttack.isQueenIn(0, 0));
TileAttack.js:
let board;
let attackBoard;
let boardSize;
function init(board) {
this.board = board;
this.attackBoard = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
this.boardSize = this.board.length;
}
function checkRight(i, j, wasQueenInPath) {
checkAttack(i, j, wasQueenInPath, i, j + 1, checkRight);
}
function checkDown(i, j, wasQueenInPath) {
checkAttack(i, j, wasQueenInPath, i + 1, j, checkDown);
}
function checkAttack(currentI, currentJ, wasQueenInPath, nextI, nextJ,
currentMove) {
let queenSeen = false;
if (currentI >= this.boardSize) return queenSeen;
if (isQueenIn(currentI, currentJ)) {
queenSeen = true;
currentMove(nextI, nextJ, queenSeen);
return queenSeen;
}
if (wasQueenInPath) this.attackBoard[currentI][currentJ]++;
queenSeen = currentMove(nextI, nextJ, wasQueenInPath);
if (queenSeen) {
this.attackBoard[currentI][currentJ]++;
return queenSeen;
}
}
function isQueenIn(i, j) {
return this.board[i][j] == 1;
}
exports.TileAttack = {init, checkDown, checkRight, isQueenIn}
The point which is different here from my previous tries is that I exports an object of functions here. in previous samples I just exports one function.
EDIT
These codes are worked well:
function sort(low, high) {
if (high <= low) return;
let pivotIndex = partition(low, high);
sort(low, pivotIndex - 1);
sort(pivotIndex + 1, high);
}
function partition(low, high) {
let pivot = this.arr[low];
let pivotIndex = low;
for (i = low + 1; i <= high; i++){
if (pivot > this.arr[i]) {
pivotIndex++;
exchange(i, pivotIndex);
}
}
exchange(low, pivotIndex);
return pivotIndex;
}
What's the diffrence between my second codes and first one? Can any one get the problem?