You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

值传递/引用传递误解导致all_construct_tabular方法不符合预期?

问题需求与代码问题分析

需求说明

  1. 实现函数all_construct_tabular(target, word_array),返回一个二维数组,包含所有通过拼接word_array中元素构造target字符串的组合方式。
  2. 二维数组的每个子数组代表一种合法的构造组合。
  3. word_array中的元素可以重复使用。

测试用例

it "returns a 2d array with x4 sub array elements" do
  result = all_construct_tabular('abcdef', ['ab', 'abc', 'cd', 'def', 'abcd', 'ef', 'c'])
  expect(result).to eq([['ab', 'cd', 'ef'], ['ab', 'c', 'def'], ['abc', 'def'], ['abcd', 'ef']])
end

初始实现与错误输出

初始代码

def all_construct_tabular(target, word_array)
  table = Array.new(target.length + 1).each.map { Array.new }
  table[0] = [[]]

  table.each_with_index do |e, i|
    word_array.each do |word|
      if target.slice(i, word.length) == word
          new_combos = table[i].map { |a| a << word }
          table[i + word.length].push(new_combos)      
      end
    end
  end
  return table[target.length]
end

错误输出

expected: [["ab", "cd", "ef"], ["ab", "c", "def"], ["abc", "def"], ["abcd", "ef"]]
            got: [[[["ab", "abc", "abcd"], "def"], [[["ab", "abc", "abcd"], "cd", "c"], "def"]], [[["ab", "abc", "abcd"], "ef"], [[["ab", "abc", "abcd"], "cd", "c"], "ef"]]]

问题猜测

我怀疑第8行的a << word操作直接修改了table[i]中的原数组,而非仅生成新的组合数组,同时最终结果存在不必要的多层嵌套问题。

临时可行但冗余的解决方案

通过调试得到一个可行但代码杂乱的版本:

def all_construct_tabular(target, word_array)
  table = Array.new(target.length + 1) { [] }
  table[0] = [[]]

  table.each_with_index do |e, i|
    word_array.each do |word|
      if target.slice(i, word.length) == word
        
        new_combos = table[i].each(&:dup)
        new_combos.map(&:flatten!)
        new_combos_with_word = new_combos.map(&:dup)
        new_combos_with_word.each {|e| e.push(word) }
        table[i + word.length] << new_combos_with_word
      end
    end
  end
  return table[target.length].flatten(1)
end

希望得到针对初始代码的问题分析和简洁的修正指导。


内容的提问来源于stack exchange,提问作者jbk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:45:25