//
// Euler problem 17
//
// """
// If the numbers 1 to 5 are written out in words: one, two, three, four, five, 
// then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
// 
// If all the numbers from 1 to 1000 (one thousand) inclusive were written out in 
// words, how many letters would be used?
// 
// NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) 
// contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of 
// "and" when writing out numbers is in compliance with British usage.
// """
// 
//  This SETL program was created by Hakan Kjellerstrand (hakank@bonetmail.com).
//  See also my SETL page: http://www.hakank.org/setl/
//


// This solution was inspired by my Pop-11 program 
//    http://www.hakank.org/poplog/euler17.p


english := procedure(n) {

    // divs      :=  [1.0E9, 1.0E6, 1.0E3, 1.0E2];
    divs      :=  [1000000000, 1000000,  1000,       100];
    divnames  :=  ["billion", "million", "thousand", "hundred"];
    prefixes  :=  ["0", "twen", "thir", "for", "fif", "six", "seven", "eigh", "nine"];
    ordinals  :=  ["first", "second", "third", "fourth", "fifth", "sixth", "seventh",
                   "eighth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth",
                   "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth"];
    cardinals :=  ["one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
                   "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];

    sstr := "";
    printed := false;
    if (n < 0) {
        sstr := "minus" + sstr;
        n := -n;
    }

    for (i in [1..#divs]) {
        d := n \ divs[i];
        n := n % divs[i];
        if (d != 0) {
	    sstr += english(d);
            sstr += divnames[i];
	    printed := true;
        }
    }

    if (n > 0 && printed) {
        sstr := sstr + "and";
    }

    if (n == 0) {
        p := p; // dummy
    } else if (n > 19) {
        d := n \ 10;
        n := n % 10;
        sstr += prefixes[d];
        sstr += "ty";
        sstr += english(n);
    } else {
        sstr += cardinals[n];
    }

    return sstr;

};

problem17 := procedure() {
    print("Problem 17: ");
    total := 0;
    for (i in [1..1000]) {
        sstr := english(i);
        slen := #sstr;
        total += slen;
    }

    print(total);
};

problem17();


