Task: Four is the number of letters in the ...


C++: #include <cctype>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

struct number_names {
    const char* cardinal;
    const char* ordinal;
};

const number_names small[] = {
    { "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
    { "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
    { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
    { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
    { "twelve", "twelfth" }, { "thirteen", "thirteenth" },
    { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
    { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
    { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};

const number_names tens[] = {
    { "twenty", "twentieth" }, { "thirty", "thirtieth" },
    { "forty", "fortieth" }, { "fifty", "fiftieth" },
    { "sixty", "sixtieth" }, { "seventy", "seventieth" },
    { "eighty", "eightieth" }, { "ninety", "ninetieth" }
};

struct named_number {
    const char* cardinal;
    const char* ordinal;
    uint64_t number;
};

const named_number named_numbers[] = {
    { "hundred", "hundredth", 100 },
    { "thousand", "thousandth", 1000 },
    { "million", "millionth", 1000000 },
    { "billion", "biliionth", 1000000000 },
    { "trillion", "trillionth", 1000000000000 },
    { "quadrillion", "quadrillionth", 1000000000000000ULL },
    { "quintillion", "quintillionth", 1000000000000000000ULL }
};

const char* get_name(const number_names& n, bool ordinal) {
    return ordinal ? n.ordinal : n.cardinal;
}

const char* get_name(const named_number& n, bool ordinal) {
    return ordinal ? n.ordinal : n.cardinal;
}

const named_number& get_named_number(uint64_t n) {
    constexpr size_t names_len = std::size(named_numbers);
    for (size_t i = 0; i + 1 < names_len; ++i) {
        if (n < named_numbers[i + 1].number)
            return named_numbers[i];
    }
    return named_numbers[names_len - 1];
}

size_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {
    size_t count = 0;
    if (n < 20) {
        result.push_back(get_name(small[n], ordinal));
        count = 1;
    }
    else if (n < 100) {
        if (n % 10 == 0) {
            result.push_back(get_name(tens[n/10 - 2], ordinal));
        } else {
            std::string name(get_name(tens[n/10 - 2], false));
            name += "-";
            name += get_name(small[n % 10], ordinal);
            result.push_back(name);
        }
        count = 1;
    } else {
        const named_number& num = get_named_number(n);
        uint64_t p = num.number;
        count += append_number_name(result, n/p, false);
        if (n % p == 0) {
            result.push_back(get_name(num, ordinal));
            ++count;
        } else {
            result.push_back(get_name(num, false));
            ++count;
            count += append_number_name(result, n % p, ordinal);
        }
    }
    return count;
}

size_t count_letters(const std::string& str) {
    size_t letters = 0;
    for (size_t i = 0, n = str.size(); i < n; ++i) {
        if (isalpha(static_cast<unsigned char>(str[i])))
            ++letters;
    }
    return letters;
}

std::vector<std::string> sentence(size_t count) {
    static const char* words[] = {
        "Four", "is", "the", "number", "of", "letters", "in", "the",
        "first", "word", "of", "this", "sentence,"
    };
    std::vector<std::string> result;
    result.reserve(count + 10);
    size_t n = std::size(words);
    for (size_t i = 0; i < n && i < count; ++i) {
        result.push_back(words[i]);
    }
    for (size_t i = 1; count > n; ++i) {
        n += append_number_name(result, count_letters(result[i]), false);
        result.push_back("in");
        result.push_back("the");
        n += 2;
        n += append_number_name(result, i + 1, true);
        result.back() += ',';
    }
    return result;
}

size_t sentence_length(const std::vector<std::string>& words) {
    size_t n = words.size();
    if (n == 0)
        return 0;
    size_t length = n - 1;
    for (size_t i = 0; i < n; ++i)
        length += words[i].size();
    return length;
}

int main() {
    std::cout.imbue(std::locale(""));
    size_t n = 201;
    auto result = sentence(n);
    std::cout << "Number of letters in first " << n << " words in the sequence:\n";
    for (size_t i = 0; i < n; ++i) {
        if (i != 0)
            std::cout << (i % 25 == 0 ? '\n' : ' ');
        std::cout << std::setw(2) << count_letters(result[i]);
    }
    std::cout << '\n';
    std::cout << "Sentence length: " << sentence_length(result) << '\n';
    for (n = 1000; n <= 10000000; n *= 10) {
        result = sentence(n);
        const std::string& word = result[n - 1];
        std::cout << "The " << n << "th word is '" << word << "' and has "
            << count_letters(word) << " letters. ";
        std::cout << "Sentence length: " << sentence_length(result) << '\n';
    }
    return 0;
}




Java: import java.util.HashMap;
import java.util.Map;

public class FourIsTheNumberOfLetters {

    public static void main(String[] args) {
        String [] words = neverEndingSentence(201);
        System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1);
        for ( int i = 0 ; i < words.length ; i++ ) {
            System.out.printf("%2d ", numberOfLetters(words[i]));
            if ( (i+1) % 25 == 0 ) {
                System.out.printf("%n%3d: ", i+2);
            }
        }
        System.out.printf("%nTotal number of characters in the sentence is %d%n", characterCount(words));
        for ( int i = 3 ; i <= 7 ; i++ ) {
            int index = (int) Math.pow(10, i);
            words = neverEndingSentence(index);
            String last = words[words.length-1].replace(",", "");
            System.out.printf("Number of letters of the %s word is %d. The word is \"%s\".  The sentence length is %,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words));
        }
    }
    
    @SuppressWarnings("unused")
    private static void displaySentence(String[] words, int lineLength) {
        int currentLength = 0;
        for ( String word : words ) {
            if ( word.length() + currentLength > lineLength ) {
                String first = word.substring(0, lineLength-currentLength);
                String second = word.substring(lineLength-currentLength);
                System.out.println(first);
                System.out.print(second);
                currentLength = second.length();
            }
            else {
                System.out.print(word);
                currentLength += word.length();
            }
            if ( currentLength == lineLength ) {
                System.out.println();
                currentLength = 0;
            }
            System.out.print(" ");
            currentLength++;
            if ( currentLength == lineLength ) {
                System.out.println();
                currentLength = 0;
            }
        }
        System.out.println();
    }
    
    private static int numberOfLetters(String word) {
        return word.replace(",","").replace("-","").length();
    }
    
    private static long characterCount(String[] words) {
        int characterCount = 0;
        for ( int i = 0 ; i < words.length ; i++ ) {
            characterCount += words[i].length() + 1;
        }        
        
        characterCount--;
        return characterCount;
    }
    
    private static String[] startSentence = new String[] {"Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,"};
    
    private static String[] neverEndingSentence(int wordCount) {
        String[] words = new String[wordCount];
        int index;
        for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {
            words[index] = startSentence[index];
        }
        int sentencePosition = 1;
        while ( index < wordCount ) {
            
            
            sentencePosition++;
            String word = words[sentencePosition-1];
            for ( String wordLoop : numToString(numberOfLetters(word)).split(" ") ) {
                words[index] = wordLoop;
                index++;
                if ( index == wordCount ) {
                    break;
                }
            }
            
            words[index] = "in";
            index++;
            if ( index == wordCount ) {
                break;
            }
            
            words[index] = "the";
            index++;
            if ( index == wordCount ) {
                break;
            }
            
            for ( String wordLoop : (toOrdinal(sentencePosition) + ",").split(" ") ) {
                words[index] = wordLoop;
                index++;
                if ( index == wordCount ) {
                    break;
                }
            }
        }
        return words;
    }
    
    private static final String[] nums = new String[] {
            "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", 
            "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
    };
    
    private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

    private static final String numToString(long n) {
        return numToStringHelper(n);
    }
    
    private static final String numToStringHelper(long n) {
        if ( n < 0 ) {
            return "negative " + numToStringHelper(-n);
        }
        int index = (int) n;
        if ( n <= 19 ) {
            return nums[index];
        }
        if ( n <= 99 ) {
            return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
        }
        String label = null;
        long factor = 0;
        if ( n <= 999 ) {
            label = "hundred";
            factor = 100;
        }
        else if ( n <= 999999) {
            label = "thousand";
            factor = 1000;
        }
        else if ( n <= 999999999) {
            label = "million";
            factor = 1000000;
        }
        else if ( n <= 999999999999L) {
            label = "billion";
            factor = 1000000000;
        }
        else if ( n <= 999999999999999L) {
            label = "trillion";
            factor = 1000000000000L;
        }
        else if ( n <= 999999999999999999L) {
            label = "quadrillion";
            factor = 1000000000000000L;
        }
        else {
            label = "quintillion";
            factor = 1000000000000000000L;
        }
        return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
    }

    private static Map<String,String> ordinalMap = new HashMap<>();
    static {
        ordinalMap.put("one", "first");
        ordinalMap.put("two", "second");
        ordinalMap.put("three", "third");
        ordinalMap.put("five", "fifth");
        ordinalMap.put("eight", "eighth");
        ordinalMap.put("nine", "ninth");
        ordinalMap.put("twelve", "twelfth");
    }
    
    private static String toOrdinal(long n) {
        String spelling = numToString(n);
        String[] split = spelling.split(" ");
        String last = split[split.length - 1];
        String replace = "";
        if ( last.contains("-") ) {
            String[] lastSplit = last.split("-");
            String lastWithDash = lastSplit[1];
            String lastReplace = "";
            if ( ordinalMap.containsKey(lastWithDash) ) {
                lastReplace = ordinalMap.get(lastWithDash);
            }
            else if ( lastWithDash.endsWith("y") ) {
                lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
            }
            else {
                lastReplace = lastWithDash + "th";
            }
            replace = lastSplit[0] + "-" + lastReplace;
        }
        else {
            if ( ordinalMap.containsKey(last) ) {
                replace = ordinalMap.get(last);
            }
            else if ( last.endsWith("y") ) {
                replace = last.substring(0, last.length() - 1) + "ieth";
            }
            else {
                replace = last + "th";
            }
        }
        split[split.length - 1] = replace;
        return String.join(" ", split);
    }
    
}