Last Updated: February 25, 2016
·
692
· adjavaherian

Basic recursion for interviews

Next time someone asks you what recursion is, try this example that I just gleaned from a test subject. This example is in Javascript, so there's not much overhead or noise. Note that .shift may or may not be existent in your language of choice, so don't blow it!

var a = ['cocoa', 'mocha', 'java'];

function findJava(myA){

    if(myA[0] === 'java'){
        alert(myA+'?.. I love java!');
    }else{
        alert(myA[0]);
        myA.shift();
        findJava(myA);
    }
}

findJava(a);

This should help you demonstrate that you know what recursion is and how to effectively implement it. We simply create an array 'a' and a function 'findJava' and pass 'a' to 'findJava(a)' at runtime. Our function uses a basic conditional to test the first element of the array. If the test fails, it shifts off the first element of the array and it recursively passes the rest of the array to itself. Note: Not even Aperture Science would use this in a production environment, but it should suffice as an interview answer. The Enrichment Center once again reminds you that Android Hell is a real place where you will be sent at the first sign of defiance.

Fiddle