Adjust the likelihood of selecting a random string

My goal is to randomly select Anna 67% of the time, Bob 30% of the time, and Tom 3% of the time. Is there a more streamlined method for achieving this?

Here's what I've come up with:

var names = ['Anna', 'Bob', 'Tom'];
var name = names[Math.ceil(Math.random() * (names.length - 1))];
console.log(name);

Answer №1

After reading through Stack Overflow, I believe the code snippet below will effectively solve your problem:

function randomlySelect(input) {
  let randomValue = input.reduce((a, b) => a + b) * Math.random();
  return input.findIndex(a => (randomValue -= a) < 0);
}

function multipleRandomSelections(input, numberOfSelections) {
  return Array.from(Array(numberOfSelections), randomlySelect.bind(null, input));
}

const names = ['Alice', 'Charlie', 'David'];

const chosenIndex = multipleRandomSelections([0.67, 0.3, 0.03], names);
console.log(names[chosenIndex]);

// Testing to verify that everything is functioning correctly:

const occurrences = [0, 0, 0];

for (let j = 0; j < 100000; j++) {

  const result = multipleRandomSelections([0.67, 0.3, 0.03], names);
  occurrences[result] = occurrences[result] + 1;

}

console.log(occurrences.map(o => o / 1000));

Answer №2

Check out this quick fix for your problem:

function chooseName(){
  var randomNumber = Math.random();
  if(randomNumber < .67) return "Alice";
  if(randomNumber < .97) return "Brian";
  return "Sam";
}

console.log( chooseName() );

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

Issues with Sound Not Playing When Button is Clicked in Python Flask

My goal is to trigger an audio sound when the Delete button is clicked. I've created an external JavaScript file and successfully linked it with Flask. index.html <a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound ...

What is the simplest method for comparing transaction amounts?

I'm in the process of integrating PayPal into my website using their REST API. My goal is to allow users to input the amount they want to deposit. While I can obtain the total during payment creation, I'm unsure how to smoothly pass it to the exe ...

How to access previous Redux state when navigating back using the Back button

Imagine a search page equipped with a search bar and various filters for the user to customize their data retrieval. As the user selects different filters, an API call is made to fetch updated data and the route path is also adjusted accordingly. However ...

AngularJS ng-repeat causing data binding to constantly refresh

If I were to have a $scope setup similar to this: $scope.array = [ { a: 1, b: 2 }, { a: 2, b: 1 }]; And a corresponding view: <div>A: <div ng-repeat="obj in array">{{obj.a}}</div> </div> My question is, if the AngularJS watche ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...

Tips for using the minimum function to find the lowest value of a product

my list1=[{"samsung6","18000"},{"samsung7","19000"},{"samsung8","12000"}] I need the output to be samsung8, 12000 but an error is occurring stating Index 0 out of bounds for length 0 public String getLowestPrice(ArrayList<String[]> data) { ...

Adding hyperlinks that do not redirect

I have 2 separate divs displayed on a website: <button class="form-control margin btn btn-warning hide_all" id="addLinks">Link Pages</button> <button style="display: none" class="form-control margin btn btn-primary hide_all" id="hideLinks"& ...

Exploring the Implementation of Multiple Form Validations in SharePoint using PreSaveAction

My knowledge of Javascript is limited to what I can gather from online resources. Currently, I'm facing a challenge with a SharePoint form where I need to set up specific validations that trigger when a user hits the "Save" button. The validations I& ...

In order for Angular forms to be considered valid, they must fall into one of two form

I am attempting to create a dynamic angular form where the user must enter either A or B. A represents a unique identifier, while B consists of a set of values that correspond to that identifier. My goal is to validate the form as valid if either A is ente ...

Steps to create a vertical center-aligned Bootstrap carousel image within the viewport

Check out my webpage at I'm trying to vertically center an image using the bootstrap carousel. The issue I'm facing is that I want the image to be displayed in its original size, but centered on the page. Here's the code snippet: <sty ...

The feature to disable swiping with SwipeEnabled set to false seems to be

I am encountering an issue with react-navigation 5 in my react-native project. I am trying to disable drawer swipes while still allowing the user to close the drawer by clicking outside of it. I have researched this property in the react-navigation documen ...

To enable the radio button upon clicking the list item in JavaScript, simply check the radio button

I am working with radio buttons Here is the HTML code: <input type="radio" class="first" name="bright" checked> <input type="radio" class="second" name="bright" > <input type=" ...

"Encountering a Three.js issue when attempting to incorporate over 37 spotlights in the scene

My project involves utilizing Three.js r58 (with the WebGLRenderer) to display a 3D model of a building with detailed information about the positions and dim levels of the lights inside. For each light sourced from the database, I create a CubeGeometry ob ...

What is the best way to convert JSON data into an array?

Here is an API code snippet taken from a template: $country_array = array(); $country_array['data'] = array(); while($row = $result->fetch(PDO::FETCH_ASSOC)) { extract($row); $country_item = array ( 'ID' => $ ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

Dynamic Menu Highlight Styling

I'm having trouble highlighting the current menu item when clicked using CSS. Here is the code I have: #sub-header ul li:hover{ background-color: #000;} #sub-header ul li:hover a{ color: #fff; } #sub-header ul li.active{ background-color: #000; } #su ...

Issue with displaying content using v-show in a Nuxt.js menu

Struggling to create a mobile menu with Vue instance error The Nuxt Menu Component : <template> <header id="menu" class="menu-g"> <Nuxt-link to="/"><img src="~assets/logo.svg" alt=&qu ...

Could someone kindly provide a detailed explanation of this Javascript code, breaking it down step

I'm currently learning Javascript and stumbled upon this code snippet. However, I'm having trouble grasping its functionality. Can someone please break it down for me step by step? var ar1 = [1, 5, 6, 4, 3, 5, 100, -20]; function funDo(ar) { ...

Difficulty encountered when trying to template routes with more than one slash in Angular-route

I'm encountering difficulties with my Express+Jade+AngularJS[v1.2.22] application when attempting to access routes such as "mydomain.com/something/somethingelse" or "mydomain.com/something/another/last", which include one or more path subdivisions. T ...

open a document and store its contents into a matrix

Here is the content of a file I am working with: 1 100 2 200 3 300 4 400 1 I am trying to convert this data into a matrix and replace missing second numbers with NULL. However, my current program is not functioning as expected. Here is a snippet of the ...