Created
November 20, 2023 10:53
-
-
Save anchietajunior/3e892dbfbd534a785c0bc06bb9a0ccda to your computer and use it in GitHub Desktop.
Implementing MS-Paint's “paint bucket”
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def flood_fill(image, x, y, new_color) | |
target_color = image[x][y] | |
fill(image, x, y, target_color, new_color) | |
end | |
def fill(image, x, y, target_color, new_color) | |
return if x < 0 || x >= image.length || y < 0 || y >= image[0].length | |
return if image[x][y] != target_color | |
return if image[x][y] == new_color | |
image[x][y] = new_color | |
fill(image, x - 1, y, target_color, new_color) | |
fill(image, x + 1, y, target_color, new_color) | |
fill(image, x, y - 1, target_color, new_color) | |
fill(image, x, y + 1, target_color, new_color) | |
end | |
# Manual Tests | |
image = [ | |
['.','#','#','#','.','.'], | |
['.','#','.','.','#','.'], | |
['.','#','#','#','.','.'], | |
['.','#','.','.','.','.'] | |
] | |
flood_fill(image, 0, 1, 'O') | |
image.each { |row| puts row.join } | |
puts "------" | |
image = [ | |
['.','#','#','#','.','.'], | |
['.','#','.','.','#','.'], | |
['.','#','#','#','.','.'], | |
['.','#','.','.','.','.'] | |
] | |
flood_fill(image, 1, 3, 'o') | |
image.each { |row| puts row.join } | |
puts "------" | |
image = [ | |
['.','#','#','#','.','.'], | |
['.','#','.','.','#','.'], | |
['.','#','#','#','.','.'], | |
['.','#','.','.','.','.'] | |
] | |
flood_fill(image, 1, 3, '#') | |
image.each { |row| puts row.join } | |
# Tests | |
require 'rspec/autorun' | |
describe 'flood_fill' do | |
it 'correctly fills an area with the new color' do | |
image = [ | |
['.','#','#','#','.','.'], | |
['.','#','.','.','#','.'], | |
['.','#','#','#','.','.'], | |
['.','#','.','.','.','.'] | |
] | |
expected_image = [ | |
['.','O','O','O','.','.'], | |
['.','O','.','.','#','.'], | |
['.','O','O','O','.','.'], | |
['.','O','.','.','.','.'] | |
] | |
flood_fill(image, 0, 1, 'O') | |
expect(image).to eq(expected_image) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment