2

I'm using Javascript to generate random movie plots from several arrays of word lists using the Math.random function which I've adapted from another generator. The code generates a random name for the main character from an array of names, and I need to repeat this same name in other parts of the plot, e.g. if the name Fred is chosen at the start then I need to say Fred in a few other sentences. If I just use the same Math.random function for subsequent instances of the name, I sometimes get a new random name from the list instead. Is there a way to "remember" the random name chosen at the start and display it whenever I want? Code sample:

<html>
<input type="button" value="Generate" onclick="GetPlot()">
<textarea name="plot" id ="plot" cols="100" rows="25"></textarea>
<script type="text/javascript">
function GetPlot(){
var Name = new Array("Fred", "John", "Roger");
var n = "";
n = n + Name[Math.round(Math.random()*(Name.length-1))];
n = n + " is the lead character." + Name[Math.round(Math.random()*(Name.length-1))] + " is wanted by the FBI.";
document.getElementById('plot').value = n;
}
</script>
</html>

0

1 Answer 1

1

Math.random() can generate a different number everytime you use it. you can just save the random number generated once and use it again. And anyways you are storing name in n once, you can use that again while making the sentence.

<html>
<input type="button" value="Generate" onclick="GetPlot()">
<textarea name="plot" id ="plot" cols="100" rows="25"></textarea>
<script type="text/javascript">
function GetPlot(){
var Name = new Array("Fred", "John", "Roger");
var randomIndex = Math.round(Math.random()*(Name.length-1));
var n = "";
n = n + Name[randomIndex];
n = n + " is the lead character." + n + " is wanted by the FBI.";
document.getElementById('plot').value = n;
}
</script>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Dij, that's great! :)
@Thoughtcat you are welcome, consider accepting the answer if it helped. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.