Sailors, coconuts and a monkey problem: Difference between revisions

m
(Added Perl example)
 
(36 intermediate revisions by 22 users not shown)
Line 27:
;C.f:
* [https://www.youtube.com/watch?v=U9qU20VmvaU Monkeys and Coconuts - Numberphile] (Video) Analytical solution.
* [http://[oeis.org/:A002021 |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).
<br><br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F monkey_coconuts(sailors = 5)
V nuts = sailors
L
V n0 = nuts
[(Int, Int, Int)] wakes
L(sailor) 0..sailors
V (portion, remainder) = divmod(n0, sailors)
wakes.append((n0, portion, remainder))
I portion <= 0 | remainder != (I sailor != sailors {1} E 0)
nuts++
L.break
n0 = n0 - portion - remainder
L.was_no_break
R (nuts, wakes)
 
L(sailors) [5, 6]
V (nuts, wake_stats) = monkey_coconuts(sailors)
print("\nFor #. sailors the initial nut count is #.".format(sailors, nuts))
print("On each waking, the nut count, portion taken, and monkeys share are:\n "wake_stats.map(ws -> String(ws)).join(",\n "))</syntaxhighlight>
 
{{out}}
<pre>
 
For 5 sailors the initial nut count is 3121
On each waking, the nut count, portion taken, and monkeys share are:
(3121, 624, 1),
(2496, 499, 1),
(1996, 399, 1),
(1596, 319, 1),
(1276, 255, 1),
(1020, 204, 0)
 
For 6 sailors the initial nut count is 233275
On each waking, the nut count, portion taken, and monkeys share are:
(233275, 38879, 1),
(194395, 32399, 1),
(161995, 26999, 1),
(134995, 22499, 1),
(112495, 18749, 1),
(93745, 15624, 1),
(78120, 13020, 0)
</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">loop, 2
{
sailor := A_Index+4
while !result := Coco(sailor, A_Index)
continue
; format output
remain := result["Coconuts"]
output := sailor " Sailors, Number of coconuts = " result["Coconuts"] "`n"
loop % sailor {
x := result["Sailor_" A_Index]
output .= "Monkey gets 1, Sailor# " A_Index " hides (" remain "-1)/" sailor " = " x ", remainder = " (remain -= x+1) "`n"
}
output .= "Remainder = " result["Remaining"] "/" sailor " = " floor(result["Remaining"] / sailor)
MsgBox % output
}
return
 
Coco(sailor, coconut){
result := [], result["Coconuts"] := coconut
loop % sailor {
if (Mod(coconut, sailor) <> 1)
return
result["Sailor_" A_Index] := Floor(coconut/sailor)
coconut -= Floor(coconut/sailor) + 1
}
if Mod(coconut, sailor) || !coconut
return
result["Remaining"] := coconut
return result
}</syntaxhighlight>
{{out}}
<pre>---------------------------
5 Sailors, Number of coconuts = 3121
Monkey gets 1, Sailor# 1 hides (3121-1)/5 = 624, remainder = 2496
Monkey gets 1, Sailor# 2 hides (2496-1)/5 = 499, remainder = 1996
Monkey gets 1, Sailor# 3 hides (1996-1)/5 = 399, remainder = 1596
Monkey gets 1, Sailor# 4 hides (1596-1)/5 = 319, remainder = 1276
Monkey gets 1, Sailor# 5 hides (1276-1)/5 = 255, remainder = 1020
Remainder = 1020/5 = 204
---------------------------
6 Sailors, Number of coconuts = 233275
Monkey gets 1, Sailor# 1 hides (233275-1)/6 = 38879, remainder = 194395
Monkey gets 1, Sailor# 2 hides (194395-1)/6 = 32399, remainder = 161995
Monkey gets 1, Sailor# 3 hides (161995-1)/6 = 26999, remainder = 134995
Monkey gets 1, Sailor# 4 hides (134995-1)/6 = 22499, remainder = 112495
Monkey gets 1, Sailor# 5 hides (112495-1)/6 = 18749, remainder = 93745
Monkey gets 1, Sailor# 6 hides (93745-1)/6 = 15624, remainder = 78120
Remainder = 78120/6 = 13020
---------------------------</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SAILORS_COCONUTS_AND_A_MONKEY_PROBLEM.AWK
# converted from LUA
BEGIN {
for (n=2; n<=9; n++) {
x = 0
while (!valid(n,x)) {
x++
}
printf("%d %d\n",n,x)
}
exit(0)
}
function valid(n,nuts, k) {
k = n
while (k != 0) {
if ((nuts % n) != 1) {
return(0)
}
k--
nuts = nuts - 1 - int(nuts / n)
}
return((nuts != 0) && (nuts % n == 0))
}
</syntaxhighlight>
{{out}}
<pre>
2 11
3 25
4 765
5 3121
6 233275
7 823537
8 117440505
9 387420481
</pre>
 
=={{header|Bc}}==
This script implements a solution in the coconuts function for a number of sailors > 1 and a number of monkeys between 1 and sailors-1. It also executes the coconuts function for some values of sailors/monkeys.
 
<langsyntaxhighlight Bclang="bc">define coconuts(sailors, monkeys) {
print "coconuts(", sailors, ", ", monkeys, ") = "
if (sailors < 2 || monkeys < 1 || sailors <= monkeys) {
Line 55 ⟶ 189:
coconuts(5, 4)
coconuts(6, 1)
coconuts(101, 1)</langsyntaxhighlight>
 
{{out}}
Line 80 ⟶ 214:
This is a translation of the second C solution. The output lists the number of sailors, the size of the original pile, and the final share each sailor receives the following morning.
 
<langsyntaxhighlight lang="befunge">>2+:01p9>`#@_00v
nvg10*g10:+>#1$<
#>\:01g1-%#^_:0v
-|:-1\+1<+/-1g1<
1>$01g.">-",,48v
^g10,+55<.,9.,*<</langsyntaxhighlight>
 
{{out}}
Line 99 ⟶ 233:
=={{header|Bracmat}}==
{{trans|Tcl}} (Though without the <code>assert</code> procedure.)
<langsyntaxhighlight lang="bracmat">( ( divmod
= a b
. !arg:(?a.?b)&(div$(!a.!b).mod$(!a.!b))
Line 154 ⟶ 288:
& minnuts$!n
)
)</langsyntaxhighlight>
 
Output:
Line 176 ⟶ 310:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
int valid(int n, int nuts)
Line 194 ⟶ 328:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>2: 11
Line 208 ⟶ 342:
But it's faster to search backwards: if everyone receives some coconuts,
see if we can backtrack to the original pile:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
// calculates if everyone got some nuts in the end, what was the original pile
Line 230 ⟶ 364:
}
return 0;
}</langsyntaxhighlight>
{{out}}
sailers: original pile, final share
Line 244 ⟶ 378:
</pre>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<syntaxhighlight lang="csharp">class Test
 
<lang C#>class Test
{
static bool valid(int n, int nuts)
Line 272 ⟶ 405:
}
}
}</langsyntaxhighlight>
 
<pre>2: 11
Line 282 ⟶ 415:
8: 117440505
9: 387420481</pre>
 
=={{header|C++}}==
{{trans|C#}}
<syntaxhighlight lang="cpp">#include <iostream>
 
bool valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) {
if (nuts % n != 1) {
return false;
}
}
 
return nuts != 0 && (nuts % n == 0);
}
 
int main() {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x)) {
x++;
}
std::cout << n << ": " << x << std::endl;
}
 
return 0;
}</syntaxhighlight>
{{out}}
<pre>2: 11
3: 25
4: 765
5: 3121
6: 233275
7: 823537
8: 117440505
9: 387420481</pre>
 
=={{header|Clojure}}==
A rather non-Clojure-like solution:
 
<syntaxhighlight lang="clojure">(defn solves-for? [sailors initial-coconut-count]
(with-local-vars [coconuts initial-coconut-count, hidings 0]
(while (and (> @coconuts sailors) (= (mod @coconuts sailors) 1)
(var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors))
(var-set hidings (inc @hidings)))
(and (zero? (mod @coconuts sailors)) (= @hidings sailors))))
 
(doseq [sailors (range 5 7)]
(let [start (first (filter (partial solves-for? sailors) (range)))]
(println (str sailors " sailors start with " start " coconuts:"))
(with-local-vars [coconuts start]
(doseq [sailor (range sailors)]
(let [hidden (/ (dec @coconuts) sailors)]
(var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors))
(println (str "\tSailor " (inc sailor) " hides " hidden " coconuts and gives 1 to the monkey, leaving " @coconuts "."))))
(println
(str "\tIn the morning, each sailor gets another " (/ @coconuts sailors) " coconuts."))
(println "\tThe monkey gets no more.\n"))))
</syntaxhighlight>
 
{{Out}}
<pre>5 sailors start with 3121 coconuts:
Sailor 1 hides 624 coconuts and gives 1 to the monkey, leaving 2496.
Sailor 2 hides 499 coconuts and gives 1 to the monkey, leaving 1996.
Sailor 3 hides 399 coconuts and gives 1 to the monkey, leaving 1596.
Sailor 4 hides 319 coconuts and gives 1 to the monkey, leaving 1276.
Sailor 5 hides 255 coconuts and gives 1 to the monkey, leaving 1020.
In the morning, each sailor gets another 204 coconuts.
The monkey gets no more.
 
6 sailors start with 233275 coconuts:
Sailor 1 hides 38879 coconuts and gives 1 to the monkey, leaving 194395.
Sailor 2 hides 32399 coconuts and gives 1 to the monkey, leaving 161995.
Sailor 3 hides 26999 coconuts and gives 1 to the monkey, leaving 134995.
Sailor 4 hides 22499 coconuts and gives 1 to the monkey, leaving 112495.
Sailor 5 hides 18749 coconuts and gives 1 to the monkey, leaving 93745.
Sailor 6 hides 15624 coconuts and gives 1 to the monkey, leaving 78120.
In the morning, each sailor gets another 13020 coconuts.
The monkey gets no more.</pre>
 
=={{header|D}}==
{{trans|Kotlin}}
<syntaxhighlight lang="d">
<lang D>
import std.stdio;
 
Line 318 ⟶ 529:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 402 ⟶ 613:
{{trans|Ruby}}
===Brute Force===
<langsyntaxhighlight lang="elixir">defmodule RC do
def valid?(sailor, nuts), do: valid?(sailor, nuts, sailor)
Line 420 ⟶ 631:
n - 1 - d
end)
end)</langsyntaxhighlight>
 
{{out}}
Line 443 ⟶ 654:
 
===Faster version===
<langsyntaxhighlight lang="elixir">defmodule Sailor do
def coconuts(sailor), do: coconuts(sailor, sailor)
defp coconuts(sailor, nuts) do
Line 458 ⟶ 669:
Enum.each(2..9, fn sailor ->
IO.puts "#{sailor}: #{Sailor.coconuts(sailor)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 474 ⟶ 685:
=={{header|Forth}}==
{{trans|uBasic/4tH}}
<syntaxhighlight lang="text">: total
over * over 1- rot 0 ?do
over over mod if dup xor swap leave else over over / 1+ rot + swap then
Line 486 ⟶ 697:
;
 
9 sailors</langsyntaxhighlight>
{{out}}
<pre>2: 11 1
Line 496 ⟶ 707:
8: 117440505 5044200
9: 387420481 14913080 ok</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<syntaxhighlight lang="freebasic">
Dim As Integer cocos = 11
 
For ns As Integer = 2 To 9
Dim As Integer oculta(ns)
cocos = Int(cocos / ns) * ns + 1
Do
Dim As Integer nc = cocos
For s As Integer = 1 To ns+1
If nc Mod ns = 1 Then
oculta(s-1) = Int(nc / ns)
nc = nc - (oculta(s-1) + 1)
If s = ns And Not (nc Mod ns) Then
Print ns; " marineros requieren un m¡nimo de"; cocos; " cocos"
For t As Integer = 1 To ns
Print !"\tEl marinero"; t; " se esconde"; oculta(t - 1)
Next t
Print !"\tEl mono obtiene"; ns
Print !"\tFinalmente, cada marinero se lleva"; Int(nc / ns); !"\n"
Exit Do
End If
Else
Exit For
End If
Next s
cocos += ns
Loop
Next ns
Sleep
</syntaxhighlight>
 
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 531 ⟶ 777:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 542 ⟶ 788:
This program works by applying a function to increasing multiples of the number of sailors. The function takes a potential final number of coconuts (at the time the sailors awaken) and works backwards to get to the initial number of coconuts. At every step, it will abort the computation if the current number of coconuts can't arise as a result of splitting the previous pile.
 
<langsyntaxhighlight lang="haskell">import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
 
-- Takes the number of sailors and the final number of coconuts. Returns
Line 550 ⟶ 796:
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where step n
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| n `mod` (s |- otherwise1) == 0 = Just $ n * s `div` (s - =1) + Nothing1
| otherwise = Nothing
 
-- Gets the number of sailors from the first command-line argument and
Line 559 ⟶ 806:
main :: IO ()
main = do
args <- getArgs
let n = case args of
case args [] -> 5of
s:_[] -> read s5
a = heads:_ .-> mapMayberead (tryFor n) $ [n, 2 * n ..]s
a = head . mapMaybe (tryFor n) $ [n,2 * n ..]
print a</lang>
print a</syntaxhighlight>
 
Examples:
<pre>
Line 580 ⟶ 827:
Here, we assume an answer which is less than 10000, and try each possibility, constraining ourselves to the list of answers which are valid. (As it happens, there's only one of those.)
 
<langsyntaxhighlight Jlang="j"> I.(=<.)%&5 verb def'4*(y-1)%5'^:5 i.10000
3121</langsyntaxhighlight>
 
These sailors must count coconuts extremely quickly.
Line 587 ⟶ 834:
When we do this with six sailors, it turns out that we have to assume a larger initial value:
 
<langsyntaxhighlight Jlang="j"> I.(=<.)%&6 verb def'5*(y-1)%6'^:6 i.1000000
233275 513211 793147</langsyntaxhighlight>
 
If it were not obvious which of the answers here was the minimum value we could additionally pick the smallest value from the list. But that would require typing two extra characters (for example, replace I. with i.&1), and most people already have so much trouble reading J that the extra code would surely be too much.
Line 594 ⟶ 841:
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">public class Test {
 
static boolean valid(int n, int nuts) {
Line 611 ⟶ 858:
}
}
}</langsyntaxhighlight>
<pre>2: 11
3: 25
Line 628 ⟶ 875:
( As in the recursive Python example )
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// wakeSplit :: Int -> Int -> Int -> Int
Line 650 ⟶ 897:
return intNuts;
});
})();</langsyntaxhighlight>
 
{{out}}
 
<syntaxhighlight lang JavaScript="javascript">[3121, 233275, 823537]</langsyntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
 
"use strict";
Adding just a touch of curry to the coconuts.
(See the Rosetta Code task: [[Currying]])
 
<lang JavaScript>(() => {
 
// wakeSplit :: Int -> Int -> Int -> Int
letconst wakeSplit = (intSailors, intNuts, intDepth) => {
let nDepth =(intNuts, intDepth) !==> undefined ? intDepth : intSailors,{
portion = Math.floor(intNuts / intSailors),const
remain nDepth = intDepth !== intNutsundefined %? intSailors;(
intDepth
) : intSailors,
portion = Math.floor(intNuts / intSailors),
remain = intNuts % intSailors;
 
return 0 >= portion || remain !== (nDepth ? 1 : 0) ?
null : nDepth ? wakeSplit(
intSailors, intNuts - portion - remain, nDepth - 1
) : 0
) ? (
null
) : nDepth ? (
wakeSplit(
intSailors
)(
intNuts - portion - remain,
nDepth - 1
)
) : intNuts;
};
 
// ---------------------- TEST -----------------------
const main = () =>
// TEST for 5, 6, and 7 Sailors
[5, 6, 7].map(intSailors => {
const intNuts = intSailors;
 
return until(
//GENERIC FUNCTIONS
wakeSplit(intNuts)
)(x => 1 + x)(intNuts);
});
 
// curry :: ((a, b) -> c) -> a -> b -> c
let curry = f => a => b => f(a, b),
 
// --------------------- GENERIC ---------------------
// until :: (a -> Bool) -> (a -> a) -> a -> a
 
until = (p, f, x) => {
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p =>
// The value resulting from repeated applications
// of f to the seed value x, terminating when
// that result returns true for the predicate p.
f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
},
 
// succ :: Int ->while Int(!p(v)) {
succ = x => x + 1 v = f(v);
}
 
return v;
};
 
// TESTMAIN for 5, 6, and 7 Sailors---
return [5, 6, 7].mapmain(intSailors => {);
})();</syntaxhighlight>
let intNuts = intSailors,
test = curry(wakeSplit)(intSailors);
 
return until(test, succ, intNuts);
 
});
})();</lang>
 
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[3121, 233275, 823537]</langsyntaxhighlight>
 
=={{header|jq}}==
Line 711 ⟶ 975:
 
If your jq does not have "until" defined, here is its definition:
<langsyntaxhighlight lang="jq">def until(cond; next): def _until: if cond then . else (next|_until) end; _until;</langsyntaxhighlight>
 
===Simulation===
<langsyntaxhighlight lang="jq"># If n (the input) is an admissible number of coconuts with respect to
# the night-time squirreling away of the coconuts by "sailors" sailors, then give 1 to the
# monkey, let one sailor squirrel away (1/sailors) coconuts, and yield the remaining number;
Line 734 ⟶ 998:
 
# Test whether the input is a valid number of coconuts with respect to the story:
def valid(sailors): nighttime(sailors) | morning(sailors);</langsyntaxhighlight>
'''Five sailors''':
Find the minimum number of coconuts if there are 5 sailors --
start at 1 as there must be at least one to give to the monkey during the night:
<langsyntaxhighlight lang="jq">1 | until( valid(5); . + 1)</langsyntaxhighlight>
{{out}}
3121
Line 745 ⟶ 1,009:
Find the minimum number of coconuts if there are 6 sailors --
start at 1 as there must be at least one to give to the monkey during the night:
<langsyntaxhighlight lang="jq">1 | until( valid(6); . + 1)</langsyntaxhighlight>
{{out}}
233275
 
===Working backwards===
<langsyntaxhighlight lang="jq"># If n (the input) is the number of coconuts remaining after
# the surreptitious squirreling away by one sailor,
# then emit the number of coconuts which that sailor originally
Line 772 ⟶ 1,036:
" and each sailor finally ended up with \(.[0])." ;
range(2;9) | solve</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">With 2 sailors, there were originally 3 coconuts, and each sailor finally ended up with 0.
With 3 sailors, there were originally 25 coconuts, and each sailor finally ended up with 2.
With 4 sailors, there were originally 765 coconuts, and each sailor finally ended up with 60.
Line 780 ⟶ 1,044:
With 6 sailors, there were originally 233275 coconuts, and each sailor finally ended up with 13020.
With 7 sailors, there were originally 823537 coconuts, and each sailor finally ended up with 39990.
With 8 sailors, there were originally 117440505 coconuts, and each sailor finally ended up with 5044200.</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|C#}}
<langsyntaxhighlight lang="julia">
function validnutsforsailors(sailors, finalpile)
for i in sailors:-1:1
Line 807 ⟶ 1,071:
 
runsim()
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 822 ⟶ 1,086:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 848 ⟶ 1,112:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 928 ⟶ 1,192:
Finally, each sailor takes 14913080
</pre>
 
=={{header|Lua}}==
{{trans|C}}
<syntaxhighlight lang="lua">function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
 
for n=2, 9 do
local x = 0
while not valid(n, x) do
x = x + 1
end
print(n..": "..x)
end</syntaxhighlight>
{{out}}
<pre>2: 11
3: 25
4: 765
5: 3121
6: 233275
7: 823537
8: 117440505
9: 387420481</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[SequenceOk]
SequenceOk[n_, k_] := Module[{m = n, q, r, valid = True},
Do[
{q, r} = QuotientRemainder[m, k];
If[r != 1,
valid = False;
Break[];
];
m -= q + 1
,
{k}
];
If[Mod[m, k] != 0,
valid = False
];
valid
]
i = 1;
While[! SequenceOk[i, 5], i++]
i
 
i = 1;
While[! SequenceOk[i, 6], i++]
i</syntaxhighlight>
{{out}}
<pre>3121
233275</pre>
 
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Coconuts;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 982 ⟶ 1,308:
 
ReadChar
END Coconuts.</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import strformat
 
var coconuts = 11
 
for ns in 2..9:
var hidden = newSeq[int](ns)
coconuts = (coconuts div ns) * ns + 1
block Search:
while true:
var nc = coconuts
for sailor in 1..ns:
if nc mod ns == 1:
hidden[sailor-1] = nc div ns
dec nc, hidden[sailor-1] + 1
if sailor == ns and nc mod ns == 0:
echo &"{ns} sailors require a minimum of {coconuts} coconuts."
for t in 1..ns:
echo &"\tSailor {t} hides {hidden[t-1]}."
echo &"\tThe monkey gets {ns}."
echo &"\tFinally, each sailor takes {nc div ns}.\n"
break Search # Done. Continue with more sailors or exit.
else:
break # Failed. Continue search with more coconuts.
inc coconuts, ns</syntaxhighlight>
 
{{out}}
<pre>2 sailors require a minimum of 11 coconuts.
Sailor 1 hides 5.
Sailor 2 hides 2.
The monkey gets 2.
Finally, each sailor takes 1.
 
3 sailors require a minimum of 25 coconuts.
Sailor 1 hides 8.
Sailor 2 hides 5.
Sailor 3 hides 3.
The monkey gets 3.
Finally, each sailor takes 2.
 
4 sailors require a minimum of 765 coconuts.
Sailor 1 hides 191.
Sailor 2 hides 143.
Sailor 3 hides 107.
Sailor 4 hides 80.
The monkey gets 4.
Finally, each sailor takes 60.
 
5 sailors require a minimum of 3121 coconuts.
Sailor 1 hides 624.
Sailor 2 hides 499.
Sailor 3 hides 399.
Sailor 4 hides 319.
Sailor 5 hides 255.
The monkey gets 5.
Finally, each sailor takes 204.
 
6 sailors require a minimum of 233275 coconuts.
Sailor 1 hides 38879.
Sailor 2 hides 32399.
Sailor 3 hides 26999.
Sailor 4 hides 22499.
Sailor 5 hides 18749.
Sailor 6 hides 15624.
The monkey gets 6.
Finally, each sailor takes 13020.
 
7 sailors require a minimum of 823537 coconuts.
Sailor 1 hides 117648.
Sailor 2 hides 100841.
Sailor 3 hides 86435.
Sailor 4 hides 74087.
Sailor 5 hides 63503.
Sailor 6 hides 54431.
Sailor 7 hides 46655.
The monkey gets 7.
Finally, each sailor takes 39990.
 
8 sailors require a minimum of 117440505 coconuts.
Sailor 1 hides 14680063.
Sailor 2 hides 12845055.
Sailor 3 hides 11239423.
Sailor 4 hides 9834495.
Sailor 5 hides 8605183.
Sailor 6 hides 7529535.
Sailor 7 hides 6588343.
Sailor 8 hides 5764800.
The monkey gets 8.
Finally, each sailor takes 5044200.
 
9 sailors require a minimum of 387420481 coconuts.
Sailor 1 hides 43046720.
Sailor 2 hides 38263751.
Sailor 3 hides 34012223.
Sailor 4 hides 30233087.
Sailor 5 hides 26873855.
Sailor 6 hides 23887871.
Sailor 7 hides 21233663.
Sailor 8 hides 18874367.
Sailor 9 hides 16777215.
The monkey gets 9.
Finally, each sailor takes 14913080.</pre>
 
=={{header|Objeck}}==
{{trans|C}}
<syntaxhighlight lang="objeck">
class Program {
function : Total(n : Int, nuts : Int) ~ Int {
k := 0;
for(nuts *= n; k < n; k++;) {
if(nuts % (n-1) <> 0) { return 0; };
nuts += nuts / (n-1) + 1;
};
 
return nuts;
}
function : Main(args : String[]) ~ Nil {
for(n := 2; n < 10; n++;) {
x := 0; t := 0;
do {
x++;
t := Total(n, x);
}
while(t = 0);
"{$n}: {$t}, {$x}"->PrintLine();
};
}
}
</syntaxhighlight>
{{out}}
<pre>
2: 11, 1
3: 25, 2
4: 765, 60
5: 3121, 204
6: 233275, 13020
7: 823537, 39990
8: 117440505, 5044200
9: 387420481, 14913080
</pre>
 
=={{header|Perl}}==
Use of <code>bigint</code> required or program silently fails for number of sailors > 13
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="perl">use bigint;
 
for $sailors (1..15) { check( $sailors, coconuts( 0+$sailors ) ) }
 
sub is_valid {
Line 1,023 ⟶ 1,492:
if ($sailors % 2 == 0 ) { ($sailors ** $sailors - 1) * ($sailors - 1) }
else { $sailors ** $sailors - $sailors + 1 }
}</langsyntaxhighlight>
{{out}}
<pre style="height:60ex;overflow:scroll;">
Line 1,205 ⟶ 1,674:
The next morning, each sailor takes 10371206370520814
with none left over for the monkey.</pre>
 
=={{header|Perl 6}}==
{{works with|rakudo|2015.09}}
There is nowhere in the spec where it explicitly states that the sailors cannot equally share zero coconuts in the morning. Actually, The On-Line Encyclopedia of Integer Sequences [http://oeis.org/A002021 A002021] considers the cases for 1 and 2 sailors equally sharing zero coconuts in the morning to be the correct answer.
 
This will test combinations of sailors and coconuts to see if they form a valid pairing. The first 6 are done using brute force, testing every combination until a valid one is found. For cases of 7 to 15 sailors, it uses a carefully crafted filter to drastically reduce the number of trials needed to find a valid case (to one, as it happens... :-) )
 
<lang perl6>my @ones = flat 'th', 'st', 'nd', 'rd', 'th' xx 6;
my @teens = 'th' xx 10;
my @suffix = lazy flat (@ones, @teens, @ones xx 8) xx *;
 
# brute force the first six
for 1 .. 6 -> $sailors { for $sailors .. * -> $coconuts { last if check( $sailors, $coconuts ) } }
 
# finesse 7 through 15
for 7 .. 15 -> $sailors { next if check( $sailors, coconuts( $sailors ) ) }
 
sub is_valid ( $sailors is copy, $nuts is copy ) {
return 0, 0 if $sailors == $nuts == 1;
my @shares;
for ^$sailors {
return () unless $nuts % $sailors == 1;
push @shares, ($nuts - 1) div $sailors;
$nuts -= (1 + $nuts div $sailors);
}
push @shares, $nuts div $sailors;
return @shares if !?($nuts % $sailors);
}
 
sub check ($sailors, $coconuts) {
if my @piles = is_valid($sailors, $coconuts) {
say "\nSailors $sailors: Coconuts $coconuts:";
for ^(@piles - 1) -> $k {
say "{$k+1}@suffix[$k+1] takes @piles[$k], gives 1 to the monkey."
}
say "The next morning, each sailor takes @piles[*-1]\nwith none left over for the monkey.";
return True;
}
False;
}
 
multi sub coconuts ( $sailors where { $sailors % 2 == 0 } ) { ($sailors - 1) * ($sailors ** $sailors - 1) }
multi sub coconuts ( $sailors where { $sailors % 2 == 1 } ) { $sailors ** $sailors - $sailors + 1 }</lang>
{{out}}
<pre>
Sailors 1: Coconuts 1:
1st takes 0, gives 1 to the monkey.
The next morning, each sailor takes 0
with none left over for the monkey.
 
Sailors 2: Coconuts 3:
...
 
Sailors 5: Coconuts 3121:
1st takes 624, gives 1 to the monkey.
2nd takes 499, gives 1 to the monkey.
3rd takes 399, gives 1 to the monkey.
4th takes 319, gives 1 to the monkey.
5th takes 255, gives 1 to the monkey.
The next morning, each sailor takes 204
with none left over for the monkey.
 
Sailors 6: Coconuts 233275:
1st takes 38879, gives 1 to the monkey.
2nd takes 32399, gives 1 to the monkey.
3rd takes 26999, gives 1 to the monkey.
4th takes 22499, gives 1 to the monkey.
5th takes 18749, gives 1 to the monkey.
6th takes 15624, gives 1 to the monkey.
The next morning, each sailor takes 13020
with none left over for the monkey.
 
Sailors 7: Coconuts 823537:
...
 
Sailors 15: Coconuts 437893890380859361:
...
</pre>
 
=={{header|Phix}}==
The morning pile must be a multiple of sailors, so this only tries multiples of sailors! Needed an ugly kludge for solve(1),
the limit of 1 billion suffices for solve(9), above that gets run-time type check errors as capacity of ints are blown anyway.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>procedure solve(integer sailors)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">sailors</span><span style="color: #0000FF;">)</span>
integer m, sm1 = sailors-1
<span style="color: #004080;">integer</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sm1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sailors</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
if sm1=0 then -- edge condition for solve(1) [ avoid /0 ]
<span style="color: #008080;">if</span> <span style="color: #000000;">sm1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- edge condition for solve(1) [ avoid /0 ]</span>
m = sailors
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sailors</span>
else
<span style="color: #008080;">else</span>
for n=sailors to 1_000_000_000 by sailors do -- morning pile divisible by #sailors
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">sailors</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1_000_000_000</span> <span style="color: #008080;">by</span> <span style="color: #000000;">sailors</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- morning pile divisible by #sailors</span>
m = n
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span>
for j=1 to sailors do -- see if all of the sailors could..
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">sailors</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- see if all of the sailors could..</span>
if remainder(m,sm1)!=0 then -- ..have pushed together sm1 piles
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sm1</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- ..have pushed together sm1 piles</span>
m = 0 -- (no: try a higher n)
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- (no: try a higher n)</span>
exit
end if <span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
m = sailors*m/sm1+1 -- add sailor j's stash and one for the monkey
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sailors</span><span style="color: #0000FF;">*</span><span style="color: #000000;">m</span><span style="color: #0000FF;">/</span><span style="color: #000000;">sm1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- add sailor j's stash and one for the monkey</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if m!=0 then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"Solution with %d sailors: %d\n",{sailors,m})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Solution with %d sailors: %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">sailors</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">})</span>
for i=1 to sailors do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">sailors</span> <span style="color: #008080;">do</span>
m -= 1 -- one for the monkey
<span style="color: #000000;">m</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- one for the monkey</span>
m /= sailors
<span style="color: #000000;">m</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">sailors</span>
printf(1,"Sailor #%d takes %d, giving 1 to the monkey and leaving %d\n",{i,m,m*sm1})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sailor #%d takes %d, giving 1 to the monkey and leaving %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">*</span><span style="color: #000000;">sm1</span><span style="color: #0000FF;">})</span>
m *= (sm1)
<span style="color: #000000;">m</span> <span style="color: #0000FF;">*=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">sm1</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"In the morning each sailor gets %d nuts\n",m/sailors)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"In the morning each sailor gets %d nuts\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">/</span><span style="color: #000000;">sailors</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
solve(5)
<span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
solve(6)</lang>
<span style="color: #000000;">solve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,333 ⟶ 1,726:
Sailor #6 takes 15624, giving 1 to the monkey and leaving 78120
In the morning each sailor gets 13020 nuts
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main ?=>
between(2,9,N), % N: number of sailors
once s(N),
fail.
main => true.
 
s(N) =>
next_candidate(N+1,N,C), % C: original number of coconuts
divide(N,N,C,Cr), % Cr: remainder
printf("%d: original = %d, remainder = %d, final share = %d\n",N,C,Cr,Cr div N).
 
next_candidate(From,_Step,X) ?=> X = From.
next_candidate(From,Step,X) => next_candidate(From+Step,Step,X).
 
divide(N,0,C,Cr) => C > 0, C mod N == 0, Cr = C.
divide(N,I,C,Cr) =>
(C-1) mod N == 0,
Q = (C-1) div N,
C1 = Q*(N-1),
divide(N,I-1,C1,Cr).
</syntaxhighlight>
{{out}}
<pre>
2: original = 11, remainder = 2, final share = 1
3: original = 25, remainder = 6, final share = 2
4: original = 765, remainder = 240, final share = 60
5: original = 3121, remainder = 1020, final share = 204
6: original = 233275, remainder = 78120, final share = 13020
7: original = 823537, remainder = 279930, final share = 39990
8: original = 117440505, remainder = 40353600, final share = 5044200
9: original = 387420481, remainder = 134217720, final share = 14913080
</pre>
 
Line 1,338 ⟶ 1,765:
You may want to read [http://paddy3118.blogspot.co.uk/2015/05/solving-monkey-and-coconuts-problem.html Solving the Monkey and coconuts problem] to get more background on the evolution of the Python code.
===Python: Procedural===
<langsyntaxhighlight lang="python">def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
Line 1,359 ⟶ 1,786:
print("\nFor %i sailors the initial nut count is %i" % (sailors, nuts))
print("On each waking, the nut count, portion taken, and monkeys share are:\n ",
',\n '.join(repr(ws) for ws in wake_stats))</langsyntaxhighlight>
 
{{out}}
Line 1,383 ⟶ 1,810:
===Python: Recursive===
 
<langsyntaxhighlight lang="python">def wake_and_split(n0, sailors, depth=None):
if depth is None:
depth = sailors
Line 1,407 ⟶ 1,834:
nuts = monkey_coconuts(sailors)
print("For %i sailors the initial nut count is %i" % (sailors, nuts))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,415 ⟶ 1,842:
===by solving Diophantine equation===
The following is a more or less general solution for arbitrary number of sailors and varying numbers of coconuts the monkey gets. The monkey can be given more coconuts than there are sailors each turn. This is not part of task requirement.
<langsyntaxhighlight lang="python"># gives one solution of (x,y) for a x + by = c
def dioph(a, b, c):
aa,bb,x,y = a, b, 0, 1
Line 1,458 ⟶ 1,885:
 
# many sailors, many nuts
#for i in range(1, 5): print(10**i, calcnuts([1]*10**i + [0])[0])</langsyntaxhighlight>
 
=={{header|R}}==
The only tricky bit is reading comprehension. For example, it's easy to miss that the coconut count after the final nighttime visit must be strictly positive and divisible by the number of sailors.
<syntaxhighlight lang="rsplus">coconutsProblem <- function(sailorCount)
{
stopifnot(sailorCount > 1) #Problem makes no sense otherwise
initalCoconutCount <- sailorCount
repeat
{
initalCoconutCount <- initalCoconutCount + 1
coconutCount <- initalCoconutCount
for(i in seq_len(sailorCount))
{
if(coconutCount %% sailorCount != 1) break
coconutCount <- (coconutCount - 1) * (sailorCount - 1)/sailorCount
if(i == sailorCount && coconutCount > 0 && coconutCount %% sailorCount == 0) return(initalCoconutCount)
}
}
}
print(data.frame("Sailors" = 2:8, "Coconuts" = sapply(2:8, coconutsProblem)))</syntaxhighlight>
{{out}}
<pre> Sailors Coconuts
1 2 11
2 3 25
3 4 765
4 5 3121
5 6 233275
6 7 823537
7 8 117440505</pre>
 
=={{header|Racket}}==
{{trans|Python}}
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (wake-and-split nuts sailors depth wakes)
Line 1,486 ⟶ 1,942:
(printf "For ~a sailors the initial nut count is ~a\n" sailors (first (last wakes)))
(map displayln (reverse wakes))
(newline))</langsyntaxhighlight>
{{out}}
<pre>For 5 sailors the initial nut count is 3121
Line 1,504 ⟶ 1,960:
(93745 15624 1)
(78120 13020 0)</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015.09}}
There is nowhere in the spec where it explicitly states that the sailors cannot equally share zero coconuts in the morning. Actually, The On-Line Encyclopedia of Integer Sequences [http://oeis.org/A002021 A002021] considers the cases for 1 and 2 sailors equally sharing zero coconuts in the morning to be the correct answer.
 
This will test combinations of sailors and coconuts to see if they form a valid pairing. The first 6 are done using brute force, testing every combination until a valid one is found. For cases of 7 to 15 sailors, it uses a carefully crafted filter to drastically reduce the number of trials needed to find a valid case (to one, as it happens... :-) )
 
<syntaxhighlight lang="raku" line>my @ones = flat 'th', 'st', 'nd', 'rd', 'th' xx 6;
my @teens = 'th' xx 10;
my @suffix = lazy flat (@ones, @teens, @ones xx 8) xx *;
 
# brute force the first six
for 1 .. 6 -> $sailors { for $sailors .. * -> $coconuts { last if check( $sailors, $coconuts ) } }
 
# finesse 7 through 15
for 7 .. 15 -> $sailors { next if check( $sailors, coconuts( $sailors ) ) }
 
sub is_valid ( $sailors is copy, $nuts is copy ) {
return 0, 0 if $sailors == $nuts == 1;
my @shares;
for ^$sailors {
return () unless $nuts % $sailors == 1;
push @shares, ($nuts - 1) div $sailors;
$nuts -= (1 + $nuts div $sailors);
}
push @shares, $nuts div $sailors;
return @shares if !?($nuts % $sailors);
}
 
sub check ($sailors, $coconuts) {
if my @piles = is_valid($sailors, $coconuts) {
say "\nSailors $sailors: Coconuts $coconuts:";
for ^(@piles - 1) -> $k {
say "{$k+1}@suffix[$k+1] takes @piles[$k], gives 1 to the monkey."
}
say "The next morning, each sailor takes @piles[*-1]\nwith none left over for the monkey.";
return True;
}
False;
}
 
multi sub coconuts ( $sailors where { $sailors % 2 == 0 } ) { ($sailors - 1) * ($sailors ** $sailors - 1) }
multi sub coconuts ( $sailors where { $sailors % 2 == 1 } ) { $sailors ** $sailors - $sailors + 1 }</syntaxhighlight>
{{out}}
<pre>
Sailors 1: Coconuts 1:
1st takes 0, gives 1 to the monkey.
The next morning, each sailor takes 0
with none left over for the monkey.
 
Sailors 2: Coconuts 3:
...
 
Sailors 5: Coconuts 3121:
1st takes 624, gives 1 to the monkey.
2nd takes 499, gives 1 to the monkey.
3rd takes 399, gives 1 to the monkey.
4th takes 319, gives 1 to the monkey.
5th takes 255, gives 1 to the monkey.
The next morning, each sailor takes 204
with none left over for the monkey.
 
Sailors 6: Coconuts 233275:
1st takes 38879, gives 1 to the monkey.
2nd takes 32399, gives 1 to the monkey.
3rd takes 26999, gives 1 to the monkey.
4th takes 22499, gives 1 to the monkey.
5th takes 18749, gives 1 to the monkey.
6th takes 15624, gives 1 to the monkey.
The next morning, each sailor takes 13020
with none left over for the monkey.
 
Sailors 7: Coconuts 823537:
...
 
Sailors 15: Coconuts 437893890380859361:
...
</pre>
 
=={{header|REXX}}==
===uses a subroutine===
{{trans|C}} {from the 1<sup>st</sup> '''C''' example}<br>
 
<lang rexx>/*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
<syntaxhighlight lang="rexx">/*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
parse arg L H .; if L=='' then L=5 /*L not specified? Then use default.*/
parse arg L H .; if HL=='' then HL=6 5 /*H " " L not "specified? "Then use default.*/
if H=='' then H= 6 /*H " " " " default.*/
/*{Tars is an old name for sailors.} */
do n=L to H /*traipse through a number of sailors. */
do $=0 while \valid(n,$); end do $=0 while \valid(n, $) /*perform while not valid coconuts. */
say 'sailors='n " coconuts="$ end /*display number of sailors & coconuts.$*/
say 'sailors='n " coconuts="$ /*display number of sailors & coconuts.*/
end /*n*/
end /*n*/
exit /*stick a fork in it, we're all done. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
valid: procedure; parse arg n,nuts /*obtain the number sailors & coconuts.*/
do k=n by -1 for n /*step through the possibilities. */
if nuts//n \== 1 then return 0 /*Not one coconut left? No solution. */
nuts=nuts - (1+nuts%n) + nuts % n) /*subtract number of coconuts from pile*/
end /*k*/
return (nuts \== 0) & \(nuts//n \== 0) /*see if number coconuts>0 & remainder.*/</langsyntaxhighlight>
Programming note: &nbsp; The parentheses in the last REXX ('''return''') statement aren't necessary, but help for readability. <br>
 
'''{{out|output''' |text=&nbsp; when using the default inputs:}}
<pre>
sailors=5 coconuts=3121
Line 1,535 ⟶ 2,072:
This REXX version is the same as the above version (but the defaults are different),
<br>and it also eliminates the use of a subroutine, making it faster.
<langsyntaxhighlight lang="rexx">/*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
 
do n=2 to 9 /*traipse through number of sailors. */
do $=0; nuts= $ /*perform while not valid # coconuts. */
do k=n by -1 for n /*step through the possibilities. */
if nuts//n\==1 then iterate $ /*Not one coconut left? No solution.*/
nuts=nuts - (1+nuts%n) - (1 + nuts % n) /*subtract number of coconuts from pile*/
end /*k*/
if (nuts\==0) & \(nuts//n\==0) then leave /*is this a solution to the riddle ? */
end /*$*/
say 'sailors='n " coconuts="$ " coconuts="$ /*display number of sailors & coconuts.*/
end /*n*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the default inputs:}}
<pre>
sailors=2 coconuts=11
Line 1,561 ⟶ 2,098:
===shows the shares===
{{trans|C}} {from the 2<sup>nd</sup> '''C''' example}<br>
 
<lang rexx>/*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
<syntaxhighlight lang="rexx">/*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
parse arg L H .; if L=='' then L=2 /*L not specified? Then use default.*/
parse arg L H .; if HL=='' then HL=9 2 /*H " " " " L not specified? " Then use default.*/
if H=='' then H= 9 /*H " " /*{Tars is an old name for" " " sailors.} */
do n=L to H /*traipse through the number of sailors*/
do $=1 until t\==0; t= total(n, $) /*perform while number coconuts not 0. */
end /*$*/
t=total(n,$) /*perform while not valid coconuts. */
say 'sailors='n " coconuts="t ' share='$
end /*$*/
say 'sailors='n end " coconuts="t ' share='$/*n*/
exit 0 /*stick a fork in it, we're all done. */
end /*n*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
total: procedure; parse arg n,nuts /*obtain the number sailors & coconuts.*/
nuts= nuts * n /*multiple # nuts by number of sailors.*/
nuts=nuts*n
nn= n -1 1 /*NN is used as calculation shortcut. */
do k=0 for n /*step through the possibilities. */
if nuts//nn\==0 then return 0 /*Not one coconut left? No solution. */
nuts=nuts + nuts%nn + 1 + nuts % nn /*bump the number coconuts to the pile.*/
end /*k*/
return nuts /*see if number coconuts>0 & remainder.*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the default inputs:}}
<pre>
sailors=2 coconuts=11 share=1
Line 1,594 ⟶ 2,130:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sailors, coconuts and a monkey problem
 
Line 1,627 ⟶ 2,163:
next
see "In the morning each sailor gets " + m/sailors + " nuts" + nl + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,650 ⟶ 2,186:
=={{header|Ruby}}==
===Brute Force===
<langsyntaxhighlight lang="ruby">def valid?(sailor, nuts)
sailor.times do
return false if (nuts % sailor) != 1
Line 1,667 ⟶ 2,203:
n -= 1 + div
end
end</langsyntaxhighlight>
{{out}}
<pre>5 sailors => 3121 coconuts
Line 1,687 ⟶ 2,223:
===Faster version===
{{works with|Ruby|2.1+}}
<langsyntaxhighlight lang="ruby">def coconuts(sailor)
sailor.step(by:sailor) do |nuts|
flag = sailor.times do
Line 1,699 ⟶ 2,235:
(2..9).each do |sailor|
puts "#{sailor}: #{coconuts(sailor)}"
end</langsyntaxhighlight>
{{out}}
<pre>2: 11
Line 1,710 ⟶ 2,246:
9: 387420481</pre>
===A function to find the solution see [[User_talk:Nigel_Galloway#Inflammatory_stuff]] for a description===
<langsyntaxhighlight lang="ruby">def ng (sailors)
def _ng (sailors, iter, start) #a method that given a possible answer applies the constraints of the tale to see if it is correct
n, g = [start], [start/sailors]
Line 1,727 ⟶ 2,263:
end
 
</syntaxhighlight>
</lang>
===A possible use of the function===
<langsyntaxhighlight lang="ruby">(3..10).each{|sailors| puts "Number of sailors = #{sailors}"; p ng(sailors)}</langsyntaxhighlight>
{{out}}
The output consists of two list. The first is the number of nuts in each pile, the second the number of nuts taken by each dishonest sailor. So in the case of three, start with 25 nuts, the first sailor takes 8 and discards 1 leaving a pile of 16. The second sailor takes 5 and discards 1 leaving 10. The last dishonest sailor takes 3 discards 1 leaving 6 nuts, which can be shared equally between the 3 (2 each).
Line 1,748 ⟶ 2,284:
Number of sailors = 10
[[31381059600, 34867844001, 38742048891, 43046720991, 47829689991, 53144099991, 59048999991, 65609999991, 72899999991, 80999999991, 89999999991], [3138105960, 3486784400, 3874204889, 4304672099, 4782968999, 5314409999, 5904899999, 6560999999, 7289999999, 8099999999, 8999999999]]</pre>
Did someone ask the value for 100 sailors?<langsyntaxhighlight lang="ruby">
n = ng(100)
(0..100).each{|g| puts "#{n[0][100-g]}:#{n[1][100-g]}"}</langsyntaxhighlight>
The number of coconuts requires is as follows, the whole output is at [[Sailors, coconuts and a monkey problem/Ruby output 100]]
<pre>9899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999901</pre>
 
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/jBSqGXg/0 ScalaFiddle (ES aka JavaScript, non JVM, be patient)] or [// https://scastie.scala-lang.org/lZXMc4YBSl2htEBw4D2TUQ Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">object Sailors extends App {
var x = 0
 
Line 1,772 ⟶ 2,309:
}
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Bc}}
<langsyntaxhighlight lang="ruby">func coconuts(sailors, monkeys=1) {
if ((sailors < 2) || (monkeys < 1) || (sailors <= monkeys)) {
return 0
Line 1,791 ⟶ 2,328:
2.to(9).each { |sailor|
say "#{sailor}: #{coconuts(sailor)}";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,808 ⟶ 2,345:
This is a very straightforward implementation. The "overnight" proc attempts to fulfill the activities of the night, throwing an error (through "assert") if it cannot. "minnuts" keeps trying to call it with more nuts until it succeeds. On success, "overnight" will return a list which narrates the night's activities.
 
<langsyntaxhighlight Tcllang="tcl">proc assert {expr {msg ""}} { ;# for "static" assertions that throw nice errors
if {![uplevel 1 [list expr $expr]]} {
if {$msg eq ""} {
Line 1,856 ⟶ 2,393:
puts "Solution with $n sailors:"
minnuts $n
}</langsyntaxhighlight>
 
{{out}}
Line 1,882 ⟶ 2,419:
{{trans|C}}
For performance reasons, we limit ourselves to seven sailors.
<syntaxhighlight lang="text">For n = 2 To 7
t = 0
For x = 1 Step 1 While t = 0
Line 1,907 ⟶ 2,444:
b@ = b@ + 1 + b@ / a@
Next
Return (b@)</langsyntaxhighlight>
{{out}}
<pre>2: 11 1
Line 1,917 ⟶ 2,454:
 
0 OK, 0:127</pre>
 
=={{header|Uiua}}==
 
<syntaxhighlight lang="Uiua">
# Produce candidate list of final numbers
⊚=0◿5⇡2000
# Five times: only keep piles that can be split by 4, do so,
# multiply by five and add one. Return the first value.
⊢⍥(+1×5÷4⊏⊚=0◿4.)5
 
⊚=0◿6⇡100000
⊢⍥(+1×6÷5⊏⊚=0◿5.)6
</syntaxhighlight>
{{out}}
<pre>
3121
233275
</pre>
 
Or for a terse point-free loop through different numbers of sailors:
<syntaxhighlight lang="Uiua">
+2⇡7
≡(
↘1×,⇡10000000
⊟:⊢⍥(+1×+1⟜÷⟜(⊏⊚=0◿)-1:,,),
)
</syntaxhighlight>
{{out}}
<pre>
╭─
╷ 2 11
3 25
4 765
5 3121
6 233275
7 823537
8 117440505
</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Option Explicit
Public Sub coconuts()
Dim sailors As Integer
Dim share As Long
Dim finalshare As Integer
Dim minimum As Long, pile As Long
Dim i As Long, j As Integer
Debug.Print "Sailors", "Pile", "Final share"
For sailors = 2 To 6
i = 1
Do While True
pile = i
For j = 1 To sailors
If (pile - 1) Mod sailors <> 0 Then Exit For
share = (pile - 1) / sailors
pile = pile - share - 1
Next j
If j > sailors Then
If share Mod sailors = 0 And share > 0 Then
minimum = i
finalshare = pile / sailors
Exit Do
End If
End If
i = i + 1
Loop
Debug.Print sailors, minimum, finalshare
Next sailors
End Sub</syntaxhighlight>{{out}}
<pre>Sailors Pile Final share
2 11 1
3 25 2
4 765 60
5 3121 204
6 233275 13020 </pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">var coconuts = 11
for (ns in 2..9) {
var hidden = List.filled(ns, 0)
coconuts = (coconuts/ns).floor * ns + 1
while (true) {
var nc = coconuts
var outer = false
for (s in 1..ns) {
if (nc%ns == 1) {
hidden[s-1] = (nc/ns).floor
nc = nc - hidden[s-1] - 1
if (s == ns && nc%ns == 0) {
System.print("%(ns) sailors require a minimum of %(coconuts) coconuts")
for (t in 1..ns) System.print("\tSailor %(t) hides %(hidden[t-1])")
System.print("\tThe monkey gets %(ns)")
System.print("\tFinally, each sailor takes %((nc/ns).floor)\n")
outer = true
break
}
} else {
break
}
}
if (outer) break
coconuts = coconuts + ns
}
}</syntaxhighlight>
 
{{out}}
<pre>
2 sailors require a minimum of 11 coconuts
Sailor 1 hides 5
Sailor 2 hides 2
The monkey gets 2
Finally, each sailor takes 1
 
3 sailors require a minimum of 25 coconuts
Sailor 1 hides 8
Sailor 2 hides 5
Sailor 3 hides 3
The monkey gets 3
Finally, each sailor takes 2
 
4 sailors require a minimum of 765 coconuts
Sailor 1 hides 191
Sailor 2 hides 143
Sailor 3 hides 107
Sailor 4 hides 80
The monkey gets 4
Finally, each sailor takes 60
 
5 sailors require a minimum of 3121 coconuts
Sailor 1 hides 624
Sailor 2 hides 499
Sailor 3 hides 399
Sailor 4 hides 319
Sailor 5 hides 255
The monkey gets 5
Finally, each sailor takes 204
 
6 sailors require a minimum of 233275 coconuts
Sailor 1 hides 38879
Sailor 2 hides 32399
Sailor 3 hides 26999
Sailor 4 hides 22499
Sailor 5 hides 18749
Sailor 6 hides 15624
The monkey gets 6
Finally, each sailor takes 13020
 
7 sailors require a minimum of 823537 coconuts
Sailor 1 hides 117648
Sailor 2 hides 100841
Sailor 3 hides 86435
Sailor 4 hides 74087
Sailor 5 hides 63503
Sailor 6 hides 54431
Sailor 7 hides 46655
The monkey gets 7
Finally, each sailor takes 39990
 
8 sailors require a minimum of 117440505 coconuts
Sailor 1 hides 14680063
Sailor 2 hides 12845055
Sailor 3 hides 11239423
Sailor 4 hides 9834495
Sailor 5 hides 8605183
Sailor 6 hides 7529535
Sailor 7 hides 6588343
Sailor 8 hides 5764800
The monkey gets 8
Finally, each sailor takes 5044200
 
9 sailors require a minimum of 387420481 coconuts
Sailor 1 hides 43046720
Sailor 2 hides 38263751
Sailor 3 hides 34012223
Sailor 4 hides 30233087
Sailor 5 hides 26873855
Sailor 6 hides 23887871
Sailor 7 hides 21233663
Sailor 8 hides 18874367
Sailor 9 hides 16777215
The monkey gets 9
Finally, each sailor takes 14913080
</pre>
 
=={{header|Yabasic}}==
{{trans|D}}
<syntaxhighlight lang="yabasic">coconuts = 11
 
for ns = 2 to 9
dim hidden(ns)
coconuts = int(coconuts / ns) * ns + 1
do
nc = coconuts
for s = 1 to ns+1
if mod(nc, ns) = 1 then
hidden(s-1) = int(nc / ns)
nc = nc - (hidden(s-1) + 1)
if s = ns and not mod(nc, ns) then
print ns, " sailors require a minimum of ", coconuts, " coconuts"
for t = 1 to ns
print "\tSailor ", t, " hides ", hidden(t - 1)
next
print "\tThe monkey gets ", ns
print "\tFinally, each sailor takes ", int(nc / ns), "\n"
break 2
end if
else
break
end if
next
coconuts = coconuts + ns
loop
next</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn monkey_coconuts(sailors=5){
nuts,wakes:=sailors,List();
while(True){
Line 1,943 ⟶ 2,695:
println("On each waking, the nut count, portion taken, and monkeys share are:\n ",
wake_stats.concat("\n "));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,965 ⟶ 2,717:
</pre>
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn total(n, nuts){
nuts *= n;
foreach k in (n){
Line 1,980 ⟶ 2,732:
break;
}
}</langsyntaxhighlight>
{{out}}
<pre>
67

edits