Forum Moderators: open

Message Too Old, No Replies

Random sentence generator using array

using arrays to generate a random sentence

         

harofreak00

3:48 pm on Mar 29, 2010 (gmt 0)

10+ Year Member



Hey guys, JS newb here. I am taking a Javascript class and the teacher assigned this:

Write a script that uses a random number generation to create sentences and name it sentences.html. Use five arrays of strings called: uppercase article (uarticle), noun, verb, lowercase article (larticle), and preposition. You will need to use the correct case for the article arrays.

Create a sentence by selecting a word at random from each array in the following order: uarticle, noun, verb, preposition, larticle, noun. You can find examples of generating random numbers in both Fig. 8.6 (dice-rolling) and Fig. 8.7 (random image) of Chapter 8.

The arrays should be filled at minimum, as follows: the article array(s) should contain the articles: the, a, one, some and any. The noun array should contain the nouns: boy, girl, dog, town and car. The verb array should contain the verbs: drove, jumped, ran, walked, and skipped. The preposition array should contain the prepositions: to, from, over, under and on. If you would like to add more words, adjust the arrays appropriately.

As each word is picked, concatenate it to the previous words in the sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The program should generate 20 sentences and output them to the screen (document.write or document.writeln). You should use a for loop similarly to the one used in Fig. 8.6 in order to get it to print 20 times.


I haven't gotten to the loop yet, I'm just working on the random sentence first. Here is what I have:
<script type="text/javascript">
<!--

uarticle = new Array("The", "A", "One", "Some", "Any");
noun = new Array("boy", "girl", "dog", "town", "car");
verb = new Array("drove", "jumped", "ran", "walked", "skipped");
larticle = new Array("the", "a", "one", "some", "any");
preposition = new Array("to", "from", "over", "under", "on");

var rand1 = [Math.floor ( Math.random() * uarticle.length )];
var rand2 = [Math.floor ( Math.random() * noun.length )];
var rand3 = [Math.floor ( Math.random() * verb.length )];
var rand4 = [Math.floor ( Math.random() * larticle.length )];
var rand5 = [Math.floor ( Math.random() * preposition.length )];

document.write(uarticle[rand2] + " " + noun[rand2] + " " + verb[rand3] + " " + preposition[rand1] + " " + larticle[rand4] + " " + noun[rand2] + ".");


-->
</script>


Am I on the right track? How would I loop the sentences using a for statement?

Fotiman

4:29 pm on Mar 29, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld!
Here's what I would change to start.

1. Remove the HTML comments. They don't belong within <script> elements (they were needed back in the days of Mosaic 1.0 and haven't been needed in many, many years).

2. You should declare your array variables using "var". Also, it's best to use array literals instead of using new Array. For example:

var uarticle = ["The", "A", "One", "Some", "Any"];

3. In general, document.write should be avoided. it's much better practice to use DOM methods to output HTML content because document.write is dependent on the script executing before the page has finished loading (if you call document.write after the load event, your document will be overwritten). However, I suspect that this has not yet been covered in your class. It is unfortunate, however, that they continue to teach about document.write before teaching about the better ways of outputting.

As for are you on the right track... not quite. You are storing the random numbers in arrays. For example, the value that gets stored in rand1 will be:
[x]
where x is a number from 0 - 4. Instead, you just want rand1 to hold the value (instead of holding an array that contains the value).

var rand1 = Math.floor(Math.random() * uarticle.length);

Also, the random number that is generated should ONLY be used for the array that it was generated against. For example, rand1 should only be used when selecting a value from uarticle, but you are using it to get a value from preposition. Likewise, rand2 should only be used to get a value from noun, but you're using it for uarticle as well.

A for loop works like this:

for (initialization; condition; update) {
statements
}


For your initialization, you could define 2 variables containing the values to be used for the condition. To create a loop that runs 20 times, you could do the following:

for (i = 0, n = 20; i < n; i++) {
// statements
}


That will a loop that starts at 0 and ends at 19 (so 20 iterations total). Be sure to add "var i;" and "var n;" to the beginning of the code.

Lastly, you might also consider creating a variable to hold your whitespace character, so instead of doing:

... + " " + ... + " " + ...

you would do something like this:

var space = " ";
... + space + ... + space + ...

Hope this helps. :)

harofreak00

5:13 pm on Mar 29, 2010 (gmt 0)

10+ Year Member



Thank you so much. I posted this on a few other forums and you were the only to actually explain what to do instead of just giving me the answer. I'll work through your comments and post back when I have my code finalized.

Fotiman

5:36 pm on Mar 29, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Glad to help. I look forward to your next post. :)

harofreak00

6:47 pm on Mar 29, 2010 (gmt 0)

10+ Year Member



Here is what I have:

<script type="text/javascript">
var uarticle = new Array("The", "A", "One", "Some", "Any");
var noun = new Array("boy", "girl", "dog", "town", "car");
var verb = new Array("drove", "jumped", "ran", "walked", "skipped");
var larticle = new Array("the", "a", "one", "some", "any");
var preposition = new Array("to", "from", "over", "under", "on");

for (var i = 1; i <=20; i++) {
var rand1 = Math.floor ( Math.random() * uarticle.length );
var rand2 = Math.floor ( Math.random() * noun.length );
var rand2a = Math.floor ( Math.random() * noun.length );
while (rand2 == rand2a) {rand2a = Math.floor ( Math.random() * noun.length ); }
var rand3 = Math.floor ( Math.random() * verb.length );
var rand4 = Math.floor ( Math.random() * larticle.length );
while (rand4 == rand1) {rand4 = Math.floor ( Math.random() * larticle.length ); }
var rand5 = Math.floor ( Math.random() * preposition.length );
var space = " ";

document.write(uarticle[rand2] + space + noun[rand2] + space + verb[rand3] + space + preposition[rand1] + space + larticle[rand4] + space + noun[rand2a] + ". <br>");

}
</script>

Fotiman

7:35 pm on Mar 29, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Nice. Now here is how I would change that.

1. Replace new Array with array literals. It takes up less space, and avoids the overhead of calling "new".

2. Move all of your var declarations to the top. This is a good convention to get in the habit of. Also, you're declaring the space variable each time through the loop, when it only needs to be defined once, so moving that outside of the loop would be a good improvement.

3. Your for loop is fine and will iterate 20 times. However, most developers (in my experience) tend to use the i = 0; i < 20 method instead of i = 1; i <= 20; Just an FYI.

4. You are still using an incorrect index when selecting the uarticle and preposition.

Here's what my version would look like:

<script type="text/javascript">
var i,
uarticle = ["The", "A", "One", "Some", "Any"],
noun = ["boy", "girl", "dog", "town", "car"],
verb = ["drove", "jumped", "ran", "walked", "skipped"],
larticle = ["the", "a", "one", "some", "any"],
preposition = ["to", "from", "over", "under", "on"],
rand1,
rand2,
rand2a,
rand3,
rand4,
rand5,
space = " ";
for (i = 1; i <=20; i++) {
rand1 = Math.floor ( Math.random() * uarticle.length );
rand2 = Math.floor ( Math.random() * noun.length );
rand2a = Math.floor ( Math.random() * noun.length );
while (rand2 == rand2a) {
rand2a = Math.floor ( Math.random() * noun.length );
}
rand3 = Math.floor ( Math.random() * verb.length );
rand4 = Math.floor ( Math.random() * larticle.length );
while (rand4 == rand1) {
rand4 = Math.floor ( Math.random() * larticle.length );
}
rand5 = Math.floor ( Math.random() * preposition.length );
document.write(uarticle[rand1] + // not rand2
space + noun[rand2] +
space + verb[rand3] +
space + preposition[rand5] + // not rand1
space + larticle[rand4] +
space + noun[rand2a] + ". <br>");
}
</script>

Also, the variables "rand1" - "rand5" can easily be confused. Here's the same example, but with better variable names:


<script type="text/javascript">
var i,
uarticle = ["The", "A", "One", "Some", "Any"],
noun = ["boy", "girl", "dog", "town", "car"],
verb = ["drove", "jumped", "ran", "walked", "skipped"],
larticle = ["the", "a", "one", "some", "any"],
preposition = ["to", "from", "over", "under", "on"],
uarticleIndex,
nounIndex1,
nounIndex2,
verbIndex,
larticleIndex,
prepositionIndex,
space = " ";
for (i = 1; i <=20; i++) {
uarticleIndex = Math.floor ( Math.random() * uarticle.length );
nounIndex1 = Math.floor ( Math.random() * noun.length );
nounIndex2 = Math.floor ( Math.random() * noun.length );
while (nounIndex1 == nounIndex2) {
nounIndex2 = Math.floor ( Math.random() * noun.length );
}
verbIndex = Math.floor ( Math.random() * verb.length );
larticleIndex = Math.floor ( Math.random() * larticle.length );
while (larticleIndex == uarticleIndex) {
larticleIndex = Math.floor ( Math.random() * larticle.length );
}
prepositionIndex = Math.floor ( Math.random() * preposition.length );
document.write(uarticle[uarticleIndex] +
space + noun[nounIndex1] +
space + verb[verbIndex] +
space + preposition[prepositionIndex] +
space + larticle[larticleIndex] +
space + noun[nounIndex2] + ". <br>");
}
</script>


Finally, looking at the code, there is a bit of code that repeats over and over:

x = Math.floor ( Math.random() * y );

So you might consider creating a function to encapsulate that logic, in which case you would need to pass in the y value (uarticle.length, noun.length, verb.length, etc.).