Home > front end >  Generate random number from array, move to new array, validate if the number has been used
Generate random number from array, move to new array, validate if the number has been used

Time:04-23

I am new to Javascript and I have decided to take on a personal project. The project will do the following:

  1. Generate a random number from an array1 on clicking a button (say numbers from 1 to 10).
  2. Remove the randomly generated number from array1 to array2 (so the number is not repeated).
  3. Display a popup when all the numbers in array1 are generated and array1 is empty.
  4. Simultaneously display all the generated numbers (preferably in ascending order and tabular form).
  5. Add an input box in which user can enter a number and a pop up will tell the user if the number has been generated yet or not.
  6. Have a reset button which will move all the elements back to array 1 and would restart the program (if the code for this is not too complex).

I am just a beginner so it would be very helpful if there were comments after every major code line explaining what does that code do, if that's not too much trouble. Thanks!

CodePudding user response:

Since you are learning, I will do the heavy lifting for your; however, the rest is after you since there is no way to learn without you working on the problem yourself. I hope that you can take care of the rest since the information to do so is available online if you search for it.

Let's take care of the engine first.

First, we create an object that will hold both array:

let numbers = {
  stored:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  used: []
};

I put both into an object to make it more reusable.

To obtain a random number, we need to obtain a random index:

let index = Math.floor(Math.random() * this.stored.length);

We do this by multiplying the length of the array with the value return by Math.random() which goes from 0 to 1. Then, we floor the results in order to eliminate any decimals.

Next, we obtain the value that we wish to return:

let value = this.stored[index];

Following, we move that value from the stored array to the used array:

this.used.push(value);

Then, we used the sort method of the array. We pass a function as an argument that indicates how we wish to order the values. by indicating how we wish to order the values.

this.used.sort((a, b) => a - b);

The way it works is that the function provided will return either zero, a positive value or a negative value, which will indicate how it will sort the content. For more information check Array.prototype.sort()

Lets not forget to remove that value from the stored array:

this.stored = this.stored.filter(elem => elem != value);

What we do here is to filter out all elements that aren't the value and return those numbers, then we assign this new array.

Note: We are assuming that all elements in the stored array are unique. If that isn't the case, then this line needs to be replaced to handle that.

let numbers = {
  stored:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  used: [],
  get random() { 
    if (this.stored.length < 1) return;
    let index = Math.floor(Math.random() * this.stored.length);
    let value = this.stored[index];
    this.used.push(value);
    this.used.sort((a, b) => a - b);
    this.stored = this.stored.filter(elem => elem != value);
    return value;
  },
  reset() {
    this.used.forEach(element => this.stored.push(element));
    this.used = [];
  },
  hasNext(){    
    return this.stored.length > 0;
  }
};  


while(numbers.hasNext()){
  console.log(numbers.random);
}

console.log("Stored Numbers: ", numbers.stored);
console.log("Used Numbers: ", numbers.used);

numbers.reset();

console.log("Stored Numbers: ", numbers.stored);
console.log("Used Numbers: ", numbers.used);

For the popup, input box and such, there are many options.

You could do it with pure HTML, CSS, and JavaScript. Create the form in HTML. With CSS, you can make the form to be hidden, with the position absolute and centered. Then, with JavaScript you manipulate when shows and not. There are many examples online showing different ways to do this.

If you are allowed to use a library then one option I might suggest is using Bootstrap. It will make your whole interface look pretty.

You can use modals and with jQuery you can manipulate the interface.

CodePudding user response:

If you're new to JavaScript, I'd suggest looking at tutorials such as W3Schools to learn more about JavaScript, specifically array manipulation, which is what you need to pursue this project. Here's a quick example that I created showing a bit of the problem you need to solve. Perhaps this can help?

W3Schools: https://www.w3schools.com/js/js_arrays.asp

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //Array of numbers

document.getElementById("btn").onclick = () => { //Check if user clicks button
  let num = array1[Math.floor(Math.random()*array1.length)] //Get random number from above array
  const index = array1.indexOf(num); //Find number that was just selected when the user clicked the button
  if (index > -1) {
     array1.splice(index, 1); //Remove ONE element from the array, this being "index" which we defined above
     alert("You chose: "   num   "\nArray: "   array1) //Alert the number that was chosen and removed, along with the current array with one less number
  } else {
    alert("No numbers remaining.") //If array is empty, alert the user
  }
}
<button id="btn">Get Random Number</button>

  • Related