0

I'm trying to create a random name generator. How can I choose how many strings to generate without having to copy and paste so many duplicates of code? Is there a way to have an input box where I can type a number and it will generate that amount?

function generator() {

    var planets = ["mercury","venus","earth","mars","jupiter","saturn","uranus","neptune","pluto"];
    
    var planets = planets[Math.floor(Math.random() * planets.length)] + " " 
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    + planets[Math.floor(Math.random() * planets.length)] + " "
    ;
    
    if (document.getElementById("planets")) {
    document.getElementById("placeholder").removeChild(document.getElementById("planets"));
    }
    
    var element = document.createElement("div");
    element.setAttribute("id", "planets");
    element.appendChild(document.createTextNode(planets));
    document.getElementById("placeholder").appendChild(element);
    }   
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Fire Bird
  • 13
  • 1

1 Answers1

0

I will assume that you not only want to pick random names, but also that there are no duplicates in that random selection.

The easiest way is to use a function that shuffles an array randomly. You can "lend" an implementation from here.

NB: there seems no good reason to delete and recreate the plants element in the document. Just reuse it.

Here is a simple integration with your planets array and an input for specifying the number:

let planets = ["mercury","venus","earth","mars","jupiter","saturn","uranus","neptune","pluto"];
let button = document.querySelector("#generate");
let input = document.querySelector("#num");
let output = document.querySelector("#planets");

button.addEventListener("click", generate);

function generate() {
    // Shuffle the planets randomly
    shuffle(planets);
    // Select only the number of planets that the user wants
    let selected = planets.slice(0, +input.value);
    // output the result, space-separated
    output.textContent = selected.join(" ");
}

function shuffle(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
number of planets: <input type="number" id="num" size="3" value="4">
<button id="generate">Generate</button><br>
<div id="planets"></div>
trincot
  • 317,000
  • 35
  • 244
  • 286