recursive algorithm utilizing an array as an argument

Currently, I am in the process of developing a function that extracts chest exercises from an array titled "chest".

This particular function is required to randomly select multiple exercises, achieved by utilizing a random pointer. In order to avoid selecting duplicate exercises, I compare the chosen chest exercise (i.e., chest[pointer]) with all the values within the final array.

If the newly selected exercise is not already present in the final array, it is returned and subsequently added to the final array. However, if the exercise is already part of the final array, a recursive call to the function takes place. The objective here is for the function to repeatedly run recursively until it identifies a new exercise that has yet to be chosen:

Obtain 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 utilizes this approach to randomly pick exercises. The resulting array is identified as 'day':

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

Despite my efforts, I am encountering duplicates when running the solution. Any insights into what may be causing this issue? (Note: I am implementing angularJS)

Answer №1

Revise your function as follows:

function getTreasure(array){
    var index = 0;
    //randomly choose an index in the array
    index = Math.round(Math.random() * (treasureChest.length - 1));
  
    for(var i = 0; i < array.length; i++){
        if(array[i].name === treasureChest[index].name){
            return getTreasure(array);
        } 
    }
    
    return treasureChest[index];
};

In essence, the loop is ending prematurely before verifying the full length of the value.

EDIT: Additionally, your loop is iterating over array.length-1 times when it should actually iterate over array.length.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

Methods for decoding a JSON object and iterating through its contents

After learning how to encode an object on the server side from this post, I am now interested in decoding it on the client side. Following is what I do on the client side: $.ajax({ type: "GET", url: "/cgi-bin/ajax_sort.pl", contentType: "appl ...

Azure-Graph is reporting an error: 'Invalid or missing Access Token.'

In my Node.js project, I effortlessly integrate azure APIs. Logging in: const MsRest = require('ms-rest-azure'); MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId); Creating a resource group: const { ResourceManageme ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

Error encountered while attempting to save user to mongoose due to bcrypt issue

I am currently dedicated to expanding my knowledge in node and react through a tutorial. If you want to check out the repository, here is the link: While making a post request to /api/users/register, I encountered an error that seems to stem from an unde ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

React-router-dom v6 causing MUI Drawer to not render

I have implemented ReactJS and I am working on incorporating a drawer/menu to display different routes on each page. I have set up the routes using react-router-dom@v6 in my index.js file. When I directly enter the URL for a specific page, I can see the co ...

The function ng-click does not successfully uncheck ion-radio

In the process of developing my application using the ionic framework, I encountered a challenge where I needed to deselect an ion-radio button when clicking on an input tag. Despite attempting to achieve this functionality through this ionic play link, I ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

Enhance Your jQuery Skills: Dynamically Apply Classes Based on URL Like a Pro!

Here is an example of HTML code for a progress meter: <div class="col-md-3" style="margin-left: -20px;"> <div class="progress-pos active" id="progess-1"> <div class="progress-pos-inner"> Login </div> </di ...

The functionality of the Toastr "options" seems to be malfunctioning

I am having some trouble with my Toastr notification messages. While the message does display, I seem to be unable to make use of any options that I set. Despite specifying some options, they do not seem to work as intended. $('#editButton').c ...

Display the default child of vue-router 4

Need Assistance with Rendering Default Child View in Vue I am currently facing an issue with rendering the default child view for the Category view. I have come across a similar problem discussed on Stack Overflow, but it seems to be related to VUE2 and o ...

NodeJs and the Power of Event Emitters

As a newcomer to Nodejs, I am diving into learning from various code snippets that I have come across on the internet. My current curiosity lies within a basic question regarding a chat application code snippet. Let's take a look at the code snippet ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...

problem with making ajax requests during the server-side processing of DataTables

Currently tackling server-side processing with datatables, but encountering an ajax error that I'll detail shortly. First things first, here's my code: Table <table id="call_analysis_basic_table" class="display" cellspacing="0" width="100%"& ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

Is it feasible to send props to { children } within a React functional component?

Workaround presented below. I am attempting to send props down to a child component using {children}. The Parent component: const ParentComp = ({ children, propsToSendToChild }) => ( <div>Dynamic component content: {children} &l ...

Developing tabbed sections in XSLT

Utilizing Angular JS within XSLT, I am aiming to develop a tab-based user interface using XML data. The requirement is to generate multiple links and corresponding div elements based on the number of nodes in the XML. To manage the display of these div ele ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...