Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby递归算法问题_Ruby_Algorithm_Recursion - Fatal编程技术网

Ruby递归算法问题

Ruby递归算法问题,ruby,algorithm,recursion,Ruby,Algorithm,Recursion,正在研究算法: Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. Note: A word cannot be split into two lines. The order of words in the sentence must rem

正在研究算法:

Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.

Note:

A word cannot be split into two lines.
The order of words in the sentence must remain unchanged.
Two consecutive words in a line must be separated by a single space.
Total words in the sentence won't exceed 100.
Length of each word is greater than 0 and won't exceed 10.
1 ≤ rows, cols ≤ 20,000.
Example 1:

Input:
rows = 2, cols = 8, sentence = ["hello", "world"]

Output: 
1

Explanation:
hello---
world---

The character '-' signifies an empty space on the screen.
Example 2:

Input:
rows = 3, cols = 6, sentence = ["a", "bcd", "e"]

Output: 
2

Explanation:
a-bcd- 
e-a---
bcd-e-

The character '-' signifies an empty space on the screen.
Example 3:

Input:
rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]

Output: 
1

Explanation:
I-had
apple
pie-I
had--

The character '-' signifies an empty space on the screen.
这是我的密码:

def words_typing(sentence, rows, cols)
   count_words(sentence, rows, cols, cols, 0, 0)
end

def count_words(sentence, rows, cols, remaining_space, row_num, word_idx)
    return 0 if row_num == rows #keep going until out of rows, ends the recursion
    word_idx = 0 if word_idx == sentence.length  #reset the word back to the first

    if remaining_space >= sentence[word_idx].length
        if remaining_space == sentence[word_idx].length
            return 1 + count_words(sentence, rows, cols, remaining_space - sentence[word_idx].length, row_num, word_idx + 1 )
        else #greater than 1
            return 1 + count_words(sentence, rows, cols, remaining_space - sentence[word_idx].length - 1, row_num, word_idx + 1 )
        end
    else #move to a new line, reset remaining space
        return count_words(sentence, rows, cols, cols, row_num+1, word_idx)
    end 
end
代码的工作原理如下。word_idx是句子数组中单词的索引。剩余空间最初是列数。每当有足够的空间放一个单词时,我在同一行上返回1+函数调用,下一个单词和剩余的空间。如果剩余空间>=1+字长,那么我将说明两个连续单词之间有一个空格(这就是为什么我有额外的条件)

如果word_idx的长度超过了句子数组,它会按原样重置回零。递归函数将一直运行,直到row_num现在大于问题中提供给我们的行数


但是,这段代码不起作用。我的输出通常大于正确答案,但从概念上讲,我觉得一切都不错。有人看到我的方法有问题吗?

这是因为你在数单词而不是句子

def words_typing(sentence, rows, cols)
   count_words(sentence, rows, cols, cols, 0, 0, 0)
end

def count_words(sentence, rows, cols, remaining_space, row_num, word_idx, number_of_sentences)
    nos = number_of_sentences
    return nos if row_num == rows #keep going until out of rows, ends the recursion

    if word_idx == sentence.length  #reset the word back to the first
    word_idx = 0 
    nos = number_of_sentences+1
    end
    if remaining_space >= sentence[word_idx].length

        if remaining_space == sentence[word_idx].length

            return count_words(sentence, rows, cols, remaining_space - sentence[word_idx].length, row_num, word_idx + 1, nos )
        else #greater than 1

            return count_words(sentence, rows, cols, remaining_space - sentence[word_idx].length - 1, row_num, word_idx + 1 , nos)
        end
    else #move to a new line, reset remaining space

        return count_words(sentence, rows, cols, cols, row_num+1, word_idx, nos)
    end 
end


rows = 3
 cols = 6
 sentence = ["a", "bcd", "e"]
words_typing(sentence, rows, cols)
rows = 4; cols = 5; sentence = ["I", "had", "apple", "pie"]
words_typing(sentence, rows, cols)
我引入了一个新的变量/参数(最后一个),它保存了句子的数量(从0开始)。当
word\u idx==句子.长度
时,表示新句子适合剩余空间,因此
nos=句子数+1


最后,我们返回nos(句子数)。

由于您的问题已经确定,我想建议另一种编写方法

def sentences_per_page(rows, cols, sentence)
  nbr_sentences = 0
  last_word_index = sentence.size-1
  loopy = sentence.each_with_index.cycle
  word, idx = loopy.next
  rows.times do
    cols_left = cols
    while cols_left >= word.size
      cols_left -= (word.size + 1)
      nbr_sentences += 1 if idx == last_word_index
      word, idx = loopy.next
    end
  end
  nbr_sentences
end

rows = 4
cols = 5
sentence = ["I", "had", "apple", "pie"]
puts                    "    rows      sentences"
(1..12).each { |n| puts "     %d           %d" %
  [n, sentences_per_page(n, cols, sentence)] }
rows      sentences
  1           0
  2           0
  3           1
  4           1
  5           1
  6           2
  7           2
  8           2
  9           3
 10           3
 11           3
 12           4
我用过这个方法。对于上文定义的
句子

loopy = sentence.each_with_index.cycle
  #=> #<Enumerator: #<Enumerator: ["I", "had", "apple", "pie"]:each_with_index>:cycle> 
loopy.first 10
  #=> [["I", 0], ["had", 1], ["apple", 2], ["pie", 3],
  #    ["I", 0], ["had", 1], ["apple", 2], ["pie", 3],
  #    ["I", 0], ["had", 1]]  
loopy=sensume.each_与_index.cycle
#=> # 
第一个10
#=>[[“I”,0],“had”,1],“apple”,2],“pie”,3],
#[“I”,0],“had”,1],“apple”,2],“pie”,3],
#[“I”,0],“had”,1]]

太好了,谢谢。它现在适用于大多数输入。然而,在较大的测试用例中,我得到了一个堆栈太深的错误。我想弄清楚为什么——我只做一次递归调用,这取决于一个单词是否能以正确的方式写下来……那么我的算法在其他地方效率低下吗?@Sunny我想你每个合适的单词做一次递归调用+1。例如#1(rows=3,cols=6,句子=[a,bcd,e])=10次呼叫,例如#2(rows=4,cols=5,句子=[I,had,apple,pie])=11次呼叫。而且Ruby(我不知道Ruby语言的当前状态)对函数不太友好,所以不应该使用太多的递归。您可以尝试提高堆栈级别或使用“尾部调用优化”[您可以打开它](不确定在这种情况下是否有效)。这里有一个很好的链接来解释它