Rosetta Code Popular

ABC Problem

Determine whether a word can be formed from a fixed set of two-letter blocks without reusing a block.

Intermediate View source
Source rosettacode/popular/abc_problem.vibe
# title: ABC Problem
# source: https://rosettacode.org/wiki/ABC_Problem
# category: Rosetta Code Popular
# difficulty: Intermediate
# summary: Determine whether a word can be formed from a fixed set of two-letter blocks without reusing a block.
# tags: popular, search, strings, recursion
# vibe: 0.2

def blocks
  [
    "BO", "XK", "DQ", "CP", "NA",
    "GT", "RE", "TG", "QD", "FS",
    "JW", "HU", "VI", "AN", "OB",
    "ER", "FS", "LY", "PC", "ZM"
  ]
end

def remove_at(values, skip_index)
  out = []
  index = 0

  while index < values.size
    if index != skip_index
      out = out + [values[index]]
    end
    index = index + 1
  end

  out
end

def block_matches?(block, letter)
  block.slice(0) == letter || block.slice(1) == letter
end

def can_make_from?(word, word_index, available_blocks)
  letters = word.upcase.split("")

  if word_index >= letters.size
    return true
  end

  letter = letters[word_index]
  block_index = 0

  while block_index < available_blocks.size
    block = available_blocks[block_index]
    if block_matches?(block, letter)
      if can_make_from?(word, word_index + 1, remove_at(available_blocks, block_index))
        return true
      end
    end
    block_index = block_index + 1
  end

  false
end

def can_make?(word)
  can_make_from?(word, 0, blocks)
end

def run
  {
    a: can_make?("A"),
    bark: can_make?("BARK"),
    book: can_make?("BOOK"),
    treat: can_make?("TREAT"),
    common: can_make?("COMMON"),
    squad: can_make?("SQUAD"),
    confuse: can_make?("CONFUSE")
  }
end
Output
Press run to execute run from this example.
rosetta-code popular search strings recursion browser-runner