MojoでProject Euler 14

https://projecteuler.net/problem=14

メモ化をすれば簡単ですが、グローバルにDynamicVectorを持てますね。

import sys


#################### process ####################

var memo = DynamicVector[Int]()
fn Collatz_length(n: Int) -> Int:
    if n < memo.size and memo[n] != 0:
        return memo[n]
    else:
        let l = Collatz_length(n//2 if n % 2 == 0 else n*3+1) + 1
        if n < memo.size:
            memo[n] = l
        return l

fn f(N: Int) -> Int:
    memo.resize(N, 0)
    memo[1] = 1
    for n in range(2, N):
        memo[n] = Collatz_length(n)
    
    var max_item = (1, 1)
    for n in range(2, N):
        if memo[n] > max_item.get[0, Int]():
            max_item = (memo[n], n)
    return max_item.get[1, Int]()

fn main() raises:
    let args = sys.argv()
    let N = atol(args[1])
    print(f(N))