A new method that selects larger numbers at random from an array

I've done some research and uncovered an algorithm designed for small lists in general. Here are a few arrays that I have:

arr = [1,2,3,4 .... , 96,97,98,99,100];

arr2 = [105, 110, 165, 170];

arr3 = [1,2,7,8,9];

My goal is to pass these arrays to a function and retrieve random numbers from them, but with a skewed probability towards higher numbers.

For instance, in array 1, the likelihood of selecting 96 should be greater than that of 4, and the likelihood of picking 97 should be higher than 96.

To explore options on how to generate a weighted distribution of elements randomly, check out this resource.

The typical solutions presented in such discussions may lead to performance issues when applied to my arrays.

How can I overcome this challenge?

Answer №1

To find the likelihoods and choose the appropriate value, you can use this method.

If you want to apply it to a custom array, utilize the random function.

getRandomValue = random(sortedArray),

Then, within a loop:

let value = getRandomValue();
const
    random = sortedValues => {
        let length = sortedValues.length,
            sum = length * (length + 1) / 2;

        return () => {
            let r = Math.random();
            return sortedValues.find((_, i) => (r -= (i + 1) / sum) <= 0);
        };
    },
    getRandomValue = random([6, 7, 8, 9, 10]),
    counts = {};

for (let i = 0; i < 1e6; i++) {
    let value = getRandomValue();
    counts[value] = (counts[value] || 0) + 1;
}

console.log(counts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

Implement a Bootstrap button that can efficiently collapse all elements in one click

Within my HTML file, I have included the following code: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <div class="list-group list-group-flush"> <a href="javascript: void(0)" da ...

What sets apart the JavaScript console from simply right-clicking the browser and opting for the inspect option?

As I work on developing an angular application, one of my tasks involves viewing the scope in the console. To do this, I usually enter the code angular.element($0).scope(). This method works perfectly fine when I access the console by right-clicking on th ...

Fetching data from a database based on the current element during ng-repetition

Currently, I am in the process of developing a spring web application where I have implemented a div table. My goal is to showcase data from an array within angularjs's $scope using ng-repeat. Here is an example: <div ng-repeat="element in element ...

Learning the ins and outs of NodeJS for developing a basic backend system

I've been working on creating a basic server in nodejs with a simple API that requires authentication through username and password. I'm not looking to include any frontend functionality like templating. However, I'm struggling to grasp the ...

Tips for iterating through a list of checked values using v-for

Currently working on a feature to create a checkbox that allows only one selection. <div id="app"> <div v-for="(question, index) in questions"> <input type="checkbox" value="question.value" v-model ...

Tips for pulling out particular information from a string?

There is a text document that needs to be parsed. The objective is to extract the strings between "@5c00\n" and "@ffd2\n", as well as between "@ffd2\n" and "@". @5c00 81 00 00 5C B1 13 3E 01 0C 43 B1 13 A6 00 1C 43 B1 13 38 01 32 D0 10 00 ...

Obtain Dates in a Uniform Structure

I have a function that retrieves the date based on specific conditions (last 30 days). const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); const startTime = start.toLocaleString().split(",")[0]; console.log(startTime) On M ...

Ensuring that the form button is reset automatically upon using the browser's "Back" button

Even after exploring numerous similar questions and trying out various suggested solutions, I still can't seem to get anything to work. The issue I'm facing involves a form on a webpage. To combat the problem of impatient individuals clicking &a ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

Implementing a collapsible menu feature in Bootstrap 3 when clicked

Experiencing an issue with a Bootstrap menu where I want the menu to collapse after clicking on one of the sections. This is the HTML code: <div class="container" id="home"> <nav class="navbar navbar-default navbar-fixed-top" role="navig ...

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...

The issue with accessing the URL using $.ajax prevents successful connection

I am currently working on a project that involves sending data using jQuery and $.ajax to a PHP file. Initially, when the page loads, a list of names is fetched from "bewohner_func.php" successfully. At the bottom of the list, there is a form that allows ...

Troubleshooting the ineffectiveness of RegExp object in finding and replacing

I have been attempting to substitute values in a string template using the following method: for (var i in replacements) { var regexp = new RegExp('\$\{' + i + '\}', 'g'); template = template.replace(re ...

Exploring how to showcase user data using only the unique identifier within the friendships node on Firebase

Trying to figure out the best way to showcase a user's friend list using this database structure: friendships: user1 - user3: true - user4: true user2 - user1: true - user5: true I'm wondering how to display the users data fr ...

Automatically scroll the element both up and down

I am working on a bootstrap table that needs to automatically scroll vertically. The table will be displayed on a screen and could have varying numbers of items, so I want it to continuously auto-scroll for the user's convenience. Once it reaches the ...

Formatting datetime in Flask using Python

Hey there, I'm new to Python and Flask. I'm curious if there's a more efficient way to convert 20210910103255 to the format 2021/09/10 10:32:55. I attempted it using the following code, which does the job, but I'm hoping for a cleaner i ...

What is causing my JavaScript to function properly without the need for the 'defer' keyword?

After crafting the subsequent HTML code: <!DOCTYPE html> <html lang="en"> <head> <script src="j1.js" **defer**></script> <meta charset="UTF-8"> <meta name="viewport" ...

Show Video Within Text

Is there a way to have a video play inline on iOS without expanding to full screen when clicking the play button? I attempted to add webkit-playsinline <video width="400" controls webkit-playsinline> <source src="mov_bbb.mp4" type="video/mp4" ...

What methods do typescript libraries use to interpret types during runtime?

After compiling source code from TypeScript to JavaScript, type annotations are removed and it becomes impossible to verify the type of a variable at runtime. Despite this limitation, there exist TypeScript libraries that alter their behavior based on the ...