module BoggleGrid
BoggleGrid — standard 4×4 Boggle dice (1992 Hasbro), roll, and path search. Public: DICE, roll_grid, word_on_grid? Tests: test/lib/boggle_grid_test.rb
Constants
- DICE
-
Official 16 dice from the 1992 Hasbro
Boggleset (Princeton algs4 / Hasbro). - DIRECTIONS
Public Instance Methods
Source
# File lib/boggle_grid.rb, line 43 def coerce_rng(rng, rand) return rng if rng.is_a?(Random) return Random.new if rand.nil? seed = rand.call(1_000_000) Random.new(seed) end
Source
# File lib/boggle_grid.rb, line 64 def path_from?(grid, letters, row, col, index, visited) return false if row.negative? || col.negative? || row >= grid.length || col >= grid[row].length key = [row, col] return false if visited[key] return false unless grid[row][col] == letters[index] return true if index == letters.length - 1 visited = visited.merge(key => true) DIRECTIONS.any? do |dr, dc| path_from?(grid, letters, row + dr, col + dc, index + 1, visited) end end
Source
# File lib/boggle_grid.rb, line 36 def roll_grid(rng: nil, rand: nil) rng = coerce_rng(rng, rand) shuffled = DICE.shuffle(random: rng) faces = shuffled.map { |die| die[rng.rand(die.length)] } 4.times.map { |row| faces[(row * 4)...(row * 4 + 4)] } end
Source
# File lib/boggle_grid.rb, line 52 def word_on_grid?(grid, word) letters = word.to_s.strip.downcase.chars return false if letters.empty? grid.each_with_index do |row, r| row.each_with_index do |cell, c| return true if path_from?(grid, letters, r, c, 0, {}) end end false end