Puzzle 8-10-08 (answer)

bearophile bearophileHUGS at lycos.com
Mon Aug 11 17:02:57 PDT 2008


Koroskin Denis, I have modified your code a little trying to use compile time functions.

But I don't understand why for example getValue() can be a CT function, while DoCheckMen() can't.

/*
The Abbott's Puzzle:

"If 100 bushels of corn were distributed among 100 people in such a
manner that each man received three bushels, each woman two, and each
child half a bushel, how many men, women, and children were there?"
*/

import std.metastrings: Format;

int numChildren(int men, int women) {
    return 100 - men - women;
}

bool isEven(int number) {
    return !(number & 1);
}

int getValue(int men, int women, int children) {
    return 3 * men + 2 * women + children / 2;
}

bool isOverflow(int men, int women = 0) {
    return getValue(men, women, 0) > 100;
}

template DoCheckMen(int men) {
    const DoCheckMen = CheckWomen!(men, 0, 100 - men);
}

template CheckSolution(int men, int women, int children) {
    static if (isEven(children) && getValue(men,women,children) == 100) {
        pragma(msg, Format!("Solution found: %s %s %s", men, women, children));
        const CheckSolution = 1;
    } else
        const CheckSolution = 0;
}

template DoCheckWomen(int men, int women) {
    const DoCheckWomen = CheckSolution!(men, women, numChildren(men, women));
}

template CheckWomen(int men, int first, int last) {
    static if (first == last) {
        const CheckWomen = DoCheckWomen!(men, first);
    } else static if (first < last) {
        // an optimization
        static if (isOverflow(men, first))
           const CheckWomen = 0;
        else
           const CheckWomen = CheckWomen!(men, first, first) + CheckWomen!(men, first+1, last);
    } else
        static assert(false);
}

template CheckMen(int first, int last) {
    static if (first == last) {
        const CheckMen = DoCheckMen!(first);
    } else static if (first < last) {
        // an optimization
        static if (isOverflow(first))
            const CheckMen = 0;
        else
            const CheckMen = CheckMen!(first, first) + CheckMen!(first+1, last);
    } else
        static assert(false);
}

const int numSolutios = CheckMen!(0, 100);

pragma(msg, Format!("Number of solutions: %s\n", numSolutios));

//void main() {}


More information about the Digitalmars-d-learn mailing list