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

Incorporating Button Value from Anchor Tag Title Upon Page Load

Currently, I am working on a real estate project and facing an issue with a contact modal box. My goal is to extract the title from tag "a" and place it as the button value in the modal box. English isn't my strong suit, so please excuse any errors i ...

Adding information to an Excel spreadsheet using JavaScript

I'm facing a challenge in appending data to an existing Excel file using node.js. I've tried using the xlsx-writestream package with the code snippet below: var XLSXWriter = require('xlsx-writestream'); var writer = new XLSXWriter(&a ...

Obtain the ending section of a URL using JavaScript

Is it possible to extract the username from a URL like this example? I'm interested in seeing a regex method for achieving this. The existing code snippet only retrieves the domain name: var url = $(location).attr('href'); alert(get_doma ...

Developing a multi-graph by utilizing several JSON array datasets

Currently exploring D3 and experimenting with creating a multi-line graph without utilizing CSV, TSV, or similar data formats. The key focus is on iterating over an array of datasets (which are arrays of objects {data:blah, price:bleh}). I am trying to a ...

Initiate the python script on the client's end

Currently, I am in the process of initiating a Python script designed to parse a CSV file that has been uploaded by the user through the UI. On the client side, how can I effectively trigger the Python script (I have explored using AJAX HTTP requests)? Add ...

How to switch images with a click using AngularJS

When I try to toggle an image on click, I am facing an issue where clicking on one element also changes the image for another element. I'm struggling to find a solution for this situation. Here is my HTML code: <div id="TestContainer" class="Test ...

Saving the Chosen Option from Button Group into react-hook-form State

Struggling to save the chosen value from MUI Button Group into react-hook-form's state, but encountering challenges with the update not happening correctly. view codesandbox example Below is a simplified version of my code: import { ButtonGroup, But ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

Enhance the standard input control in Vue.js by extending it to include features such as

Incorporating vue.js: Can you enhance a standard HTML input without the need for a wrapper element? I am interested in customizing a textarea like so: Vue.component('custom-textarea', { data () => { return { } }, template: &apo ...

Error: 'fs' module not found in React.js and cannot be resolved

Encountering issues with tatum io v1 + react? Developers have acknowledged that it's a react problem which will be addressed in V2. In the meantime, you can utilize tatum io V1 with node js. I've included all dependencies that could potentially ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

Managing Image Quality with Unsplash API

How can we ensure high quality images are embedded on the web using Unsplash API or other methods? The image displayed in the example below appears blurry and unclear compared to the original image. Original Image link: Example of embedding the image abo ...

Revise shiny datatable to display total column sum differently

This is a follow up question to this inquiry: Adding Total/Subtotal to the bottom of a DataTable in Shiny. Below is the code snippet referenced: library(shiny) library(DT) ui <- shinyUI(fluidPage( h1('Testing TableTools'), mainPanel( ...

What is the method for transforming latitude and longitude coordinates into a physical address for a website?

I'm working with an API that provides latitude and longitude coordinates, and I need to retrieve the address information (city, area, etc.) based on these values. For example, there is a website like where if we enter the IP address of a location, i ...

Attempting to retrieve currentScript is causing a typeError to be thrown

I'm attempting to access a custom attribute that I added to my script tag: <script type="text/javascript" src="https://.../mysource.js" customdata="some_value"></script> To make this work on Internet Explorer ...

Determine whether the click occurs inside or outside of a bar on a ChartJS graph

I'm currently working with a bar graph using chartJS. I'm trying to figure out how to detect where the user clicked - whether it was inside or outside of the bar region in chartJS. const waterFChart = new Chart(canvasRef.current, { plugins: [ ...

Using Redis for caching in Node.js applications

As I delved into this module, I found myself pondering the use of callbacks within it. My understanding is that memory caching is designed to be speedy, providing instant results. So why introduce callbacks, which may imply a waiting period? If the resul ...

Angular Partial Submit/Procession

I have more experience with JSF than Angular or jQuery. I am interested in learning about partial submit and processing in web development. Is there an easy way to achieve this? Specifically, I would like to understand how to implement partial page process ...

Express.js - What is the method to determine the total number of routes set up in my application?

Is there a way to calculate the total number of routes set up in Express.js without manually counting them? I have defined routes throughout my application and they are not grouped together, so I can't use a counter inside each one. I've searche ...

Managing nested levels in Vue Draggable

Here is a link to the code sandbox: Nested Draggable Code Sandbox The nesting in this code is controlled through directives, specifically using v-if: <template> <draggable class="dragArea" tag="ul" :list="tasks" :g ...