使用Swift语言编写递归函数以循环遍历Objective C中的Collection对象



我见过有人在努力编写一个有效的递归函数。几乎可以肯定的是,人们在第一次尝试时并没有正确地使用递归函数

这篇文章将帮助开发人员了解编写正确的递归函数实际需要做什么。此外,第一次尝试就要做好

请参阅下面的答案:

一般来说,递归函数的一种思考方式是每次经历三个步骤:

  1. 确定基本情况
    • 这是你知道停止递归的时候
    • 它通常是函数中最简单的输入
  2. 编写一个步骤案例,使您的功能最终终止
    • 还不用担心结果
    • 重点是让你的输入在相关意义上"更小"(一个更小的数字,一个更短的数组等)
  3. 修改步骤案例,以便返回正确的结果
    • 换句话说,执行一个工作单元

以计算数字的位数为例。这可以使用尾递归来完成,尾递归是一种常见的递归。

采用上述配方:

  1. 我们的基本情况是一个个个位数
  2. 我们的step情况需要使用数字较少的数字进行递归;以及
  3. 我们需要确保我们每次都在构建一个数字数组

因此,如果我们在Swift中实现这一点,我们最终会得到一个概念上简单的结果:

extension Int {
    func digitsInBase(base: Int) -> [Int] {
        /*
         * Check for the 'base case', ie the simplest input
         * We can immediately deal with this situation
         */
        if self < base {
            return [self]
        }
        /*
         * Here, we have the 'step case'
         * The idea is to break the problem into small parts, while
         * making sure we get a bit closer to the base case each time
         */
        return (self/base).digitsInBase(base) + [self%base]
    }
    // convenience property for a common base
    var digits: [Int] {
        return self.digitsInBase(10)
    }
}
123.digits // [1, 2, 3]
7.digitsInBase(2) // [1, 1, 1]

在概念上,没有什么比将其扩展到类似循环的东西更困难的了,就像另一个答案一样,但认为所有递归都涉及循环是错误的。

以另一个答案的递归求和序列为例,我们对每个元素进行基本/步骤决策:

  1. 基本情况是可以转换为浮点数的元素
  2. 步骤情况是作为序列的元素;以及
  3. 每次我们都需要将元素本身或元素的递归和添加到结果中

什么是递归函数
递归函数是一个代码块,它一次又一次地调用自己,直到满足中断条件。

递归函数的重要方面:

  1. 循环块(例如,用于循环)
    1.1编写一个循环来迭代最顶层的集合
    1.2如果条件,在此如果条件内,当满足所需条件时中断循环
    1.3调用递归函数以循环通过子集合的else条件
  2. 当break条件不满足时调用自己的递归函数
    2.1编写一个循环来迭代子集合
    2.2如果条件,在此如果条件内,当满足所需条件时,中断循环
    2.3调用self函数以循环通过子集合的else条件

示例代码:

import UIKit
let arr1 = [1,2,3,4,5]
let arr2 = [6,7,8,9,10]
let arr3 = [11,12,13,14,15]
let arr4 = [16,17,18,19,20]
let arr5 = [arr1, arr2, 26, 27]
let arr6 = [arr3, arr4, 28]
let arrMain = [arr5, arr6, 21, 22, 23, 24, 25]
var compareNumber:Int = 5
var foundNumber:Int = 0
func recurringFunc(numbers: NSArray) -> Void {
    for number in numbers{
        "the number is (number)"
        if number is Int{
            if number.isEqual(compareNumber){
                foundNumber = number as Int;
                break
            }
        }
        if number is NSArray{
            "the number is (number)"
            recurringFunc(number as NSArray)
        }
    }
}
for numbers in arrMain{
    numbers
    if  numbers is Int{
        "the number is (numbers)"
        if numbers.isEqual(compareNumber){
            foundNumber = numbers as Int;
            break
        }
    }
    if numbers is NSArray{
        "the number is (numbers)"
        recurringFunc(numbers as NSArray)
   }
}
foundNumber

最新更新