Supernumber Lottery: A Chance to Win Big!

I've been faced with the task of creating a random number generator for selecting lottery numbers. The challenge is to generate 6 unique numbers between 1 and 49, in ascending order, without any repeats. Additionally, there is a 7th number called the super-seven, which cannot be any of the previous 6 numbers.

<script type="text/javascript">
    const numb = new Array();
    for (var i = 0; i < 6; i++) {
        numb[i] = Math.floor(49 * Math.random()) + 1;

        // compare to existing numbers
        for (var k = 0; k < numb.length - 1; k++) {
            if (numb[i] == numb[k]) {
                i--;
                break;
            }
        }
    }

    let supNumb = new Array();
    supNumb = Math.floor(49 * Math.random()) + 1;
    for (var s = 0; s <= 1; s++) {
        // compare supNumb to numb
        for (var t = 0; t < numb.length - 1; t++) {
            if (supNumb == numb[t]) {
                s--;
                break;
            }
        }
    }


    // SORT & DISPLAY NUMBERS 
    function sort(a, b) {
        return a - b;
    }

    numb.sort(sort);
    document.write("<p> " + numb);
    document.write("<h4>" + "SuperSeven: " + supNumb);
</script>

After testing, it seems that the super-seven number supNumb sometimes matches one of the numbers generated in numb. I'm struggling to figure out how to prevent this from happening.

If anyone could review my code and suggest how I can compare supNumb to numb correctly, I would greatly appreciate it.

Is my current approach correct for this task?

Thank you in advance!

Answer №1

If you want to create an infinite loop and break it when you find a valid number, you can do the following:

while(true){
    randomNum = Math.floor(49 * Math.random()) + 1;
    if(numbers.indexOf(randomNum) < 0){
        break;
    }
}

It's recommended to use indexOf to search in the array as it is faster than plain JS. https://www.w3schools.com/jsref/jsref_indexof_array.asp


Another approach is to utilize the Set functionality. Sets only store unique values, ignoring duplicates:

var numberSet = new Set(),
    randomNum = 0;
while(numberSet.size < 6){
    numberSet.add(Math.floor(49 * Math.random()) + 1);
}
while(true){
    randomNum = Math.floor(49 * Math.random()) + 1;
    if(!numberSet.has(randomNum)) break;
}
var sortedNumbers = [...numberSet].sort((a,b)=>{return a-b})
console.log(sortedNumbers, randomNum);

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Set

Answer №2

It appears that the value for supNumb is currently set as an array when it should be a single integer to properly compare against the array member of numb.

If supNumb does not meet the criteria of being unique, you will need to generate a new random value.

Answer №3

If you're looking to generate non-repeating numbers, one effective method is the Fisher-Yates-Knuth shuffle technique. This method ensures the selection of 7 unique numbers from a range of 1 to 49 without the need for additional checks.

While I don't have JavaScript knowledge, here is a pseudocode representation:

a = _.range(1, 50);

for i from n−1 downto 1 do
     j ← random integer such that 0 ≤ j ≤ i
     exchange a[j] and a[i]

sort(a, 6); // sort first 6 elements
super = a[6];

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

Typescript error: The argument containing 'username' and 'password' fields cannot be assigned to a parameter expecting only a 'string' type

My service is designed to take an endpoint and execute a HTTP call. Here is the code snippet: export const updatePassword = (data: { username: string; password: string; }): HttpResponse<string> => { const { usernam ...

Exploring jQuery's class attribute: Uncovering the key-value pair trick

I am encountering difficulties in obtaining the class of my div elements, which are intended to function as tabs on a simple asp.net website. I aim to achieve this using jQuery for better control over dynamic functions in the future. However, every time I ...

Issues with monitoring multi-touch gesture events using Hammer JS

Can anyone figure out why this code, which utilizes hammer.js for multi-touch gesture events, is not functioning as expected? This code closely resembles one of the examples on Hammer's documentation. Despite setting up swipe events on specific elem ...

Click the link to capture the ID and store it in a variable

Currently working on a project involving HTML and JavaScript. Two HTML pages ("people.html" and "profile.html") are being used along with one JavaScript file ("people.js") that contains an object with a list of names, each assigned a unique ID: var person ...

Strategies for extracting methods and refactoring to a separate file for better reusability

Still relatively new to the JQuery/javascript realm, I've put together a functional jqgrid with a datepicker and custom control (using jquery auto complete) by piecing together code samples I came across online. This code has been added to a T4 templa ...

Tips for Sending an Ajax POST Request

I've been using the following code snippet to initiate a POST request to my node API in order to generate a PDF. However, upon execution, my node console displays the following errors: $('#renderPDF').click(function(){ var request = $ ...

PHP and JavaScript Form: Include the page URL in the email form when submitting

After submitting a basic form, I am struggling to include the URL of the page in the email notification to track where the user completed the form. I have attempted various solutions from this forum, but unfortunately none of them seem to work. How can I ...

Retrieve the Three.js object from an array

As part of a course requirement, I am tasked with creating a simple game using Three.js. One of the tasks involves setting up an array of spotlights in the following manner: function loadLights(roomWidth, roomHeight) { let spotlights = []; fet ...

Is there a way to attach a React component to an HTML element called i?

I've been implementing the winbox modal library and have encountered an issue when trying to add a React node to it. The modal offers an html parameter that accepts an HTML string like div.innerHTML = <div>hello</div>. The code snippet is ...

What is the reason that the insertBefore() method fails to properly extract an element from the friendly iframe in IE7?

I'm looking to extract an element from the DOM tree of an iframe and transfer it to the DOM tree of the parent document. Although this process is successful with most modern browsers, it encounters an issue with IE7, generating an Error: Invalid argu ...

Accessing state in Vuex modules is crucial for managing and manipulating data effectively

Feeling a bit lost here... I'm utilizing Vuex in my project and have a module called common stored in the file common.js: const initState = { fruits: [] } export default { state: initState, mutations: { SET_FRUITS(state, fruits) { cons ...

Uploading Files with PhoneGap using Ajax

I have been attempting to execute this PhoneGap example for uploading images from a device to a server. // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // functi ...

Populating parameters in a JavaScript callback function - what's the process?

Callbacks are functions that are passed as parameters into other functions, as shown in this simple example: function operation(a,b, callback) { return callback(a,b); } function add(a,b) { return a+b; } function multiply(a,b) { return a*b ...

Error in the data format or configuration within the chart.js streaming data plugin

I'm in the process of setting up a live streaming data chart that reads data from a page displaying the most recent data points every second. I am utilizing the chart.js-plugin-streaming plugin developed by nagix for this task. The challenge I'm ...

Having Trouble Sending Text to InputBox Using Selenium WebDriver

Greetings everyone Can someone guide me on how to use Selenium to input a Login and Password in an Alert Dialog Box? Upon loading the webpage, the alert is already displayed: https://i.stack.imgur.com/F1O5S.png I have attempted the following code: Str ...

Automatically load content using AJAX when scrolling within a HTML5 segment

Recently, I've been developing a website that dynamically loads new content from a MySQL database as the user scrolls. However, I've encountered an issue where the new content is loaded even with minimal scrolling, rather than only when reaching ...

Flask not serving Favicon and images to a React application

I am currently working with a Flask server and have it set up in the following manner: app = Flask(__name__, static_folder="dist/assets", static_url_path='/assets', template_folder="dist") ...

Updating an item in an array stored in state using user input in a React.js application

Currently, I am working on a react madlibs app and facing an issue with updating the this.state.blanks array accurately as the user inputs words. I believe there might be an issue with binding (even though I used a fat arrow function which should bind it) ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

The function parseFloat in Javascript can be used to subtract two numbers, returning an integer value

Apologies for the inconvenience, but I could really use some assistance. I attempted to convert a string into a decimal and was successful, although I encountered an issue: number = document.getElementById("totalcost").innerHTML; //String that rep ...