I have a 2d matrix (x/y-matrix) like this:
var matrix=[
'111111',
'100001',
'101101',
'100001',
'111111'
]
Id like to find all connected '1'-characters (ones) starting from any point and push the result of the connected positions to an array.
Calling my function with e.g (X:2, Y:2) will return the positions I have marked with the '2'-char below:
var matrix=[
'111111',
'100001',
'102201',
'100001',
'111111'
]
Calling my function with e.g (X:4, Y:4) will return this coordinates also marked with '2':
var matrix=[
'222222',
'200002',
'201102',
'200002',
'222222'
]
So I've already written some code but it doesn't seems to work that way & Im absolutely not sure if this would be the most efficient solution. So I hope somebody like to share some code matching my problem, thanks a million in advance,
-- Jonas
Array.prototype.extract_specific_components_positions = function(x_position, y_position, selector) {
var matrix = this.map(str => Array.from(str, Number)),
result_array = []
function test_connection(array, i, j, value, callback) {
try {
if (array[i][j].toString() == selector) {
result_array.push([j, i]);
array[i][j] = value;
test_connection(array, i - 1, j, value, callback);
test_connection(array, i + 1, j, value, callback);
test_connection(array, i, j - 1, value, callback);
test_connection(array, i, j + 1, value, callback);
}
else {
callback(j, i)
}
}
catch (e) {
callback(j, i)
}
}
matrix.forEach(function(a, i, aa) {
a.forEach(function(b, j, bb) {
if (i == y_position && j == x_position) {
status = true
}
if (!status) return false
test_connection(aa, i, j, 2, function(j, i) {
status = false;
})
})
})
matrix = matrix.map(a => [a.join('')]).concat.apply([], matrix.map(a => [a.join('')]));
return [matrix, result_array]
}
var matrix=[
'111111',
'100001',
'101101',
'100001',
'111111'
]
var result = matrix.extract_specific_components_positions(0,0,'1')
console.log(result[0].join('\n'))
console.log(result[1])