在Ruby中创建Word组合工具

时间:2012-02-14 19:44:10

标签: ruby

这是CodeLesson.com上课程的练习:编写一个程序,接受用户的单词列表。这些可以是每行一个或全部在一行上,并以某种方式分隔(可能使用逗号)。然后打印出两个单词的每个组合。例如,如果用户输入book,bus,car,plane,则输出将类似于:

  bookbook bookbus bookcar bookplane busbook busbus buscar busplane   carbook carbus carcar carplane planebook planebus planecar planeplane“

3 个答案:

答案 0 :(得分:1)

如果你想要一个kickstart,那么使用内置的Array#repeated_permutation。为了自己动手,想一想循环数组的方法;在那个循环中,再次循环。

答案 1 :(得分:0)

您需要一种算法来获得“重复排列”。谷歌,你会发现很多页面都有解释和算法。由于这是一项学习任务,我不会提供实际的实现:)但请参见此处:

Permutation with repetition without allocate memory

现在,你说你的想法都没有奏效。也许如果您在问题中添加其中一些内容,您可以获得有关它们无法正常工作以及如何使算法运行的具体提示。

答案 2 :(得分:0)

作为第一个想法,你可以遍历单词数组中的每个元素,然后在循环内循环遍历每个单词:

# Ask the user for a comma-separated input.
input = gets

# Split the input into an array, and map
# each element of the array to the same 
# element, but with surrounding whitespace
# removed.
words = input.split(',').map { |w| w.strip }

# Iterate over each word.
words.each do |w1|
  # For each word, iterate over 
  # all words once again.
  words.each do |w2|
    # Skip the loop if the two
    # words are the same.
    next if w1 == w2
    puts w1 + w2 
  end
end

然而,有一种更简洁的方式说“循环遍历数组,并在每个循环内再次遍历数组”:它被称为重复排列。方法Array#repeated_permutation允许您执行此操作。它将置换的长度作为参数(在我们的例子中,长度为2:我们在数组上迭代一次,然后在每个循环内再次迭代)。这是看起来的样子:

input = gets
words = input.split(',').map { |w| w.strip }
words.repeated_permutation(2) do |w1, w2|
  next if w1 == w2
  puts w1 + w2
end

希望这有帮助。