Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop number sequence of (1,1,2,2,3,3, etc.)

I looked it up and this pattern is Hofstadter Female sequence. The equations are:

M(n) = n-F(M(n-1))

F(n) = n-M(F(n-1))

but I'm not sure how to put that into code.

So far I have:

while () {
    _p++
    _r++
    if (_p % 2 === 0) {
        _r = _p - 1;
    }
}

Any help?

like image 674
Tom Avatar asked Dec 15 '22 01:12

Tom


1 Answers

Without memoization:

function F(n)
{
    return 0 < n ? n - M(F(n-1)) : 1
}

function M(n)
{
    return 0 < n ? n - F(M(n-1)) : 0
}

var N = 10;
var f = [];
var m = [];
for (var i = 0; i <= N; ++i) {
    f.push(F(i));
    m.push(M(i));
}

console.log('F: ' + f.join(','))
console.log('M: ' + m.join(','))

Output:

F: 1,1,2,2,3,3,4,5,5,6,6
M: 0,0,1,2,2,3,4,4,5,6,6

http://jsfiddle.net/KtGBg/1/

like image 115
Matt Avatar answered Dec 31 '22 17:12

Matt