This exercise covers reproducible simulation, with extension to discrete-time Markov chains.
- Simulate
100coin flips of a fair-sided coin and determine the longest streak of heads and the longest streak of tails. - Simulate
100coin flips of an unfair coin, where the probability of getting heads is0.7and the probability of getting tails is0.3. Determine the longest streak of heads and the longest streak of tails.
-
Given the following initial probability
arrayand transition probabilitymatrix, simulate the first100steps of a discrete-time Markov chain.var initial = [ 0.2, 0.8 ]; // sums to unity var transition = [ [ 0.3, 0.7 ], // sums to unity [ 0.4, 0.6 ] // sums to unity ];
The output should be a
101element state vector; e.g.,[1,1,0,1,0,0,0,1,1,...], where the first element is the initial state. -
As a bonus, extend the simulation to
5states and1000steps and plot the state vector.
-
Download and process a training corpus.
-
Download a full plain text copy of Moby Dick from Project Gutenberg.
-
Remove the front matter before
Chapter 1, and remove the end matter after theEpilogue. -
Replace all tab characters with a single space.
-
Replace all newline characters (and trailing spaces) with a single space.
-
Replace multiple spaces with a single space.
-
Split the text into separate "words" using a single space as the delimiter.
-
Write the word list to file.
-
Build a database (dictionary) where each key is a pair of consecutive words and the key value is an
arrayof words which follow the key pair. For example, given the phrase "The quick brown fox jumped over the lazy cat.", the database would bevar dict = { 'The quick': ['brown'], 'quick brown': ['fox'], 'brown fox': ['jumped'], 'fox jumped': ['over'], 'jumped over': ['the'], 'over the': ['lazy'], 'the lazy': ['cat.'] };
-
Write the database to file as JSON.
-
-
Using the database and word list from above, create a function to generate text having a maximum word length of
25. Hints:- First seed the text generator with two words from the word list.
- Look up the list of possible third words in the database and randomly pick one of them.
- Next, use the second and third words to find a fourth word, and so on and so forth.
- Stop once you have generated the desired number of words.
-
Use
123456to seed randu, thus allowing comparison with solution results. -
When processing the training corpus, consider using streams (e.g., split, join, and transform) for efficient processing.
-
To select a random element from a list,
var randu = require( '@stdlib/math/base/random/randu' ); var floor = require( '@stdlib/math/base/random/floor' ); var list = [ 1, 2, 3, 4, 5 ]; // Generate a random index: var i = floor( randu()*list.length ); // Grab a random element: var el = list[ i ];
Assuming that each solution is placed in a separate file,
$ node ./path/to/<solution_1>.js
$ node ./path/to/<solution_2>.js
# ...When all your solutions succeed, proceed to the next exercise.