【问题标题】:adjacentElementsProduct function in rubyruby 中的相邻元素产品函数
【发布时间】:2018-07-13 14:04:06
【问题描述】:

我被困在一个名为相邻元素产品的函数的算法上,该函数接受一个数组作为参数。它应该返回数组中相邻数字的最大乘积。例如,如果参数是 [2,4,1,3,2,6],由于 2 和 6 的对,它会返回 12。

我的代码是

def adjacentElementsProduct(inputArray)
    idx1 = 0
    idx2 = 1 

    while idx2 < inputArray.length
        pair = [inputArray[idx1], inputArray[idx1 + 1]]
        next_pair = [inputArray[idx2], inputArray[idx2 + 1]]

        if next_pair.reduce(:+) > pair.reduce(:+)
            pair = next_pair

            idx1 += 1
            idx2 += 1
        else
            idx1 += 1
            idx2 += 1

        end

    end
    pair.reduce(:+)
end

我只是不知道我的代码在哪里不起作用。我只是在寻找正确的方向,因为我知道仅仅给出答案对我没有多大帮助。谁能帮帮我?

【问题讨论】:

    标签: arrays ruby methods


    【解决方案1】:

    代码没有意义:)。 您正在使用 + 而不是 * 在循环中,您总是分配 pair = [inputArray[idx1], inputArray[idx1 + 1]]。 所以你总是返回最后一对或前一对。如果最大乘积在开始,您仍然继续推进 pair 变量直到循环结束。

    此外,解决方案相当复杂。

    def adjacentElementsProduct(inputArray)
      index = 0
      length = inputArray.length
      max = 0
    
      while index < length-1 do
        result = inputArray[index] * inputArray[index+1]
        max = result if result > max
        index += 1
      end
      max
    end
    

    【讨论】:

    • 谢谢,我不知道为什么我从来没想过只创建一个数组长度的变量,而不是每次都写inputArray.length。您的方法比每次使用 reduce 查找产品要简单得多。
    • 此解决方案适用于所有测试,直到它开始对具有最大产品但仍为阴性的阵列进行测试。所以我做了代码max = inputArray[index] * inputArray[index + 1]。所以默认情况下,第一个产品将是数组的前两个元素。
    • 好的。这样更好。
    • do 是否必须在 while 行之后?我没有把它放在这个功能上,它并没有产生技术上的差异。除了写块之外,以后还有更大的用途吗?
    • 执行是可选的。您可以使用“do”换行、“\”或“;”将条件与您将在循环内执行的代码分开。
    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多