Guest User

Untitled

a guest
Jul 17th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. <script>
  2.  
  3. function randInt(low_bound_inclusive, high_bound_inclusive) {
  4. var range = high_bound_inclusive - low_bound_inclusive;
  5. var r = Math.random();
  6. r = r * range;
  7. r = r + low_bound_inclusive;
  8. r = Math.round(r);
  9. return r;
  10. }
  11.  
  12.  
  13.  
  14. proper_nouns = [
  15. 'John',
  16. 'Mary'
  17. ];
  18.  
  19. nominals = [
  20. 'fish',
  21. 'cat',
  22. 'dog',
  23. 'zebra',
  24. 'horse',
  25. 'donkey',
  26. 'giraffe',
  27. 'walrus',
  28. ];
  29.  
  30. determiners = [
  31. 'the',
  32. 'a',
  33. ];
  34.  
  35. past_tense_verbs = [
  36. 'ate',
  37. 'dragged in',
  38. 'befriended',
  39. 'saluted',
  40. ];
  41.  
  42. // cfg maps between a non-terminal symbol and the list of expansions it can have
  43. cfg = {
  44. 'S': ['NP VP'],
  45. 'NP': ['DN', 'PN'],
  46. 'DN': ['DET N', 'DET N that NP V'],
  47. 'PN': proper_nouns,
  48. 'VP': ['V NP'],
  49. 'V': past_tense_verbs,
  50. 'DET': determiners,
  51. 'N': nominals,
  52. }
  53. var nonterminals = [
  54. 'S',
  55. 'PN',
  56. 'VP',
  57. 'V',
  58. 'NP',
  59. 'DET',
  60. 'N',
  61. 'DN',
  62. ];
  63.  
  64.  
  65. function generate(g) {
  66. var tokens = g.split(' ');
  67. for (var i = 0; i < tokens.length; i++) { var token = tokens[i];
  68. for (var j = 0; j < nonterminals.length; j++) {
  69. var nonterminal = nonterminals[j];
  70. if (token === nonterminal) {
  71. // select one of the possible expansions of token to use
  72. var expansions = cfg[nonterminal];
  73. var expansion = expansions[randInt(0, expansions.length-1)];
  74.  
  75. // now replace this instance of token with a recursive expansion of its expansion
  76. g = g.replace(token, generate(expansion));
  77. break;
  78. }
  79. }
  80. // if no nonterminal matched, then token was a terminal symbol
  81. }
  82. // all nonterminal symbols have been replaced by terminal ones
  83. return g;
  84. }
  85.  
  86. document.writeln('<ul>');
  87. for (var i = 0; i < 5; i++) {
  88. var sentence = generate('S');
  89. document.writeln('<li>' + sentence + '</li>');
  90. }
  91. document.writeln('</ul>');
  92. </script>
Add Comment
Please, Sign In to add comment