循环到递归解的转换 [英] Conversion of Looping to Recursive Solution

查看:59
本文介绍了循环到递归解的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Scala中使用嵌套循环编写了方法 pythagoreanTriplets .作为scala中的新手,我正在努力使用递归来做同样的事情,并对返回列表(元组列表)使用惰性评估.任何帮助将不胜感激.

I have written a method pythagoreanTriplets in scala using nested loops. As a newbie in scala, I am struggling with how can we do the same thing using recursion and use Lazy Evaluation for the returning list(List of tuples). Any help will be highly appreciated.

P.S:以下方法运行良好.

P.S: The following method is working perfectly fine.

// This method returns the list of all pythagorean triples whose components are
// at most a given limit. Formula a^2 + b^2 = c^2

def pythagoreanTriplets(limit: Int): List[(Int, Int, Int)] = {
    // triplet: a^2 + b^2 = c^2
    var (a,b,c,m) = (0,0,0,2)
    var triplets:List[(Int, Int, Int)] = List()
    while (c < limit) {
      breakable {
        for (n <- 1 until m) {
          a = m * m - n * n
          b = 2 * m * n
          c = m * m + n * n
          if (c > limit)
            break
          triplets = triplets :+ (a, b, c)
        }
        m += 1
      }
    }// end of while
    triplets
  }

推荐答案

我看不到递归将在哪些方面提供明显优势.

I don't see where recursion would offer significant advantages.

def pythagoreanTriplets(limit: Int): List[(Int, Int, Int)] = 
  for {
    m <- (2 to limit/2).toList
    n <- 1 until m
    c =  m*m + n*n if c <= limit
  } yield (m*m - n*n, 2*m*n, c)

这篇关于循环到递归解的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆