I’d like to find out how I would go about turning an array like this:
Into an array that looks like this:
I had no idea how to phrase this question so I didn’t look it up online.
I think you you wanna achieve is to fill the hole which is bounded by 1
.
Take every 0
from the array and find a 1
value in every directioin, if every direction has a 1
, then it can be filled with 1
as well.
There could be use-case where you need to check, if such shape is closed (there are no holes).
This could be achieved by testing first zero, moving to its zero neighbor in every direction, and testing it as well. All tested subjects must be saved into an array as position before changing them. If at least one zero fails with the check, then the shape is not closed. However if there are no more zeroes to be tested, take such array of positions, and set these values on these positions to 1
.
This looks like floodfill algorithm soI think you should look into that.
What exactly are you trying to achieve? What sort of pattern are you trying to make/achieve?
Edit: nvm I got it.
Managed to do it, thanks to @Cloudy71 for pointing out what you are trying to do and to @dthecoolest for pointing out the algorithm that does this, here’s the code.
local array = {
{0, 1, 0, 0, 0, 0},
{1, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 1, 0},
{0, 1, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0},
{0, 0, 0, 0, 0, 0},
}
function floodFill(array, x, y, old, new)
if x < 1 or x > #array or y < 1 or y > #array[x] or array[x][y] ~= old then
return
end
array[x][y] = new
floodFill(array, x-1, y, old, new)
floodFill(array, x+1, y, old, new)
floodFill(array, x, y-1, old, new)
floodFill(array, x, y+1, old, new)
end
floodFill(array, 3, 3, 0, 1)
print(array)
Now for the explanation. Firstly we will define the array and the function and it will be a recursive function.
Inside the function we check if the current cell is out of bounds or has a different value (not old) so we stop the code, after passing the if statement, we set the value in the array (currently as old) to new (argument passed) then we call the function to do the same thing again for the element before, after, up and down and it will keep on calling itself until the whole array is “changed”.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.