Simple, but very robust Mad Libs algoritm


/ Published in: ActionScript 3
Save to your folder(s)

This is very simple script, you can add ass meny items and arrays as you want. You can change the separator and/or enging of the sentance. It can be very easily modified to work with external XML files


Copy this code and paste it in your HTML
  1. var sentance:Array = [
  2. ["Name 1", "Name 2", "Name 3", "Name 4", "Name 5"],
  3. ["and", "without", "and somehow", "and his twin sister"],
  4. ["Girl name 1", "Girl name 2", "Girl name 3", "Girl name 4"],
  5. ["went ot school", "passed the exams", "went on vacation", "voted for Obama"]
  6. ]
  7.  
  8. var finalString:String = "";
  9. var separator:String = " ";
  10. var end:String = ".";
  11. for(var i:Number = 0; i< sentance.length; i++){
  12. finalString += String(sentance[i][Number( Math.ceil( Math.random()*sentance[i].length-1 ))] + separator);
  13. }
  14.  
  15. finalString = finalString.slice(0, finalString.lastIndexOf(separator)) + end;
  16.  
  17. trace(finalString); //output: Name 2 and somehow Girl name 4 voted for Obama.
  18. //or output: Name 3 and his twin sister Girl name 1 passed the exams.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.