Question

How can I write this code (posted below) using vectors instead of arrays? This is the...

How can I write this code (posted below) using vectors instead of arrays?

This is the task I have and the code below is for Task 1.3:

Generate twenty random permutations of the number 0, 1, 2, ..., 9 using of the algorithms you designed for Task 1.3. Store these permutations into a vector and print them to the screen with the additional information of unchanged positions and number of calls torand(). Calculate the total numbers of unchanged positions. Compare the outcomes of two approaches of random permutation generation.

#include <iostream>

#define SIZE 10

using namespace std;

//O(n^2) = Quadratic time

//Nested Loop

//More operations involved so time execution is longer

int methodOne(int a[]) { //function to randomly insert 0 to 9 into an array

  

int count = 0; //variable to count number of times rand() is used

for(int i = 0; i < SIZE; i++){ //We run a loop for every number to be entered into the array

bool flag = false;

int pos=-1;

while(!flag) {//we run for loop till a new number is generated

flag = true;

pos = rand() % 10;

count++;

for(int j = 0; j < SIZE; j++){

if(a[j] == pos)

flag = false;

}

}

a[i] = pos; //entering the number into the array

}

return count; //returning number of times rand() was called

}

//O(n) = Linear time

//When an algorithm accepts n input size, it would perform n operations as well.

//less operations = less execution time

int methodTwo(int a[]) { //function to randomly insert 0 to 9 into an array

  

int count=0; //variable to count number of times rand() is used

for(int i=0;i<SIZE;i++){

int pos=-1;

while(a[pos] != -1) { //running loop till an unoccupied position is found

  

pos = rand()%10;

count++;

}

a[pos] = i; //entering the number into the array

}

return count; //returning number of times rand() was called

}

int main() {

srand(static_cast<unsigned int>(time(nullptr)));

int a[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; //filling the array with random numbers

int count=methodOne(a);

cout<< "First Approach: "<< endl;

for (int i : a) {

cout << i << " ";

}

cout<< endl;

cout<< "Calls to rand() function: "<< count << endl;

cout<< endl;

int b[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};

count = methodTwo(b);

cout<< "Second Approach: "<< endl;

for (int i : b) {

cout << i << " ";

}

cout<< endl;

cout<< "Calls to rand() function: "<< count << endl;

  

int unchangedPos = 0;

cout << "Total number of unchanged position is: ";

for (int i = 0; i < SIZE; ++i) {

if (a[i] == b[i]) { // check if a[i] == b[i] if yes then increment unchangedPos

unchangedPos++;

}

}

cout << unchangedPos << endl;

  

return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>
#include <bits/stdc++.h>
#include <vector>
#define SIZE 10

using namespace std;

//O(n^2) = Quadratic time

//Nested Loop

//More operations involved so time execution is longer

int methodOne(vector<int> &a) //function to randomly insert 0 to 9 into an array
{

int count = 0; //variable to count number of times rand() is used

for(int i = 0; i < SIZE; i++) //We run a loop for every number to be entered into the array
{

bool flag = false;

int pos=-1;

while(!flag) //we run for loop till a new number is generated
{

flag = true;

pos = rand() % 10;

count++;

for(int j = 0; j < SIZE; j++)
{

if(a[j] == pos)

flag = false;

}

}

a[i] = pos; //entering the number into the array

}

return count; //returning number of times rand() was called

}

//O(n) = Linear time

//When an algorithm accepts n input size, it would perform n operations as well.

//less operations = less execution time

int methodTwo(vector<int> &a) //function to randomly insert 0 to 9 into an array
{

int count=0; //variable to count number of times rand() is used

for(int i=0; i<SIZE; i++)
{

int pos=-1;

while(a[pos] != -1) //running loop till an unoccupied position is found
{

pos = rand()%10;

count++;

}

a[pos] = i; //entering the number into the array

}

return count; //returning number of times rand() was called

}

int main()
{
vector<int> c;
vector<int> d;

srand(static_cast<unsigned int>(time(0)));

for(int i=0; i<SIZE; i++) //filling the array with random numbers
c.push_back(-1);
int count=methodOne(c);

cout<< "First Approach: "<< endl;

for (int i=0; i<10; i++)
{

cout << c[i] << " ";

}

cout<< endl;

cout<< "Calls to rand() function: "<< count << endl;

cout<< endl;

for(int i=0; i<SIZE; i++) //filling the array with random numbers
d.push_back(-1);

count = methodTwo(d);

cout<< "Second Approach: "<< endl;

for (int i=0; i<10; i++)
{

cout << d[i] << " ";

}


cout<< endl;

cout<< "Calls to rand() function: "<< count << endl;

int unchangedPos = 0;

cout << "Total number of unchanged position is: ";

for (int i = 0; i < SIZE; ++i)
{

if (c[i] == d[i]) // check if a[i] == b[i] if yes then increment unchangedPos
{

unchangedPos++;

}

}

cout << unchangedPos << endl;

return 0;
}

Add a comment
Know the answer?
Add Answer to:
How can I write this code (posted below) using vectors instead of arrays? This is the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can you fix this program and run an output for me. I'm using C++ #include using...

    Can you fix this program and run an output for me. I'm using C++ #include using namespace std; //function to calculate number of unique digit in a number and retun it int countUniqueDigit(int input) {    int uniqueDigitCount = 0;    int storeDigit = 0;    int digit = 0;    while (input > 0) {        digit = 1 << (input % 10);        if (!(storeDigit & digit)) {            storeDigit |= digit;       ...

  • howthe   output   of   the   following   4   program segments (a)    const int SIZE=8;    int values[SIZE]...

    howthe   output   of   the   following   4   program segments (a)    const int SIZE=8;    int values[SIZE] = {10, 10, 14, 16, 6, 25, 5, 8};    int index;    index=0;    res = values[index];    for (int j=1; j<SIZE; j++)    {        if (values[j] > res)        {            res = values[j];            index = j;        cout << index << res << endl;        }    }    cout <<...

  • DO NOT use for loop and while loop Goal: Learn how to use recursive functions. General...

    DO NOT use for loop and while loop Goal: Learn how to use recursive functions. General requirement: Use cout to fully demonstrate your works for all tasks. The output must clearly show how each of these functions work. If no output is displayed for a task below, 0 point will be given to the task. If the output is not clear, some points may be deducted.    Task 1 – Reverse array (3 pts) Given an integer array like: const...

  • I need to update this C++ code according to these instructions. The team name should be...

    I need to update this C++ code according to these instructions. The team name should be "Scooterbacks". I appreciate any help! Here is my code: #include <iostream> #include <string> #include <fstream> using namespace std; void menu(); int loadFile(string file,string names[],int jNo[],string pos[],int scores[]); string lowestScorer(string names[],int scores[],int size); string highestScorer(string names[],int scores[],int size); void searchByName(string names[],int jNo[],string pos[],int scores[],int size); int totalPoints(int scores[],int size); void sortByName(string names[],int jNo[],string pos[],int scores[],int size); void displayToScreen(string names[],int jNo[],string pos[],int scores[],int size); void writeToFile(string...

  • // PLACE YOUR NAME HERE #include <iostream> using namespace std; float findAverage (int [], int); //...

    // PLACE YOUR NAME HERE #include <iostream> using namespace std; float findAverage (int [], int); // finds average of all //grades int findHighest (int [], int); // finds highest of all //grades int findFirstFail( int[]); int main() { int grades[100]; // the array holding 100 grades. int numberOfGrades; // the number of grades read. int pos; // index to the array. float avgOfGrades; // contains the average of the grades. int highestGrade; // contains the highest grade. int inderOfFail; //...

  • Modify PartTwo.cpp so that it is uses a vector, named vect, instead of an array. PartTwo.cpp...

    Modify PartTwo.cpp so that it is uses a vector, named vect, instead of an array. PartTwo.cpp Is posted here: // This program reads data from a file into an array. Then, it // asks the user for a number. It then compares the user number to // each element in the array, displays the array element if it is larger. // After looking at entire array, it displays the number of elements in the array larger // than the user...

  • Convert the TreeArray C++ source code(posted below) into a BinaryTree, using this TreeNode definition: class TreeNode<T>...

    Convert the TreeArray C++ source code(posted below) into a BinaryTree, using this TreeNode definition: class TreeNode<T>       T data       TreeNode<T> left       TreeNode<T> right Since this TreeNode is a generic Template, use any data file we've used this quarter to store the data in the BinaryTree. To do this will likely require writing a compare function or operator. Hint: Think LEFT if the index is calculate (2n+1) and RIGHT if index is (2n+2). Source code: #include<iostream> using namespace std;...

  • I need help of how to include the merge sort code into this counter code found...

    I need help of how to include the merge sort code into this counter code found below: #include<iostream> using namespace std; int bubble_counter=0,selection_counter=0; // variables global void bubble_sort(int [], int); void show_array(int [],int); void selectionsort(int [], int ); int main() { int a[7]={4,1,7,2,9,0,3}; show_array(a,7); //bubble_sort(a,7); selectionsort(a,7); show_array(a,7); cout<<"Bubble counter = "<<bubble_counter<<endl; cout<<"Selection Counter = "<<selection_counter<<endl; return 0; } void show_array(int array[],int size) { for( int i=0 ; i<size; i++) { cout<<array[i]<< " "; } cout<<endl; } void bubble_sort( int array[],...

  • REWRITE the code below and declare a class that holds an array of 10. Create a...

    REWRITE the code below and declare a class that holds an array of 10. Create a constructor that initializes the array with random integers 1 and 100. Write a member function to show the entire array and another to sort the array. Rewrite with instruction above: //Exchange Sort Function for Descending Order void ExchangeSort(vector<int> &num) {      int i, j;      int temp;   // holding variable      int numLength = num.size();      for (i=0; i< (numLength -1); i++)       {...

  • I want to compare the runtimes and swap operations times among quick Sort, selection Sort and...

    I want to compare the runtimes and swap operations times among quick Sort, selection Sort and shell Sort here is my code: But when I create a 1000,000 size array, I can't get the result of the operations times and runtime. what's wrong with my code? and I also want to copy the array. Because I want to use same array for three sort. And for the shell Sort, I haven't learn it in my class. Can anyone help me...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT