MojoでProject Euler 42

https://projecteuler.net/problem=42

String.splitあるんですね。前からありましたかね。

import sys

#################### library ####################


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

fn get_words(data: String) raises -> List[String]:
    var v = data.split(",")
    for s in v:
        s[] = s[].replace('"', "")
    return v

fn to_Int(word: String) -> Int:
    var sc = 0
    for c in word.as_bytes():
        sc += int(c[] - ord("A") + 1)
    return sc

fn int_sqrt(n: Int) -> Int:
    var x = 1
    x = (x + n // x) // 2
    while True:
        var x1 = (x + n // x) // 2
        if x1 >= x:
            return x
        x = x1

fn is_triangle(n: Int) -> Bool:
    # n = x(x + 1) / 2
    # x^2 + x - 2n = 0
    # x = (-1 + sqrt(1 + 8n)) / 2
    var x = (-1 + int_sqrt(1 + 8 * n)) // 2
    return x * (x + 1) // 2 == n

fn f(path: String) -> Int:
    var counter = 0
    try:
        with open(path, "r") as f:
            var data = f.read()
            var words = get_words(data)
            for word in words:
                var value = to_Int(word[])
                if is_triangle(value):
                    counter += 1
    except:
        return 0
    
    return counter

fn main():
    print(f("0042_words.txt"))