Create a set of four unique numbers in an array with four digits each

let gameScope = {}

function generateUniqueNum() {
    gameScope.uniqueNumbers = [];
    for (let j = 0; j < 4; j++) {
        let number = Math.floor((Math.random() * 9)+1);
        if (!gameScope.uniqueNumbers.includes(number)) {
            gameScope.uniqueNumbers.push(number);
        } else {
            j--;
        }
    }
    return gameScope.uniqueNumbers;
}

Hey there! I'm new to learning JavaScript and I have an assignment to create a 4 digit array with unique numbers ranging from 1 to 9 (for a game similar to Bulls and Cows). I'm having trouble figuring out how to check this array for repeated numbers. Any help would be greatly appreciated. Thanks!

Answer №1

If you prefer, you have the option to utilize a source array that includes all numbers from 0 to 9, and then select and delete one of them each time:

function generateNumber(){
    var targetArray = [], // target array
        sourceArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], // source array
        sourceLength = sourceArray.length,
        index, randomIndex;

    for (index=0; index<4; index++) {
        randomIndex = Math.floor(Math.random() * (sourceLength - index)); // choose a random index
        // remove the selected number from the source and add it to the target array
        targetArray.push(sourceArray.splice(randomIndex, 1)[0]);
    }

    // return the resulting array
    return targetArray;
}

To learn more about the .splice method, visit MDN.

Answer №2

To efficiently obtain a set of random digits, the ideal approach involves utilizing an array containing all possible digits and then retrieving them individually:

let allDigits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    outcome = [];
for (let j = 0; j < 5; j++) {
    outcome[j] = allDigits.splice(Math.floor((Math.random() * allDigits.length) + 1, 1);
}
return outcome;

Answer №3

If you're approaching this task from a beginner's perspective, the first step is to outline the necessary steps needed to accomplish it.

Pseudocode:

1. Generate a random number.
2. Add the random number to an array.
3. Loop until the array length reaches 4:
4.    Generate another random number.
5.    Check if the number already exists in the array.
6.    If the number is not already in the array, add it.

Creating the code is made simple by following these steps. Start by generating a random number and pushing it into an array. Then, use a while loop until array.length === 4. Generate additional numbers within this loop and utilize a for loop to verify if the number is already present in the array.

for (var i = 0; i < array.length; i++) {
   //Check for existence here
}

Answer №4

let gameData = {}


function createNumbers() {
    gameData.randomNums = [];
    while (gameData.randomNums.length < 4) {
        let num = Math.floor((Math.random() * 9) + 1);
        if (gameData.randomNums.indexOf(num) < 0) {
            gameData.randomNums.push(num);
        }
    }
    return gameData.randomNums;  
}

Answer №5

This particular method could be precisely what you're seeking:

  • Start by selecting a random position within the range of [0,10-i)
  • Next, append the number at position #index to the resulting array
  • Lastly, copy the number at position #i into position #index

function generateNumber()
{
    var numbers = [0,1,2,3,4,5,6,7,8,9];
    var resultArray = [];
    for (var i=0; i<4; i++)
    {
        var position = Math.floor(Math.random() * (10 - i));
        resultArray += numbers[position];
        numbers[position] = numbers[10 - i];
    }
    return resultArray;
}

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

When the button is clicked, request the total count of elements in the array

Is there a way to log the index of an array element when clicked? I have a large array with over 100 elements: var cubesmixed = []; var cubes; for(var i = 0; i < 143; i++) { cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random ...

Rejuvenate your Bootstrap Accordion with these Settings

Using bootstrap documentation, I have implemented an accordion in my web application with the following code: <div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class=" ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...

Is there a quick method for determining the location of an item within a flat 2D list using coordinates?

I need a concise formula to determine the flattened position of an ordered pair. Imagine a TicTacToe grid as an example. |---|---|---| | 0 | 1 | 2 | |---|---|---| | 3 | 4 | 5 | |---|---|---| | 6 | 7 | 8 | |---|---|---| If given (1, 1), how do I arrive a ...

Error in Typescript: 'SyncClient' not found in Twilio

While working on my Ionic app, I encountered an issue every time I attempted to use the twilio-chat library in my project through npm install. The error consistently appeared in the .d.ts files. Here is how I imported it in my provider : import { Client ...

Convert a JSON object into a new format with a nested hierarchy

The JSON object below is currently formatted as follows: { "id": "jsonid", "attributes": { "personName": { "id": "name1", "group": "1.1" }, "ag ...

Encountered an error while running npm run dev on a Laravel Vue 3 project: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],

I am facing an issue in my Laravel 9 Vue 3 project. When I run php artisan serve and then npm run dev, I encounter the following error: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'di ...

Guide to running examples of three.js on a local web browser

Currently, I am attempting to run the examples from three.js locally in a web browser on MacOS. To do this, I have cloned the entire three.js repository and attempted to open a file in a browser (such as three.js/examples/misc_controls_orbit.html). However ...

How can I retrieve text adjacent to a checked input checkbox by using JQuery (or JavaScript)?

Here is the HTML block under consideration: <div class"radioGroup"> <input type="radio" value="0"> This option is NOT selected <input type="radio" value="1" checked = "checked" > This option is selected <inpu ...

Leveraging npm in vanilla JavaScript applications

Because of limitations set by the governance of my current project, I am unable to utilize many of the modern JS libraries and frameworks. Therefore, for our MVP, we are resorting to using vanilla JS directly loaded to the client (un-minified), which is no ...

Positioning a Bootstrap popover directly adjacent to the cursor's location (within the clicked element)

I've been struggling to get my bootstrap popover to show up inside the element I'm calling it on, next to my mouse cursor. Despite extensive research in the popper.js documentation and numerous attempts with various parameters, including the &apo ...

What is the best way to arrange an array by comparing to the previous element?

I am currently working on a JavaScript challenge: I have an array of random map coordinates (latitude, longitude) stored like this: var coordinates = [ [64,22],[55,33],[28,35],[...,...] ] Additionally, I have a function that calculates the distance betwe ...

What is the best way to extend the lower row items in a flex box to accommodate additional content when clicked?

My latest project involved designing an HTML flex-box to showcase images retrieved from an API. Here is a sneak peek of the layout: [![Preview of the flex-box layout][1]][1] However, I am now seeking to enhance user experience by adding functionality tha ...

Mastering the art of modifying click events with jQuery

Currently, I am delving into the world of JavaScript and JQuery, specifically exploring a reference for the click event from jquery.js. In my endeavors, I have attempted to override the click event, but to no avail. Despite my efforts to make the new even ...

The drop-down list unexpectedly closes at the most inconvenient moment

I am looking to create a search input with a drop-down list. The requirement is for the list to close when the focus or click is anywhere except the search input. I have added a function listClose() to the "blur" listener, but now I am unable to capture t ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...

Utilize the Same Function for Loading Ajax Content to Handle Additional Ajax Content

I am currently trying to load all the content on my site using ajax. The code below demonstrates how I am attempting to achieve this: <script> function lage(url){ $.get(url, function(data) { $('#plus').html(data); $('[hr ...

webpack encountered an issue: The configuration.module contains an unidentified property 'loaders'

Upon starting the server with npm run start, I encountered the following error message: ✖ 「wds」: Invalid configuration object. Webpack has been initialized using a configuration object that does not comply with the API schema. - Configuration cont ...

Assigning data to a two-dimensional array in the C programming language and then displaying the contents

Currently, I am developing a program that has the capability to open a CSV file and store the data in a 3D array. Most of the code is functioning well, but I am encountering an issue with assigning records to a 2D array. Below is the code snippet: // co ...

Is it a good idea to steer clear of including OAuth tokens in the

Utilizing my OAuth2 token in my API program is essential. However, I am also keen on sharing my code through GitHub. How can I securely use my confidential token without including it directly in my source code? ...