3.6 KiB
3.6 KiB
title, id, challengeType
title | id | challengeType |
---|---|---|
Sailors, coconuts and a monkey problem | 59da22823d04c95919d46269 | 5 |
Description
Instructions
N
sailors.
Note:
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc. can occur in time fitting the story line, so as not to affect the mathematics.
C.f:
- Monkeys and Coconuts - Numberphile (Video) Analytical solution.
- A002021 Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
Tests
tests:
- text: <code>splitCoconuts</code> is a function.
testString: assert(typeof splitCoconuts === 'function', '<code>splitCoconuts</code> is a function.');
- text: <code>splitCoconuts(5)</code> should return 3121.
testString: assert(splitCoconuts(5) === 3121, '<code>splitCoconuts(5)</code> should return 3121.');
- text: <code>splitCoconuts(6)</code> should return 233275.
testString: assert(splitCoconuts(6) === 233275, '<code>splitCoconuts(6)</code> should return 233275.');
- text: <code>splitCoconuts(7)</code> should return 823537.
testString: assert(splitCoconuts(7) === 823537, '<code>splitCoconuts(7)</code> should return 823537.');
Challenge Seed
// noprotect
function splitCoconuts(intSailors) {
// Good luck!
return true;
}
Solution
// noprotect
function splitCoconuts(intSailors) {
let intNuts = intSailors;
let result = splitCoconutsHelper(intNuts, intSailors);
while (!result) {
intNuts += 1;
result = splitCoconutsHelper(intNuts, intSailors);
}
return intNuts;
}
function splitCoconutsHelper(intNuts, intSailors, intDepth) {
const nDepth = intDepth !== undefined ? intDepth : intSailors;
const portion = Math.floor(intNuts / intSailors);
const remain = intNuts % intSailors;
if (portion <= 0 || remain !== (nDepth ? 1 : 0)) {
return null;
}
if (nDepth) {
return splitCoconutsHelper(
intNuts - portion - remain, intSailors, nDepth - 1
);
}
return intNuts;
}