0

I am trying to create a function that gets chest exercises from an array called chest.

This function needs to be able to pick several exercises at random, which I have done using a random pointer. To stop duplicate exercises I compare the chest exercise picked (i.e chest[pointer]) and compare it against all the values in the final array.

If the new exercise is not already in the final array, the newly picked exercise is returned and then pushed onto the final array. If it is already in the final array, the function is called recursively. The idea being that the function will run recursively until it finds a new exercise which has not already been chosen:

Get Chest:

function getChest(arr){
    var pointer = 0;
    //random array pointer
    pointer = Math.round(Math.random() * (chest.length - 1));
    //check for duplicate
    for(var i = 0; i < arr.length - 1; i++){
        if(arr[i].name === chest[pointer].name){
            return getChest(arr);
        } else {
            return chest[pointer];
        }
    }
};

The main function uses this method to select exerises randomly. The final array is called 'day'.:

function chooseExercises(){
    for(i = 0; i <= 5; i++){
        ex = getChest(day);
        day.push(ex);
    }
 }

The problem I am having is that there are still duplicates when I run it. Any idea as to what is going wrong? (I am using angularJS)

1
  • 1
    You should perhaps not go about this using recursion in the first place – pretty sure that simply shuffling the array and then just taking the first x elements out of it will perform better. Commented Jun 22, 2015 at 22:46

1 Answer 1

1

Modify your function to this,

function getChest(arr){
    var pointer = 0;
    //random array pointer
    pointer = Math.round(Math.random() * (chest.length - 1));
    //check for duplicate
    for(var i = 0; i < arr.length; i++){
        if(arr[i].name === chest[pointer].name){
            return getChest(arr);
        } 
    }
    return chest[pointer];
};

Basically, the loop is breaking before the value is checked with its full length.

EDIT: also your loop is running over arr.length-1 times, which actually should be just arr.length.

Sign up to request clarification or add additional context in comments.

2 Comments

i < arr.length - 1 --- this looks like an off-by-one error.
I managed to figure it out shortly after posting! but Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.