<commit_before>require 'matrix'

class Grid
  def initialize(cells)
    @grid = Matrix[*cells]
  end

  def words
    w = []
    grid.each_with_index do |_, i, j|
      w += f([[i, j]])
    end
    w
  end

  private

  attr_reader :grid

  def f(visited)
    current_cell = visited.last
    neighbours = visitable_neighbours(current_cell, visited)

    [assemble_word(visited)] +
      neighbours.reduce([]) do |words, cell|
        words + f(visited.dup << cell)
      end
  end

  def visitable_neighbours(cell, visited)
    i, j = cell

    neighbours = []

    (i - 1).upto(i + 1) do |i|
      next if i < 0 || grid.row_size == i

      (j - 1).upto(j + 1) do |j|
        next if j < 0 || grid.column_size == j

        cell = [i, j]

        next if visited.include?(cell)

        neighbours << cell
      end
    end

    neighbours
  end

  def assemble_word(visited)
    visited.map { |(i, j)| grid[i, j] }.join
  end
end
<commit_msg>Refactored Grid#visitable_neighbours.<commit_after>require 'matrix'

class Grid
  def initialize(cells)
    @grid = Matrix[*cells]
  end

  def words
    w = []
    grid.each_with_index do |_, i, j|
      w += f([[i, j]])
    end
    w
  end

  private

  attr_reader :grid

  def f(visited)
    current_cell = visited.last
    neighbours = visitable_neighbours(current_cell, visited)

    [assemble_word(visited)] +
      neighbours.reduce([]) do |words, cell|
        words + f(visited.dup << cell)
      end
  end

  def visitable_neighbours(cell, visited)
    i, j = cell

    neighbours = []

    start_i = [0, i - 1].max
    end_i = [grid.row_size - 1, i + 1].min

    start_j = [0, j - 1].max
    end_j = [grid.column_size - 1, j + 1].min

    start_i.upto(end_i) do |i|
      start_j.upto(end_j) do |j|
        cell = [i, j]
        neighbours << cell unless visited.include?(cell)
      end
    end

    neighbours
  end

  def assemble_word(visited)
    visited.map { |(i, j)| grid[i, j] }.join
  end
end

{'fraction_non_alphanumeric': 0.12659520163348648, 'fraction_numerical': 0.0071465033180193975, 'mean_word_length': 2.223684210526316, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6455476', 'n_tokens_mistral': 771, 'n_tokens_neox': 735, 'n_words': 188}