What version of Swift are you using, and what exactly do you mean by 'Xcode
cannot stop’? It seems like you might be using an older version of Swift, and
have hit upon a compiler bug/performance issue that has since been fixed.
This code fails to compile for me in Swift 3.1:
'let dp' should be 'var dp'
With that fixed, the code takes ~10 seconds to compile (which is much longer
than I would expect).
IIRC, the Swift compiler has a hard time with multidimensional arrays (maybe
someone else could enlighten us on why that’s the case). Adapting your code to
use a single array brings down the compile time to something much more
reasonable, although the code becomes somewhat less intuitive:
class Solution {
func rob(nums: [Int]) -> Int {
guard nums.count > 0 else { return 0 }
let stride: Int = 2
var dp: [Int] = Array.init(repeating: 0, count: nums.count * stride)
dp[0] = 0
dp[1] = nums[0]
for i in 1 ..< nums.count {
let base = i * stride
let prevBase = (i - 1) * stride
dp[base] = max(dp[prevBase], dp[prevBase + 1])
dp[base + 1] = dp[prevBase] + nums[i]
}
return 0
}
}
If you’re using an older version of Swift and are in a position to update - I’d
suggest making the change. Otherwise I’d recommend avoiding multidimensional
arrays (if possible).
Greg
> On 5 Jun 2017, at 10:32 pm, Hbucius Smith via swift-users
> <[email protected]> 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
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-users
_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users