Avi Moses
Avi Moses

Reputation: 13

Is there a way to have JavaScript remember which part of an array was chosen at random?

I am trying to make a bot that can write poetry. I'm using p5js, which is based on JavaScript. For the actual output, I have:

text("the"+" "+ random (subjectnonperson)+" "+ random (adverbs)+" "
+ random (affectingverb)+"s"+" "+ "the"+" "+ random (adjective)+ " "
+ random (subjectnonperson),10,30) 

text(random(adverbs)+','+' '+'a '+random(noun)+' '+random(affectingverb)+"s",10,200)

The arrays that I have are inside the randoms. I want the affecting verb chosen in the first sentence to be the same as the one in the second sentence.

Upvotes: 1

Views: 44

Answers (2)

Rafael Herscovici
Rafael Herscovici

Reputation: 17124

Not an answer to your question, but you seem to just start coding. Storing a value in memory is one of the first steps in JS and i would suggest to do a little reading about the language (dont go too deep, just the basics) That said, your code can look much better:

let subject = random(subjectnonperson);
let str = `the ${subject} ${random(adverbs)} ${random(affectingverb)}s the ${random(adjective)} ${subject}`;
text(str, 10, 30);

Upvotes: 1

Kevin Workman
Kevin Workman

Reputation: 42174

You can store the selection in variables. Something like this:

const randomSubjectNonPerson = random(subjectNonPerson);
const randomAdverb = random(adverbs);
...

text("the " + randomSubjectNonPerson + " " + randomAdverb + " " ...

Upvotes: 1

Related Questions