Jump to content

Mutual recursion: Difference between revisions

Line 946:
 
=={{header|JavaScript}}==
<lang javascript>function Ff(nnum) {
return n(num === 0) ? 1 : nnum - Mm(Ff(nnum - 1));
{
return n === 0 ? 1 : n - M(F(n - 1));
}
 
function Mm(nnum) {
return n(num === 0) ? 0 : nnum - Ff(Mm(nnum - 1));
{
return n === 0 ? 0 : n - F(M(n - 1));
}
 
//make 20 elements to iterate over
var
//we can't use "new Array(20)" here because Array.prototype.map()
out = {F: [], M: []},
//doesn't run our function on 'undefined' elements
i;
var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
for (i = 0; i < 20; i++)
 
{
//return a new array of the results and join with commas to print
out.F.push(F(i));
console.log(a.map(function (n) { return f(n); }).join(', '));
out.M.push(M(i));
console.log(a.map(function (n) { return m(n); }).join(', '));</lang>
}
print(out.F + "\n" + out.M);</lang>
{{out}}
<pre>1,1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12
0,0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12</pre>
 
ES6 implementation
<lang javascript>
var f = num => (num === 0) ? 1 : num - m(f(num - 1));
var m = num => (num === 0) ? 0 : num - f(m(num - 1));
 
//make 20 elements to iterate over
//we can't use "new Array(20)" here because Array.prototype.map()
//doesn't run our function on 'undefined' elements
var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
 
//return a new array of the results and join with commas to print
console.log(a.map(n => f(n)).join(', '));
console.log(a.map(n => m(n)).join(', '));</lang>
 
=={{header|jq}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.