Question #100127

1. Generate N>10 random values from 1 to 100 using a uniform probability distribution. N is entered by the user. The first 5 values are put into nodes and added to a priority queue based on their value. Each node also contains a list of values. After the first 5 are inserted into the priority queue the rest of the values are added to the lists with the initial node being the delimiter as the maximum value. This defines an interval from the previous node to that value. The range for the first value is 1 to is value Display the contents of the Priority Queue as below:


For example if the values were

5, 55, 22, 14, 98, 23, 99, 40, 7, 55, 25, 9, 66


The PQueue would have interval nodes 5, 14, 22, 55, 98 the entire contents would be


Node 5 has NO entries

Node 14 has values 7, 9 (( values greater than 5 but <= 14))

Node 22 has NO values

Node 55 has value 23, 55

Node 98 has value 66


The value 99 does not appear since it does fall within any of the intervals

Expert's answer

#include <iostream>

#include <random>

#include <queue>

#include <list>




using namespace std;







struct Node

{

  int nodeVal;

  list<int> valuesInRange;

};







int main()

{

  default_random_engine generator;

  int a = 0, b = 100;

  uniform_int_distribution<int> distribution(a, b);

  int N;

  cout << "Enter the N(more than 10): ";

  cin >> N;

  int i;

  int values[N];

  Node nodes[5];

  priority_queue<Node> myQ;

  for(i = 0; i < N; i++)

  {

    values[i] = distribution(generator);

    if(i < 5)

    {

      nodes[i].nodeVal = values[i];

      myQ.push(nodes[i]);

    }

  }

  for(i = 0; i < 5; i++)

  {

    nodes[i] = myQ.top();

    myQ.pop();

  }

  int j;

  for(j = 5; j < N; j++)

  {

    if(values[j] <= nodes[0].nodeVal)

      nodes[0].valuesInRange.push_back(values[j]);

    else if(values[j] > nodes[0].nodeVal && values[j] <= nodes[1].nodeVal)

      nodes[1].valuesInRange.push_back(values[j]);

    else if(values[j] > nodes[1].nodeVal && values[j] <= nodes[2].nodeVal)

      nodes[2].valuesInRange.push_back(values[j]);

    else if(values[j] > nodes[2].nodeVal && values[j] <= nodes[3].nodeVal)

      nodes[3].valuesInRange.push_back(values[j]);

    else if(values[j] > nodes[3].nodeVal && values[j] <= nodes[4].nodeVal)

      nodes[4].valuesInRange.push_back(values[j]);

  }




  return 0;

}
LATEST TUTORIALS
APPROVED BY CLIENTS