首页 \ 问答 \ 将递归函数的返回值存储在ruby中的变量中(Storing the return value of a recursive function in a variable in ruby)

将递归函数的返回值存储在ruby中的变量中(Storing the return value of a recursive function in a variable in ruby)

我正在研究一个问题,找到一个数组中第一对与特定目标相加的数字。 我必须返回最右边的索引首先出现的那对。 所以说目标是10 ,发现的对是[5,5]在指数1,5[3,7]在指数3,4我必须返回[3,7] 。 我有递归部分工作,问题是它返回一个散列,最左边的索引作为键,而对作为值。 我试图从另一个函数(#sum_pairs)调用这个递归函数,这样我就可以格式化我需要的输出,但是当我这样做并尝试将它存储在变量对中时,它返回的是一个空哈希,甚至虽然它只是在我从控制台调用它时返回完成的哈希。

下面是我的代码:

    $starts = [0]

    def sum_pairs(ints, s)
     pairs = find_pairs(ints,s)
     pairs[pairs.keys.min]
    end

    def find_pairs(ints, s)
     sums = {}

     ints.each_with_index do |n, idx|
       next if idx < $starts.last
       right_idx = completes(ints, idx, n, s)

       if right_idx.nil?
        return sums if idx == (ints.length - 1)
        next
      else
       sums[right_idx] = [n, (s - n)]
       $starts << idx
       sums.merge!(sum_pairs(ints[0...right_idx], s))
       sums
      end
     end
    end

    def completes(ints, idx, n, s )
     ints.each_with_index do |num, index|
      next if index <= idx
      return index if num == s - n
     end
     nil
   end

我知道我可以通过迭代来做到这一点,它可能会更有效或更高效,但我正在尝试使用它来更好地理解递归,谢谢!


I'm working on a problem to find the first pair of numbers in an array that sums to a specific target. I have to return the pair which its rightmost index appears first. So say target is 10 and pairs found are [5,5] at indices 1,5 and [3,7] at indices 3,4 I'd have to return [3,7]. I have the recursive part working, problem is it returns a hash with the leftmost index as key and the pair as value. I'm trying to call this recursive function from another function (#sum_pairs) so that I can then format the output I need, but when I do that and try to store it in the variable pairs all it returns is an empty hash, even though it returns the completed hash when I just call it from the console.

Heres my code:

    $starts = [0]

    def sum_pairs(ints, s)
     pairs = find_pairs(ints,s)
     pairs[pairs.keys.min]
    end

    def find_pairs(ints, s)
     sums = {}

     ints.each_with_index do |n, idx|
       next if idx < $starts.last
       right_idx = completes(ints, idx, n, s)

       if right_idx.nil?
        return sums if idx == (ints.length - 1)
        next
      else
       sums[right_idx] = [n, (s - n)]
       $starts << idx
       sums.merge!(sum_pairs(ints[0...right_idx], s))
       sums
      end
     end
    end

    def completes(ints, idx, n, s )
     ints.each_with_index do |num, index|
      next if index <= idx
      return index if num == s - n
     end
     nil
   end

I know I could do this with iteration an it would probably be more or equally efficient, but I'm trying to use this to better understand recursion, thank you!


原文:https://stackoverflow.com/questions/39419518
更新时间:2023-05-10 16:05

最满意答案

你不明白的是从IIS返回浏览器只能是一个流

在你的情况下,你相信你可以发送两个。

实际发生了什么?

A. 您从网页发回一些数据。

B。 您将从用户返回一些文件以供下载。

C. 流结束和关闭 - 没有任何东西进入浏览器了。 所以页面无法拒绝,并且页面上的数据无法更改,因为您不再向页面发送任何内容。

怎么解决这个问题。

a )您可以创建一个下载文件的处理程序,并且只在页面中提供一个链接,该链接指向下载数据的处理程序。

b )您可以创建一些其他页面,您可以使用您要发送的消息重定向他,并自动使用一些javascript开始下载您的文件。

c )您可以使用ajax下载您的额外数据,并使用javascript来显示任何消息

类似的答案

从服务器下载文件的最佳方法是什么?
通过调用.ashx页面下载文件
在开始下载之前更新页面?


What you do not have understand is that the return from IIS to the browser can be one stream only.

In your case, you believe that you can send two.

What is actually happened?

A. You post back some data from the web page.

B. You return some file for download from the user.

C. There the stream end and close – nothing is going to the browser any more. So there is no way the page to refress, and there is no way the data on the page to change because you send nothing any more to the page.

How to solve this.

a) You can make a handler that download the file and you only give a link in the page, a link to the handler that download the data.

b) you can make some other page that you redirect him with the message that you like to send, and there automatically with some javascript you start downloading your file.

c) you can use ajax to download your extra data, and javascript to show any message

similar answers

What is the best way to download file from server
file download by calling .ashx page
Updating a page before initiating a download?

相关问答

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)