Create a randomized string of numbers that includes specific digits while excluding others

I am struggling with generating strings in JavaScript. Specifically, I have an array of numbers from which a string needs to be generated. The string must contain at least 1 number from the array, but must not contain a specific number given by the user. Additionally, the string length must be exactly 7 digits long.

var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user

My current approach involves randomly selecting a number from the array, then choosing a random position in the string, and finally filling in the remaining digits with random numbers. However, I keep encountering issues where the process takes too long or causes my browser to freeze, especially when checking for the excluded number.

//randomly select a number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];

//randomly determine position of the selected number 
var position = Math.floor(Math.random() * 6);

//calculate length of string after the selected number
var afterlen = 7 - (position+2);

//genNum(...) is a function I use to generate a string of numbers with a specific length
var nstr = genNum(position) + getRandom + genNum(afterlen);

while (nstr.includes(exclude)) {
nstr = genNum(position) + getRandom + genNum(afterlen);
}

I am looking for ways to optimize this process and prevent long loading times or browser freezes. Any suggestions on how to improve this would be greatly appreciated.

Update: This task is part of my homework assignment related to generating phone numbers. The final string format should resemble something like "37915002".

Answer №1

Updated my code once again

Is this solution more aligned with your requirements now? The code has become a bit messy and I'm not entirely confident if it's accurate (I never am.. xD) but hopefully, it sparks some ideas for you.

// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";

// Generate a filtered final array
var finalList = initialList.filter(element => {
  let shouldBeIncluded = true;
  excludeList.forEach(excluder => {
    Array.from(excluder).forEach(excluderFragment => {
      if (element.includes(excluderFragment)) shouldBeIncluded = false;
    });
  });
  if (shouldBeIncluded) return true;
});

// Handle case where all elements are excluded
if (finalList.length == 0) {
  // Implement error handling here
} else {
  // Form the final list
  for (let i = 0; i < resultLength; i++) {
    finalString += finalList[Math.floor(Math.random() * finalList.length)];
  }
  // Trim the list due to multiple digit values
  finalString = finalString.slice(0, 7);
  console.log(finalString);
}

Answer №2

To begin, you can remove the unwanted number from the incNumber array and proceed with the same process on the new array.

var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";

var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];

If we consider exclude to be an array of values instead of a single value, the formula would be adjusted as follows:

var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];

var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];

It has been mentioned that the random variable might become undefined if all numbers in incNumber are excluded. In such a scenario, it is advisable to include an additional check to prevent this:

if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

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

Struggling to display the preloader animation while waiting for the render.com server to start up (using the free tier web service)

My choice for deploying dynamic websites is render.com and I am currently using their free tier. The issue with this free service is that Render spins down the web service after 15 minutes of inactivity, resulting in a delay when it needs to spin back up u ...

Once the Angular project has been initialized, the Button disable attribute cannot be modified

In my Ionic-Angular project, I am creating registration pages where users input their information in multiple steps. For each step, there is a button that remains disabled until the correct information is entered. An issue arises when transitioning to the ...

Concerns with the window's onload function

window.onload = prepareButton; function prepareButton() { document.getElementById('slist').onclick = function() { window.location = "students"; } } Whenever I click on a slist element, which is actually a <p> tag formatt ...

Adding a class using jQuery based on whether a section is visible or hidden on the screen

Seeking advice on the best approach to take. Division 1 or section - Apply style 1 if division 1 is currently visible on the screen. Division 2 or section - Apply style 1 if division 2 is currently visible on the screen. Division 3 or section - Apply st ...

Upon triggering a GET request to the URL "http://localhost:3000/search", a "404 (Not Found)" error response was received. Interestingly

Can Someone assist me please? I'm having trouble creating a website similar to YouTube and encountering the following error: GET http://localhost:3000/search 404 (Not Found) Uncaught (in promise) Error: Request failed with status code 404 at createEr ...

Issue encountered when setting up Webpack development server resulted in the failure to generate

Is anyone else experiencing difficulties when trying to create a static folder named "dist"? Package.json "scripts": { "start": "webpack-dev-server --open", "dev": "webpack --mode development --watch ./frontend/src/index.js --output ./frontend/static/fr ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

Setting the value for a HiddenField using jQuery in an ASP.NET application

Is there a way to set a value for a HiddenField control using jQuery? function DisplayContent(obj) { var FareValue = $(obj).closest('tr').find("[id*=lbFare]").text(); $(obj).parent().parent().find('[id*=pnlGrd]').show(); $ ...

Prevent regex from matching leading and trailing white spaces when validating email addresses with JavaScript

In my current setup, I utilize the following regular expression for email validation: /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/ My attempt to validate the email is shown below: if (!event.target.value.match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\. ...

Transition from FadeOut to loading content and displaying it

Is there a way to simply display the content after loading without using fadeIn? $(function() { $('.hovers').click(function(event) { var target = $(this).attr('href'); window.location.hash = target; $.ajax({ url: ...

In the scenario where there are duplicate 'id' keys within the array of objects, what is the best method to remove the object with the duplicate key?

When there are duplicate 'id' keys among the objects in the array, how can you remove the object with the duplicated 'id'? I attempted to use filter, map, and set methods, but none of them were successful. Since the array is not one-di ...

Select a random character from a string using JavaScript

This question sets itself apart from Removing random letters from a string as it focuses on selecting a random letter from a string in JavaScript without removing any characters. The goal is to implement a code that picks random letters from a string in J ...

What is the best way to resize a div located below a dynamic div in order to occupy the available space?

My website has a dynamic div1 and a scrollable table inside div2. I need the div2 to take up the remaining height of the window, while ensuring all divs remain responsive. I've tried using JavaScript to calculate and adjust the heights on window loa ...

Unseen cells and sift through information in datatables

I encountered an issue with the data table while trying to display data from a database using AJAX and applying filters through a PHP file. The initial setup works smoothly, however, I faced a problem after implementing a column hiding feature which caus ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

What is the best way to include a disable option or default option in a select box?

I am incorporating react material in react using the select component. My goal is to include a first disabled option that says "please select item." This is how it's currently implemented in HTML: <select name="tagging"> <option sel ...

What methods can a controller use to verify the legitimacy of the scope?

I'm a bit perplexed when it comes to validation in angular. It seems like all of the validation is connected to the form. But what happens when the controller needs to ascertain if the model is valid or not? Here's an example I quickly whipped u ...

Toggle Button Control

In my PHP file, I have a submit button for the form coded like this: <input type="submit" name="submit" value="submit" disabled="true" /> Next, I initiate an asynchronous request using a request object, document.getElementById("username").onblur= ...

Pre-Render Conditions in React - Optimizing Your Components for Faster

Before launching my React application, there are two key conditions that need to be checked: First, it is important to verify if the user is logged in. If not, the user should be redirected to the login page. Secondly, all user settings must be retrieved ...