Looking for the leftmost and topmost connected '1' character in a 2D matrix?
- Find the most left & top connected '1' character
- Find the most right & bottom connected '1' character
EDIT 2.0:
To start, provide the coordinates for the initial '1' character.
10001
00001
11111
01110 --> (x: 1, y: 3)
The function will iterate through adjacent columns to find connected '1' characters for x or y value calculation.
Your function initiates at a specific point (e.g. y: 2, x: 0)
var array = [
'00000',
'01111', --> get position of the most top & right '1'-character (x: 4, y: 1)
'11000',
'00000'
]
This function retrieves the top-right end of '1' characters:
var array = [
'00000',
'01111',
'11000',
'00000'
]
Array.prototype.get_top_right = function(x_pos, y_pos) {
var matrix = this, y1= y_pos;
for (var x1 = x_pos; x1 < this[0].length; x1++) {
try {
if (matrix[(y1-1)][x1] == '1') y1--;
else if (matrix[y1][(x1+1)] != '1') break;
} catch(e) {}
}; return [x1,y1]
}
var result=array.get_top_right(0,2)
console.log(result)
Want to find the most bottom-left connected '1' character now?
var array = [
'00000',
'01111',
'11000', --> get position of the most bottom & left '1'-character (x: 0, y: 2)
'00000'
]
Check out the updated function below to achieve this:
Array.prototype.get_bottom_left = function(x_pos, y_pos) {
var matrix = this, y2= y_pos;
for (var x2 = x_pos; x2 > 0; x2--) {
try {
if (matrix[(y2+1)][x2] == '1') y2++;
if (matrix[y2][(x2-1)] != '1') break;
} catch(e) {}
}; return [x2,y2]
}
Don't forget to test your updated function with the error_array provided below.
var error_array = [
'000000',
'000011',
'111110',
'111111'
]
If you encounter any issues, seek help from the community. Good luck!
Best regards,
- hans