selecting a number at random from a defined array

I am looking to generate a series of lottery numbers like the following:

my list could be between 1 - 100, or it might range from 1 - 200, or even 1 - 300

  1. select 35 random numbers from the chosen list.
  2. choose another set of 25 numbers from the list.
  3. pick an additional 10 numbers from the same list.

This task must be completed using only Javascript.

Answer №1

Illustrated below is a concise example where the script generates a list of random numbers ranging from 0 to 10 (you have the option to alter the range by adjusting the values for min/max in the getRandomInt(min, max) function).

The argument in getNumbers(times) specifies how many times you wish to select a number from the pool.

It's worth noting that this example may select a number multiple times on different interactions (since this requirement was not mentioned in the original question).

(function() {
  var getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };
  var getNumbers = function(times) {
    for (var i = 0; i < times; i++) {
      console.log(getRandomInt(0, 100));
    }
  };
  console.log('---------- Selecting 35 numbers randomly');
  getNumbers(35);
  console.log('---------- Selecting 25 numbers randomly');
  getNumbers(25);
  console.log('---------- Selecting 10 numbers randomly');
  getNumbers(10);
})();

The modified version below only selects unique numbers (as per your request in the comment):

(function() {
  var usedNumbers = [];
  var getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };
  var getNumbers = function(times) {
    for (var i = 0; i < times; i++) {
      var number = getRandomInt(0, 100);
      if (usedNumbers.indexOf(number) === -1) {
        usedNumbers.push(number);
        console.log(number);
      }
    }
  };
  console.log('---------- Selecting 35 unique numbers');
  getNumbers(35);
  console.log('---------- Selecting 25 unique numbers');
  getNumbers(25);
  console.log('---------- Selecting 10 unique numbers');
  getNumbers(10);
})();

Answer №2

Presented below is the function I devised, designed to compare each generated random number with previous numbers in order to prevent duplicates. Additionally, it allows for exclusion of specific numbers (such as those from prior attempts) by passing them as arguments to the exc parameter within the function.

var lottery = function (min, max, size, exc) {
  var results = []
      , isDuplicate = false
      , random = 0;
  exc = exc || [];  
  for (var i = 0; i < size; i++) {
    isDuplicate = true
    while (isDuplicate) {
      random = Math.floor(Math.random() * (max - min + 1)) + min;
      if (results.indexOf(random) === -1 && exc.indexOf(random) === -1) {
        results.push(random);
        isDuplicate = false
      }
    }
  }
  return results;
}

var firstRun = lottery(1,100,35);
console.log(firstRun);
var secondRun = lottery(1,100,25,firstRun);
console.log(secondRun);

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

"Object.entries seems to be returning only the initial object in the list

This is my object var obj = { "first_obj": { "a":1, "status": 1 }, "second_obj": { "a":2, "status": 3 } } I'm struggling to loop through this object using foreach and Object.entries, as the latter only returns the first object. How ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...

Having trouble with AJAX integration when adding two products to the cart? Looking for a solution to resolve this issue?

In the cart view page, I have noticed that when there is only one product in the cart, I am able to increase and decrease the quantity by clicking on the + and - buttons. However, if I add more than one product to the cart, these buttons do not work for an ...

I'm encountering an issue in my node application where it is unable to access the push

I am a beginner in the world of node.js and express. Whenever I try to start my application using the command npm start, I encounter an error message saying Cannot Read property push of undefined from my index.js file. The problematic code snippet looks l ...

When using Python Selenium, we can see JavaScript in the view page source, but inspecting elements reveals the

I'm currently facing a challenge in accessing links to attachments for a web automation project. The issue lies in the fact that while I can view the HTML Code (divs and tables) when loading the webpage via Chrome and inspecting element, all I see in ...

javascript - audio is not working on the web

I've been trying to incorporate sound into my website using this code. Strangely, the sounds only seem to play in Adobe Dreamweaver and not in any browsers. Any advice would be greatly appreciated! :) var audio1 = new Audio('sound1.mp3'); v ...

Comparing ASP.NET Core and Node.js: A Closer Look at Their Similar

After working with Node.js for some time, I have gained a deep understanding of how it operates internally, including the event loop and other aspects. However, I can't help but notice that ASP.NET Core bears a striking resemblance to Node.js. ASP.NE ...

Setting state for a dynamic component based on condition in React

Working on creating a dynamic component where the data index matches the URL parameter blogID received from the router. Below are the router parameters sending props to the component: <Route path='/blog/:blogId/:blogTitle' render={() => & ...

When transitioning in Vue, pagination bullets shift to the left upon changing routes

While using Vue 3 and swiper.js, I encountered an issue where the pagination bullets move to the left when the route changes (component unmounted). It appears that the styling for the bullets and active button also disappear. I have created a reproduction ...

HTML elements not displaying in Ajax form

I am encountering an issue with my ajax based feedback form where the form is displaying the html from the response instead of processing it correctly. Here is the JQuery code: $(document).ready(function() { var form_holder = $('#form-holder'); ...

Adjusting the Depiction Camera Distortion in Three.js

In my top-down Three.js game, I'm currently using a Perspective Camera. However, I've noticed that it curves a bit too much because it's mainly for "first-person view". Is there a way to customize how objects bend or curve within the frustum ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...

Unusual div image alignment when dimensions are dynamically adjusted with Javascript animations

I have created a basic webpage using JavaScript that aims to scale an element from the center of the page over time when clicked. It is functioning properly for the SVG element I tested it with. However, when I use an image, it initially appears outside o ...

Cannot bind rvalue reference to temporary constant array

Below is the test program currently in question: #include <iostream> #include <type_traits> #include <utility> template<typename Ty, std::size_t N> void foo(Ty (&&)[N]) { std::cout << "Ty (&&)[" << ...

The left border is failing to appear on the Td element

When attempting to add border styling to td elements, the left border is not displaying correctly. This issue seems to vary across different browsers. Here is the HTML code: <table class="table-bordered"> <thead> <tr> ...

A straightforward Node.js function utilizing the `this` keyword

When running the code below in a Chrome window function test(){ console.log("function is " + this.test); } test(); The function test is added to the window object and displays as function is function test(){ console.log("function is " + this.tes ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

Manipulating data with Angular's array object

I am having an issue with posting an object array. I anticipate the post to be in JSON format like this: {"campaign":"ben", "slots":[ { "base_image": "base64 code here" } ] } However, when I attempt to post ...

Changes in a portion of the state for Vaadin's AbstractJavascriptComponent

I am currently working on implementing a JavaScript-based component for Vaadin that will be responsible for displaying and updating a large data set. To achieve this, I am extending AbstractJavaScriptComponent. My goal is to keep the JavaScript side as si ...

Having trouble changing the state within React's useEffect() when using an empty dependencies array? Socket.io is the cause

I have a question regarding the access of allUserMessages from my state within useEffect without anything in its dependency array. Let me provide more details below. Thank you. My goal is to append data to an array in my state using useEffect similar to c ...