I_love_vegetables
I_love_vegetables

Reputation: 1341

how to generate strings with random lengths

function generate(n) {
  const notations = [" U", " D", " R", " L", " F", " B"];
  const switches = ["", "\'", "2"];

  let last = null;
  let scrambles = "";

  for (let i = 0; i < n; ++i) {
    //subtract 1 when you can't select the same as the last
    let available_notations = notations.length - (last === null ? 0 : 1);

    //one random for all combinations
    let random = Math.floor(Math.random() * available_notations * switches.length);

    let nt = Math.floor(random / switches.length); //notation value
    let sw = Math.floor(random % switches.length); //switch value

    if (last !== null && last <= nt) nt += 1; //add 1 when value bigger than last
    last = nt;

    scrambles += notations[nt] + switches[sw];
  }
  return scrambles;
}

so i have this code which will generate random strings like thisB U F' D' F2 L2 R F2 L2 B F' D2 U2 L' D' R' L2 F D R but they all generate with the same length which is whatever i put as n on the for loop

but i want the length to vary from a specfic number until a specfic number like for example i want it to generate with length of 20 until 25

Upvotes: 0

Views: 69

Answers (2)

Sivakumar A
Sivakumar A

Reputation: 701

You can also try like this

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

and then call your generator method like

var value = generate(getRandomInt(10, 25));

Here, 10 is the minimum and 25 is the maximum in range. It will produce various combinations on each execution.

Upvotes: 1

You could try something like this:

I've added an option to add min and max number, with a default value.

function generate(nMin = 20, nMax = 25)

And then we use the line below to get a random number between min and max

var n = Math.floor(Math.random() * (nMax - nMin + 1) + nMin)

Demo

function generate(nMin = 20, nMax = 25) {
  const notations = [" U", " D", " R", " L", " F", " B"];
  const switches = ["", "\'", "2"];

  let last = null;
  let scrambles = "";
  var n = Math.floor(Math.random() * (nMax - nMin + 1) + nMin)
  for (let i = 0; i < n; ++i) {
    //subtract 1 when you can't select the same as the last
    let available_notations = notations.length - (last === null ? 0 : 1);

    //one random for all combinations
    let random = Math.floor(Math.random() * available_notations * switches.length);

    let nt = Math.floor(random / switches.length); //notation value
    let sw = Math.floor(random % switches.length); //switch value

    if (last !== null && last <= nt) nt += 1; //add 1 when value bigger than last
    last = nt;

    scrambles += notations[nt] + switches[sw];
  }
  return scrambles;
}

document.getElementById("div").innerHTML = generate(20, 25) + '<br/>' + generate(2);
<div id="div"></div>

Upvotes: 1

Related Questions