Update the array by verifying if the ID exists and then randomly modify it

I've been experimenting with various methods for some time now, but I've hit a wall where everything I try seems to go wrong.

Here's what I attempted: Firstly, I generate a random number and add it to an array:

for(.......){
  random[i] = Math.floor(Math.random() * (word.length));

Next, another random number is appended to the array:

randomkey[i] = Math.floor(Math.random() * (word.length));

Following that, I create a function:

var accept=true;
// word is a text (length:22)
function acceptRandom(random,word){
  stop:
    for(var i=0;i<randomkey.length+1; i++){
      if(word[i] != word[random])
        accept = true;
      else {
        accept = false;
        break stop;
      }
    }
    if(accept == false){
      newrandom = Math.floor(Math.random() * (word.length));
      // Random number exists so we call the function again with a new value
      acceptRandom(newrandom,word);
    } else
      return random;
}

The issue now is that it doesn't provide a new value when the random number already exists.

Answer №1

As you iterate through the entire list, inevitably there will always come a point where word[i] == word[random] (since you are comparing the word to itself.) To resolve this issue swiftly, consider implementing the following tweak:

for(var i=0;i<randomkey.length+1; i++){
    if(word[i] == word[random] && i !== random) {
        accept = false;
        break;
    }
}

Furthermore, don't forget to return your recursive call:

if(accept == false){
      newrandom = Math.floor(Math.random() * (word.length));
      // Since a random number exists, we invoke the function again with a new value
      return acceptRandom(newrandom,word);
}

Frankly speaking, it seems like you might have encountered the XY problem. What exactly is your aim here? There's likely a more effective approach available.

Answer №2

Update:

for(.......){
  random[i] = Math.floor(Math.random() * (word.length));
// A random value is being assigned to random[i]

with the change to

for(.......){
  random[i] = words[Math.floor(Math.random() * (word.length))];
// Instead, you should assign words[random number] to random[i]

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

Executing a personalized function within a Server Component with the Next JS App Router while the application is running

In my server component Home, I call the function getMyAge: // app/page.tsx import { getMyAge } from './utils/datetime'; export default function Home() { return ( <Page> <Paragraph>I'm {getMyAge()} years old</Parag ...

JavaScript and jQuery code: Trigger the vjs-fade-out class to toggle when the userActive value in video.js changes

I am currently utilizing video.js to develop a player that is compatible with various devices. One crucial feature I have included is a custom "return to menu" button located in the top right corner of the video player. The challenge I am facing is dynamic ...

Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure: { "a": "b", "c": "d", "e": { "f": "g", "h": "i" } } I want to transform it into the following structure: { "name": "Root", "parent": "null", "children": [ { ...

Showing data in json format using Angular

I have designed a data table that showcases a list of individuals along with their information. However, when I click on the datatable, it keeps opening a chat box displaying the details of the last person clicked, overriding all other chat boxes. 1. Is t ...

Determine the presence of either one or both values in a JavaScript object

I was looking at an Object like this: {"user": { "name": "Harry Peter", "phoneNumber": "12345", "products": [ { "type": "card", "accountId": "5299367", }, { "type": "Loan", ...

`javascript pop up notification will only display one time`

I am currently developing a chrome extension with two different modes. When the user clicks on the icon, a pop-up message should appear to indicate which mode is active. However, I am facing an issue where the message does not always display when the pop- ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

Traversing a 2-dimensional array in a diagonal fashion

I am facing a challenge with iterating through a 2D array of characters. I already have the code set up for iterating, but I'm struggling with ... This is my 2D array: a,v,i,o,n,l t,o,t,o,l,l m,a,r,c,o,e s,a,g,r,c,i o,e,n,z,o,g s,t,r,a,r,u Currentl ...

The integration of query, URL, and body parameters is not working as expected in Seneca when using Seneca

I'm facing some difficulties with Seneca and seneca-web as a beginner. This is the current state of my code: "use strict"; var express = require('express'); var Web = require("seneca-web"); var bodyParser = require('body-parser' ...

Javascript - Editing specific markers with varying titles from the url

My website contains checkboxes in the html code: <input onclick="markAsChanged(this); toggleApproveDeny(this);" name="2c9923914b887d47014c9b30b1bb37a1_approveChk" type="checkbox"> <input onclick="markAsChanged(this); toggleApproveDeny(this);" na ...

Is there a way to collapse child elements in a hover sidebar using Vuetify?

My project includes a sidebar that opens when I hover over it with the mouse. Everything works fine, but within the sidebar, there is a collapse dropdown menu. When I open this menu and then move the mouse away from the sidebar and back again, the collapse ...

Assistance with Validating Forms Using jQuery

I have a form located at the following URL: . For some reason, the form is not functioning properly and I am unsure of the cause. Any suggestions or insights on how to fix it? ...

Dealing with React Native: Navigating App Store Rejections and Embracing IPv6

In my react-native client for a website, the login page offers two options: manually enter the login code or scan it using a barcode scanner. I have extensively tested the app on real devices and emulators, and it's functioning correctly. However, all ...

Alternative method in PSQL for joining to return all rows

I have a PSQL function with 3 joins that return data in a json object. There's a 4th table I need data from, but it has a one-to-many relationship with the table I want to join on. This is my current code: select json_agg(row_to_json(s)) as results f ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

What's the deal with Django and JSON using both single and double quotes?

Observing that when using the simplejson function in Django, all the strings are enclosed in single quotes and the entire JSON object string is enclosed in double quotes. However, when passing this string to JSON.parse, an error occurs because the standard ...

Why is array_udiff() such a useful function in PHP?

I am currently exploring the array_udiff() function and trying to grasp its functionality. However, I find it perplexing that both array_diff() and array_udiff() seem to produce identical results. This leads me to question the necessity of using array_udif ...

What is the best way to dynamically populate a dropdown menu in JavaScript?

I am currently working on populating a dropdown list. Initially, I had manually entered each variable into the array, but now I would like to use a loop to add items to the array dynamically. As a beginner in javascript, any help or pointers would be grea ...

Restricting the amount of text within a span element

Can someone explain how to limit the display of characters in a tag using CSS, similar to the way YouTube truncates titles? I've searched through the styles but couldn't figure it out. Maybe they used JavaScript? Thanks! ...

Ways to avoid executing JavaScript code that is outputted in PHP

My question relates to the code snippet below, which is obtained via the jquery Data object on a php page. echo " var $d = $('<div/>', { id: 'hi' + $('#textResp').children().length, class: 'even ...