Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. /* Copyright (C) 1999 Lucent Technologies */
  2. /* Excerpted from 'The Practice of Programming' */
  3. /* by Brian W. Kernighan and Rob Pike */
  4.  
  5. #include <time.h>
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <string>
  9. #include <deque>
  10. #include <map>
  11. #include <vector>
  12. #include <fstream>
  13.  
  14. using namespace std;
  15.  
  16. const int NPREF = 2;
  17. const char NONWORD[] = "\n"; // cannot appear as real line: we remove newlines
  18. const int MAXGEN = 10000; // maximum words generated
  19.  
  20. typedef deque<string> Prefix;
  21.  
  22. map<Prefix, vector<string> > statetab; // prefix -> suffixes
  23.  
  24. void build(Prefix&, istream&);
  25. void generate(int nwords, int a[]);
  26. void add(Prefix&, const string&);
  27.  
  28. // markov main: markov-chain random text generation
  29. int main(void)
  30. {
  31. int nwords = MAXGEN;
  32. Prefix prefix; // current input prefix
  33.  
  34. ifstream fin("rands.txt");
  35. string line;
  36. int a[MAXGEN];
  37. int i=0;
  38.  
  39. while(getline(fin, line))
  40. {
  41. int value = atoi(line.c_str());
  42.  
  43. a[i] = value;
  44. i++;
  45. }
  46.  
  47. for (int i = 0; i < NPREF; i++)
  48. add(prefix, NONWORD);
  49. build(prefix, cin);
  50. add(prefix, NONWORD);
  51. generate(nwords, a);
  52. return 0;
  53. }
  54.  
  55. // build: read input words, build state table
  56. void build(Prefix& prefix, istream& in)
  57. {
  58. string buf;
  59.  
  60. while (in >> buf)
  61. add(prefix, buf);
  62. }
  63.  
  64. // add: add word to suffix deque, update prefix
  65. void add(Prefix& prefix, const string& s)
  66. {
  67. if (prefix.size() == NPREF) {
  68. statetab[prefix].push_back(s);
  69. prefix.pop_front();
  70. }
  71. prefix.push_back(s);
  72. }
  73.  
  74. // generate: produce output, one word per line
  75. void generate(int nwords, int a[])
  76. {
  77. Prefix prefix;
  78.  
  79. for (int i = 0; i < NPREF; i++)
  80. add(prefix, NONWORD);
  81.  
  82. for (int i = 0; i < nwords; i++) {
  83. vector<string>& suf = statetab[prefix];
  84. const string& w = suf[(a[i])%suf.size()];
  85. if (w == NONWORD)
  86. break;
  87. cout << w << "\n";
  88. prefix.pop_front(); // advance
  89. prefix.push_back(w);
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement