Skip to content

Instantly share code, notes, and snippets.

@theaboutbox
Created February 7, 2014 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theaboutbox/8865613 to your computer and use it in GitHub Desktop.
Save theaboutbox/8865613 to your computer and use it in GitHub Desktop.
def found_sequence?(grid, sequence, position, direction)
return true if sequence.size == 0
row,col = position
return false if [row,col].min < 0
return false if row >= grid.length
return false if col >= grid[row].length
return false if grid[row][col] != sequence[0]
dy,dx = direction
return found_sequence?(grid, sequence[1..-1],[row+dy,col+dx],direction)
end
def find_sequence(grid,sequence)
# Define some directions, just to make the code simpler
directions = {
east: [0, 1],
south: [1, 0],
south_east: [1, 1],
south_west: [-1, 1]}
grid.each_with_index do |row_str,row|
row_str.chars.each_with_index do |col_char,col|
directions.each do |dir, vector|
if found_sequence?(grid,sequence,[row,col],vector)
puts "Found #{sequence} at row #{row}, col #{col}, direction: #{dir}"
end
end
end
end
end
# Create an array of rows
grid =
"AAYKAKAYKAYYKKAAKAYAAAYKYKYAYK
KYYAKYAAAYKAAKKYAKKKAAAKAAYKAA
KKKYAKAKAYKKYKKYKKAKYAAAAKAAKK
YKAAKYAAKKKKKAYAYYYYYAAKAAKKKK
KKAYYAAKKYYAYAAKAAKKAAYKAKKAAK
KKAAAKAAAKKAKKKYAAAYKYAYAKYKAA
KKYKAAAAAAAAAAKKAAAKYYAKAKAKKY
KKKKKKAKYYKYYKKAAYAKAAAKYAKKAA
KAKKAKAYKAAYAKYYKKAYKKKAAAAAKA
KKAKAKAKAAAKAYAYKAKAYYAYKKAKYY
AAAYAKKKAKKAKYKAYKKAKKYKAAKKYY
YKKKYKKYAAAKKKKAKAYKKKKKAAKKKY
KKAKAYKAAKAKKYYAKAYAAKYAAAAAAA
AAAAKKYAAKKAAYKKAAAYAYAKYAKAYK
AKKAKKAYKAAYKYKAKYAAKKYKKKKKKA
KYKAAKKYAYKAKKKYKAKAYAYKYAAAKK
KAYYKKAKYKAYAAKAYAAYYYAKKYKYKK
KKKKAKAYAAAKKAYAYKKYAKAAAAYKAY
AYKAKKKAAKAKAYAAAKKYKKAYKAYAYY
KYAYKAYAKAKYYKYKAKAAYKYKKAYKAK
AKAKKAKKAKKKKAAAKYYYYKAKAAAAAK
KAKYYKAKKYKYAKYAAAAAKAKAYAAKKA
KKAAAKKAKAKKAAKAYAAYAAAKKAAYYA
KAKKYYKKAYAYKKAKKYYKYKYKKAAAKA".split("\n")
sequence = "KAYAK"
find_sequence(grid,sequence)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment