在 swift 中计算这个的最有效方法(简单数学)

Most effecient way to calculate this in swift (simple math)

问题与计算货币增加有关。

循环 n 次,假设您从 5 万美元开始,您的乘数是 2。类似于 b * 2 + a

这是正确的结果:

,000.00
0,000.00
0,000.00
0,000.00
,450,000.00
,500,000.00
,450,000.00
,400,000.00
,250,000.00

所以要明确一点,问题是关于 swift 的效率,而不仅仅是如何计算这个。是否有任何方便的数据结构可以使它更快?基本上我只是循环遍历多少年 (n) 加 2 (200%) 并递增几个临时变量以跟踪当前和以前的值。感觉必须有更好的方法来处理这个问题。

k base

k * 2 + 0 (previous value) = 0k
0k * 2 + k = 0k
0k * 2 + 0k = 0k
etc.

代码:

let baseAmount = 50000.0
let percentReturn = 200.0
let years = 10

// Calc decimal of percent.
var out: Double = 0.0
var previous: Double = 0.0
let returnPercent = percentReturn * 0.01

// Create tmp array to store values.
var tmpArray = [Double]()

// Loop through years.
for var index = 0; index < years; ++index
{
    if index == 0
    {
        out = baseAmount
        tmpArray.append(baseAmount)
    }
    else if index == 1
    {
        out = (out * returnPercent)
        tmpArray.append(out)
        previous = baseAmount
    }
    else
    {
        let tmp = (tmpArray.last! * returnPercent) + previous
        previous = tmpArray.last!
        tmpArray.append(tmp)
    }
}

println(tmpArray)

这里有一些提高效率的想法:

  • 将您的数组初始化为适当的大小(它不是动态的;它始终是年数)
  • 从 for 循环中删除特殊情况(第 0 年和第 1 年的计算)

代码:

func calculate(baseAmount: Double, percentReturn: Double, years: Int) -> [Double] {

    // I prefer to return an empty array instead of nil
    // so that you don't have to check for nil later
    if years < 1 {
        return [Double]()
    }

    let percentReturnAsDecimal = percentReturn * 0.01

    // You know the size of the array, no need to append
    var result = [Double](count: years, repeatedValue: 0.0)
    result[0] = baseAmount

    // No need to do this in the loop
    if years > 1 {
        result[1] = baseAmount * percentReturnAsDecimal
    }

    // Loop through years 2+
    for year in 2 ..< years {
        let lastYear = result[year - 1]
        let yearBeforeLast = result[year - 2]
        result[year] = (lastYear * percentReturnAsDecimal) + yearBeforeLast
    }

    return result
}

速度方面的效率我发现这是最快的算法实现:

let baseAmount = 50000.0
let returnPercent = 2.0
let years = 10

// you know the size of the array so you don't have to append to it and just use the subscript which is much faster
var array = [Double](count: years, repeatedValue: 0)
var previousValue = 0.0
var currentValue = baseAmount

for i in 0..<years {
    array[i] = currentValue
    let p2 = currentValue
    currentValue = currentValue * returnPercent + previousValue
    previousValue = p2
}

print(array)