/**************************************************************** **** **** This file belongs with the course **** Introduction to Scientific Programming in C++/Fortran2003 **** copyright 2017-2023 Victor Eijkhout eijkhout@tacc.utexas.edu **** **** adjacent2.cxx : adjacency matrix implementation, sparse **** ****************************************************************/ #include using std::cin; using std::cout; #include using std::vector; class AdjacencyMatrix { private: vector< vector > pages; public: AdjacencyMatrix(int size) { pages = vector>(size); }; //! Add a page by setting the corresponding boolean. //! This models a link from page i to page j. void addpage(int i,int j) { // test whether i,j already exists pages.at(i).push_back(j); }; //! Count the number of links from a page. int number_of_outlinks(int page) { return pages.at(page).size(); }; //! Given a probability vector, compute a new vector vector transition( vector state ) { // basic compatibility checking int n = state.size(); if (n!=pages.size()) { cout << "State vector has length " << n << "; incompatible with matrix of size " << pages.size() << '\n'; throw(1); } vector newstate(n,0.); for (int page=0; page0) { // if we are on page `page' float probability_per_link = 1./number_of_outlinks(page); float probability_for_page = state.at(page); for ( auto link : pages.at(page) ) { // (int link=0; link probability_vector(number_of_pages,0.), new_probability; { int random_page = number_of_pages * ( (float)rand() )/RAND_MAX; probability_vector.at(random_page) = 1.; } // now do a number of transition steps for (int step=0; step <5; ++step) { cout << "Step " << step << '\n'; int page; for (page=0; page0) { new_probability = web.transition(probability_vector); float sum_of_probabilities{0}; int count{0}; for ( auto p : new_probability ) { sum_of_probabilities += p; ++count ; } cout << "On page " << page << ", sum of " << count << " outgoing probabilities=" << sum_of_probabilities << '\n'; } } cout << '\n'; } return 0; }