0

I'm wondering if anyone can help, I'm not even sure if this is totally possible but hopefully it is.

Just to explain what I want to achieve - I'm looking to build a simple HTML page whereby the user clicks a "Generate" button and it retrieves a random selection of lines from a text file - shuffled and a random number of lines each time the button is clicked.

For a greater explanation - I'm building a Credits generator with actor and character names. This needs to be unique each time "Generate" is pressed.

This is what I have as a starting block, but the problem is it only returns one entry each time but I'm struggling on how I might go about achieving this.

index.html


  <head>
    <meta charset="utf-8" />
    <title>Cast List Generator</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Cast List Generator</h1>
    <button id="showLine">Generate</button>
    <p id="list"></p>
  </body>

</html>

script.js

    var lines;
    var randomNumber;
    var lastRandomNumber;
    
    $(document.body).ready(function () {
      
      // load the trivia from the server
      $.ajax({
        url: 'list.txt'
      }).done(function(content) {
        
        // normalize the line breaks, then split into lines
        lines = content.replace(/\r\n|\r/g, '\n').trim().split('\n');
        
        // only set up the click handler if there were lines found
        if (lines && lines.length) {
          $('#showLine').on('click', function () {
            // loop to prevent repeating the last random number
            while (randomNumber === lastRandomNumber) {
              randomNumber = parseInt(Math.random() * lines.length);
              // check to prevent infinite loop
              if (lines.length === 1) { break; }
            }
            // keep track of the last random number
            lastRandomNumber = randomNumber;
            
            // show the corresponding line
            $('#list').text(lines[randomNumber]);
          });
        }
      });
    });

list.txt (will go up to 100+)

Actor1 as Character 1
Actor2 as Character 2
Actor3 as Character 3
Actor4 as Character 4
Actor5 as Character 5
Actor6 as Character 6
Actor7 as Character 7
Actor8 as Character 8
Actor9 as Character 9
Actor10 as Character 10
Actor11 as Character 11

Would appreciate any tips with this :)

Danny Ni
  • 3
  • 1
  • Check this question out: https://stackoverflow.com/questions/13392059/grabbing-a-random-line-from-file – doo_doo_fart_man Jan 04 '21 at 23:30
  • 1
    You are successfully returning one random text line. But you want to return several (where several is random number) so why not create another random number which will be the number of lines to return, and loop through getting the next random line - of course you will need to remember which lines you've already got this time and not show them more than once on each go. – A Haworth Jan 04 '21 at 23:52

1 Answers1

0

A implementation of A Haworth idea might work:

let startingLineNumber;
let lastStartingLineNumber;
let amountOfLines;
let lastAmountOfLines;

$(document.body).ready(function () {
  
  // load the trivia from the server
  $.ajax({
    url: 'list.txt'
  }).done(function(content) {
    
    // normalize the line breaks, then split into lines
    lines = content.replace(/\r\n|\r/g, '\n').trim().split('\n');
    
    // only set up the click handler if there were lines found
    if (lines && lines.length) {
      $('#showLine').on('click', function () {
        do {
          startingLineNumber = Math.floor(Math.random() * lines.length);
          const remaingLinesToEnd = lines.length - startingLineNumber;
          amountOfLines = Math.ceil(Math.random() * remaingLinesToEnd);

          // check to prevent infinite loop
          if (lines.length === 1) { break; }
        } while (startingLineNumber === lastStartingLineNumber && amountOfLines === lastAmountOfLines);
        // keep track of the last random number
        lastStartingLineNumber = startingLineNumber;
        lastAmountOfLines = amountOfLines;
        // show the corresponding line
        const actors = lines.slice(startingLineNumber, startingLineNumber + amountOfLines).join(", ");
        $('#list').text(actors);
      });
    }
  });
});
Thiago Viana
  • 301
  • 2
  • 9
  • Thank you so much for this code, it seems to be working almost how I want it to! Is there an easy way I can amend so that the results display with each string displaying on a new line instead of next to each other? https://i.imgur.com/LjKlT82.jpg – Danny Ni Jan 05 '21 at 11:36
  • Offcourse, change the .join(", ") to .join("
    "), this will place a breaking line each spaces beetwen elements of array, and, to accept inject html content, change .text(actors) to .html(actors)
    – Thiago Viana Jan 05 '21 at 12:41