[swift-users] Compile time exceeded. Anything wrong?

Jens Persson jens at bitcycle.com
Mon Jun 5 18:02:32 CDT 2017


When compiling that from the command line, I get the following (after about
6 seconds):

test.swift:7:18: error: cannot assign through subscript: 'dp' is a 'let'
constant
        dp[0][0] = 0
        ~~       ^
/.../

After fixing that (changing let dp to var dp), it will compile
successfully, still taking a very long time though. This usually means that
some expression(s) in the code happen to be a bit hard on the type checker
(in its current state).
I tried the latest dev snapshot and it is a bit faster, perhaps 3 s instead
of 6.

Anyway, here is a logically equivalent rewrite which will compile faster:

class Solution {
    func rob(nums: [Int]) -> Int {
        guard nums.count > 0 else { return 0 }
        var dp = Array.init(repeating: Array.init(repeating: 0, count:
nums.count),
                            count: 2)
        dp[0][0] = 0
        dp[0][1] = nums[0]
        for i in 1 ..< nums.count {
          let dp_iMinus1_0 = dp[i - 1][0]
          let dp_iMinus1_1 = dp[i - 1][1]
            dp[i][0] = max(dp_iMinus1_0, dp_iMinus1_1)
            dp[i][1] = dp_iMinus1_0 + nums[i]
        }
        return 0
    }
}





On Mon, Jun 5, 2017 at 2:32 PM, Hbucius Smith via swift-users <
swift-users at swift.org> wrote:

> Hi Swift-Users,
>
>     when I compiled the code, Xcode cannot stop, I do not know why. It is
> very strange. Can anyone help ? Here is the code. I am using Xcode 8.1
>
> class Solution {
>
>     func rob(nums: [Int]) -> Int {
>
>         guard nums.count > 0 else { return 0 }
>
>         let dp = Array.init(repeating: Array.init(repeating: 0, count:
> nums.count),
>
>                             count: 2)
>
>         dp[0][0] = 0
>
>         dp[0][1] = nums[0]
>
>         for i in 1 ..< nums.count {
>
>             dp[i][0] = max(dp[i - 1][0], dp[i - 1][1])
>
>             dp[i][1] = dp[i - 1][0] + nums[i]
>
>         }
>
>         return 0
>
>     }
>
> }
>
>
>
> *best wishes for you *
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170606/0df5b388/attachment.html>


More information about the swift-users mailing list