Skip to content

Instantly share code, notes, and snippets.

@jonatas
Created April 6, 2020 02:03
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 jonatas/f02718b0d51e79cc61f3eba3ffd8fc54 to your computer and use it in GitHub Desktop.
Save jonatas/f02718b0d51e79cc61f3eba3ffd8fc54 to your computer and use it in GitHub Desktop.
def crossed_words size = 20
words = %w[jonatas aline lorenzo lucas
joao juca pedro mariana
pedroca joana bartolomeu
maria louise ana carol luiza salete rafael leandro]
matrix = (0..size).map{|_|['.']*size}
n = 0
while words.any?
word = words.sort_by(&:size).last
orientation = ['vertical', 'horizontal'].sample
if orientation == 'horizontal'
x, y= rand(size), rand(size - word.size+1)
if Regexp.new(matrix[x][y,word.size].join).match?(word)
matrix[x][y, word.size] = word.split ''
words.delete word
end
else
x, y= rand(size-word.size+1), rand(size)
if Regexp.new(matrix[x,word.size].map{|e|e[y]}.join).match?(word)
word.split('').each_with_index do |w,i|
matrix[x+i][y] = w
end
words.delete word
end
end
n += 1
break if n > 5000
end
puts "#{size}x#{size} finished in #{n} cycles", matrix.map{|e|e.join(" ")}
end
crossed_words(12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment