Puzzle 8-10-08 (answer)
Koroskin Denis
2korden at gmail.com
Mon Aug 11 11:23:47 PDT 2008
On Mon, 11 Aug 2008 21:25:46 +0400, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> "BCS" wrote
>> Reply to wyverex,
>>
>>> 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?"
>>>
>>
>> <M, W, C> = <17,5,78> + i*<-3,5,-2> for i in [0,5]
>>
>>
>
> You missed <20, 0, 80>
>
> Of course, this assumes that it's possible to have 0 women (unlikely :) )
>
> And what's with the non-D code? It should be a requirement that you
> have to
> solve it with D ;)
>
> -Steve
>
>
In D you asked? Here you are: (read from bottom to top)
template doCheckMen(int men)
{
const int doCheckMen = CheckWomen!(men, 0, 100-men);
}
template numChildren(int men, int women)
{
const int numChildren = 100 - men - women;
}
template isEven(int number)
{
const bool isEven = (number & 1) == 0;
}
template getValue(int men, int women, int children)
{
const int getValue = 3 * men + 2 * women + children / 2;
}
template checkSolution(int men, int women, int children)
{
static if ( isEven!(children) && getValue!(men,women,children) == 100)
{
pragma(msg, "Solution found: " ~ itoa!(men) ~ " " ~ itoa!(women) ~
" " ~ itoa!(children));
const int checkSolution = 1;
} else {
const int checkSolution = 0;
}
}
template isOverflow(int men, int women = 0)
{
const int isOverflow = getValue!(men, women, 0) > 100;
}
template doCheckWomen(int men, int women)
{
const int doCheckWomen = checkSolution!(men, women, numChildren!(men,
women));
}
template CheckWomen(int men, int first, int last)
{
static if (first == last) {
const int CheckWomen = doCheckWomen!(men, first);
} else static if (first < last) {
// an optimization
static if (isOverflow!(men, first)) {
const int CheckWomen = 0;
} else {
const int 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 int CheckMen = doCheckMen!(first);
} else static if (first < last) {
// an optimization
static if (isOverflow!(first)) {
const int CheckMen = 0;
} else {
const int CheckMen = CheckMen!(first, first) +
CheckMen!(first+1, last);
}
} else {
static assert(false);
}
}
int solve() {
return CheckMen!(0, 100);
}
void main()
{
const int numSolutios = solve();
pragma(msg, "Number of solutions: " ~ itoa!(numSolutios));
}
More information about the Digitalmars-d-learn
mailing list