Daniel Kobe
Daniel Kobe

Reputation: 9825

JavaScript recursive function console logging correct answer but returning undefined

I've implemented a recursive function for solving the coin game problem discussed on this geeksforgeeks page. My code seems to work because it logs the right answer from Math.max(coin_l, coin_r) and yet the return value being logged here console.log('input_1 result', maxPoints(input_1)); returns undefined. Not sure what's going on.

Coin Game Code

var maxPoints = function(coins, i, j) {
    if (i === undefined || j === undefined) maxPoints(coins, 0, coins.length - 1);
    if (j === i) return coins[i];
    if (j === i + 1) return Math.max(coins[i], coins[j]);

    var coin_l = coins[i] + Math.min(maxPoints(coins, i + 2, j), maxPoints(coins, i + 1, j - 1));
    var coin_r = coins[j] + Math.min(maxPoints(coins, i + 1, j - 1), maxPoints(coins, i, j - 2));

    console.log(Math.max(coin_l, coin_r));
    return Math.max(coin_l, coin_r);
};

var input_1 = [5, 3, 7, 10];
var input_2 = [8, 15, 3, 7];

var run = function() {
    console.log('input_1 result', maxPoints(input_1));
    console.log('input_2 result', maxPoints(input_2));
};

run();

Upvotes: 2

Views: 196

Answers (1)

BeyelerStudios
BeyelerStudios

Reputation: 4283

your first if statement is missing a return

if (i === undefined || j === undefined) **return** maxPoints(coins, 0, coins.length - 1);

Upvotes: 2

Related Questions