I use clock() in library to calculate excution time of a function, which is BubbleSort(..) function in my code below. But probleam is that the return execution time always = 0 (and it shows no unit, too).
This is my code:
#include <iostream>
#include <ctime>
using namespace std;
void BubbleSort(int arr[], int n)
{
for (int i = 1; i<n; i++)
for (int j = n-1; j >=i; j-- )
if (arr[j] < arr[j-1])
{
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
return;
}
int main()
{
int arr[] = {4,1,7,2,6, 17, 3, 2, 8,1};
int len = sizeof(arr)/sizeof(int);
cout << "Before Bubble Sort: \n";
for (int i=0;i<len;i++)
{
cout << arr[i] << " ";
}
clock_t start_s=clock(); // begin
BubbleSort(arr,len);
clock_t stop_s=clock(); // end
cout << "\nAfter Bubble Sort: \n";
for (int i=0;i<len;i++)
{
cout << arr[i] << " ";
}
// calculate then print out execution time - currently always returns 0 and I don't know why
cout << "\nExecution time: "<< (double)(stop_s - start_s)/CLOCKS_PER_SEC << endl;
//system("pause");
return 0;
}
I haven't known how to fix this problem yet .. So hope you guys can help me with this. Any comments would be very appreciated. Thanks so much in advanced !
As you have only a very small array, the execution time is probably much shorter than the resolution of clock(), so you either have to call the sort algorithm repeatedly or use another time source.
I modified your code as such and both start end stop have the value of 0. (ubuntu 13.10)
std::cout<<"start: "<<start_s<<std::endl;
BubbleSort(arr,len);
clock_t stop_s=clock(); // end
std::cout<<"stop: "<<stop_s<<std::endl;
you probably want something more like gettimeofday()
this http://www.daniweb.com/software-development/cpp/threads/120862/clock-always-returns-0 is an interesting discussion of the same thing. the poster concluded that clock()(on his machine) had a resolution of about 1/100 of a sec. and your code is probably ( almost certainly) running faster than that
Related
This is the problem I am working with
Using a loop and rand(), simulate a coin toss 10000 times
Calculate the difference between heads and tails.
Wrap the above two lines in another loop, which loops 1000 times.
Use an accumulator to sum up the differences
Calculate and display the average difference between the number of heads and tails.
The accumulator is not working the way I want It to? Very much a C++ Noob, for homework lol. Anyone help please?
Why am I using rand()????
second part of the assignment has us using the newer method (mt19937), just trying to tackle this bit first before moving on.
#include <iostream>
using namespace std;
int main() {
int heads = 0, tails = 0, num, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
for (int i = 0; i < 10000; i++) // COIN TOSS
{
int random = rand() % 2;
if (random == 0)
{
heads++;
}
else
{
tails++;
}
}
cout << abs((heads++ - tails++));
cin >> num;
total =+ num;
}
cout << "The average distance between is " << total / 1000 << endl;
cin.get();
return 0;
}
With your code, you never actually save the values that you need. And there's some unnecessary arithmetic that would throw off your results. This line:
cout << abs((heads++ - tails++)); increments the heads and tails variables, but they shouldn't be.
The next two lines make no sense. Why do you need to get a number from the user, and why do you add that number to your total?
Finally, this expression: total / 1000 performs integer division, which will throw off your results.
Those are the immediate issues I can spot in your code.
Next, we move on to your problem statement. What is an accumulator? To me, it sounds like you're supposed to have a class? It also reminds me of std::accumulate, but if that's what you intended, it would have said as much. Also, std::accumulate would require storing results, and that's not really necessary for this program. The code below performs the main task, i.e. it runs the necessary simulations and tracks results.
You'll notice I don't bother counting tails. The big average is also calculated as it goes since the total number of simulations is known ahead of time.
#include <cmath>
#include <iostream>
#include <random>
int flip_coin() {
static std::mt19937 prng(std::random_device{}());
static std::uniform_int_distribution<int> flip(0, 1);
return flip(prng);
}
int main() {
constexpr int tosses = 10'000;
constexpr int simulations = 1'000;
double diffAvg = 0.0;
for (int i = 0; i < simulations; ++i) {
int heads = 0;
for (int j = 0; j < tosses; ++j) {
if (flip_coin()) {
++heads;
}
}
diffAvg +=
std::abs(heads - (tosses - heads)) / static_cast<double>(simulations);
}
std::cout << "The average heads/tails diff is: " << diffAvg << '\n';
return 0;
}
What I ended up doing that seems to work for **THIS VERSION WITH RAND() (using the new method later) **
#include <iostream>
using namespace std;
int main()
{
int heads = 0, tails = 0, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
{
for (int i = 0; i < 10000; ++i) // COIN TOSS
if (rand() % 2 == 0)
++heads;
else
++tails;
total += abs(heads - tails);
}
}
cout << "The average distance between is " << total / 1000.0 << '\n';
cin.get();
return 0;
}
I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;
int recursiveMinimum(vector<int>, int, int);
void main() {
cout << "How many values do you want your vector to be? ";
cin >> vectorSize;
cout << endl;
vector<int> searchVector(vectorSize);
start = 0;
ending = searchVector.size() - 1;
for (int i = 0; i < vectorSize; i++) {
cout << "Enter value for position " << i << " " << endl;
cin >> searchVector[i];
}
for (int x = 0; x < vectorSize; x++) {
cout << searchVector[x] << " ";
}
int answer = recursiveMinimum(searchVector, start, ending);
cout << "The smallest value in the vector is: " << answer;
_getch();
}
int recursiveMinimum(vector<int> searchVector, int start, int end) {
if (start < end) {
if (searchVector[start] < minimum) {
minimum = searchVector[start]; //this part seems to not work
}
start++;
recursiveMinimum(searchVector, start, end);
}
else {
return minimum;
}
}
`
Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);
Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].
So, ultimately, your code should look like this:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1
While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:
start++;
return recursiveMinimum(searchVector, start, end);
The main issue is that you do not initialise minimum. Hence, comparison searchVector[start] < minimum might never become true, and minimum remains uninitialized.
As a quick fix, write int minimum = MAX_INT; instead of int minimum;. MAX_INT is the maximum positive integer value (defined in limits.h). So the values in your array will never be greater that this value, and your minimum search loop will work (unless there are other issues; but for that, please consult the debugger :-) )
Having a problem with my quicksort algorithm. The code compiles without any errors, but when I try to run the program the only output I get is "The random numbers are: " and then acts like it wants input from the user, and then I have to kill the program. Now when I remove the call for my quicksort function in my main program, the program prints out the numbers, but doesn't work with the call for quicksort function. I'm not sure if the parameters I'm using are the issue or if it's the function itself.
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <stack>
#include <queue>
using namespace std;
void quicksort(int arr[], int left, int right) {
int l = left;
int r = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (l <= r) {
while (arr[l] < pivot)
l++;
while (arr[l] > pivot)
r--;
if (l <= r) {
tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
l++;
r--;
}
}
if (left < r)
quicksort(arr, left, r);
if (l < right)
quicksort(arr, r, right);
}
int main() {
int n = 20;
int testlist[n];
for (int i = 0; i<n; i++) {
testlist[i] = rand()%100;
}
cout << "The random numbers are: " << endl;
for (int i = 0; i < n; i++) cout << testlist[i] << " ";
quicksort(testlist, 0, n - 1);
cout << " " << endl;
cout << "The sorted numbers are: " << endl;
for (int i = 0; i < n; i++) {
cout << testlist[i] << " ";
}
return 0;
}
You have an infinite loop in your quicksort function. As this function never returns, nothing after the "The random numbers are:" line is printed, as the quicksort call never returns. The random numbers themselves may or may not print (and do print on my system) as the system is not guaranteed to flush the output buffer to the screen immediately. (They probably would be printed if you wrote a std::endl to cout after the for loop that prints the numbers.)
I suspect this is the problem:
while (arr[l] > pivot)
r--;
That statement while (arr[l] > pivot) should probably actually be while (arr[r] > pivot).
This happens because something goes wrong inside quicksort() and you print the numbers without an std::endl!
You see, without the std::endl, the numbers are written in the output buffer, but they are not flushed. They will, eventually, without the std::endl, but that your code doesn't make it to that time.
Pro tip: Always use std::endl when you debug your code!
I won't debug your quicksort(), since you should do that, in order to practice! If you need a reference, you can always use my baby example: Quicksort (C++), which is written in a c-like way, so that people from both c and c++ can easily follow! :)
Hunch: You use recursion, your program doesn't terminate...Infinite loop may be the cause... ;)
BTW, if I were you and didn't have any important reason to use:
#if __INCLUDE_LEVEL__ < 1
I would discard that (along with the accompanied #endif).
My homework program has to write random numbers for arrival time and burst time into a file. Then after they are written, it reads the file and sorts the contents.
I figured setting up a 2d array would be the easiest way for me to go about this. But I am unsure on how to implement my sort so that if an arrival time swaps places then burst time of that arrival goes along for the ride.
I feel like I worded that poorly, but a basic example would be:
array[3][10] > array[2][23]
So since second array has an earlier arrival time I need both its arrival 2 and its burst 23 to move before array[3][10], but I need this do that and compare 100 inputs.
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
const int max = 100;
using namespace std;
int main()
{
multimap<int [][]> myMap;
int randomBurst[max];
int arrivalTime[max];
int line[max][2];
int first = 0;
for (int i = 0; i < 100; i++)
{
if (i < 100)
{
ofstream write("Schedule.txt", ios::app);
randomBurst[i] = rand() % 1000;
arrivalTime[i] = rand() % 1000;
write << arrivalTime[i] << " " << randomBurst[i] << endl;
}
}
ifstream read("Schedule.txt");
for (int i = 0; i <= max; i++)
{
for (int j = 0; j < 2; j++)
{
read >> line[i][j];
cout << line[i][j] << " " ;
}
cout << endl;
}
cout << endl;
cout << endl;
for (int i = 0; i <= max; i++)
{
for (int j = 0; j < 2; j++)
{
myMap.insert(pair<int[][]>(line[i][j]);
}
cout << endl;
}
system("pause");
return 0;
}
My code sets up my array correctly after it reads the written file content, but I'm kind of lost what I should implement for a sort.
Well coming forward with this, mainly left that comment to be able to find this question faster on my laptop.
Like I said in the comment, if you want a presorted, by key value 2D "array", the quickest manner in which you could do this is with the map container., and if you really need the internal points to be ordered, and you will be using multiple entries within it, lets say entries 2,30 2,12 ... You could either build a map of vectors, or arrays, or use a Multimap. Not too sure of this data structure, as I have never really had a reason to use it as of yet. Referenced here http://www.cplusplus.com/reference/map/multimap/
The above will provide you with the sorting done for you, and the reason why I recommended a vector is the lack of order within it, and not sure if the 'bursts?' are to be ordered as well.
EDIT:
Forgot to mention, that a map will not hold more than one key of any given value, so if you are, again, inputting multiple points a above, then you will. if implementing things as you were before, overwrite things.
EDIT:
So this is more or less the fix I think I have, but you are working around this in a very indirect manner, that is hard to follow honestly.
#include <map>
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
using namespace std;
const int MAX = 100;
int main()
{
multimap<int,int> myMap;
int randomBurst[100];
int arrivalTime[100];
int line[100][2];
int first = 0;
for (int i = 0; i < 100; i++)
{
if (i < 100)
{
ofstream write("Schedule.txt", ios::app);
randomBurst[i] = rand() % 1000;
arrivalTime[i] = rand() % 1000;
write << arrivalTime[i] << " " << randomBurst[i] << endl;
}
}
ifstream read("Schedule.txt");
for (int i = 0; i <= 100; i++)
{
for (int j = 0; j < 2; j++)
{
read >> line[i][j];
cout << line[i][j] << " " ;
}
cout << endl;
}
// cout << endl;
// cout << endl;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 2; j++)
{
//Attain the value in the index, and the held value within it.
myMap.insert(pair<int, int> (line[i][j], line[i][j]));
}
cout << endl;
}
// system("pause");
return 0;
This fixes the insertion point, just because you give it an array it does not mean that the program will take that as a pair, as the first index is a point to another array in itself. And so on. I recommend starting off wiht a map object instead, as the multimap makes things a bit annoying, if you are familiar with the vector containers then use that instead within the map to log multiple values.
I am having a hard time with translating this pseudocode into C++. The goal is to generate random numbers into A[] and sort them using insertion sort then get the execution time in milliseconds. Insertion sort would run for m=5 times. Each n value should be 100, 200, 300,....,1000. So for example if n=100 then that would run 5 times with 5 different sets of random numbers, then do the same thing for n=200, etc...
I have already written my insertion sort and that works so I did not include it. I am really just having trouble translating this pseudocode into something I can work with. I included my attempt and the pseudocode so you can compare.
Pseudocode:
main()
//generate elements using rand()
for i=1 to 5
for j=1 to 1000
A[i,j] = rand()
//insertion sort
for (i=1; i<=5; i=i+1)
for (n=100; n<=1000; n=n+100)
B[1..n] = A[i,n]
t1 = time()
insertionSort(B,n)
t2 = time()
t_insort[i,n] = t2-t1
//compute the avg time
for (n=100; n<=1000; n=n+100)
avgt_insort[n] = (t_insort[1,n]+t_insort[2,n]+t_insort[3,n]+...+t_insort[5,n]+)/5
//plot graph with avgt_insort
This is my attempt:
I am confused with t_insort and avgt_insort, I did not write them to C++. Do I make these into new arrays? Also take I am not sure if I am doing my time correctly either. I am sorta new at this running time thing so I have never actually wrote it into code yet.
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
int A[100];
for(int i=1; i<=5; i++)
{
for(int j=1; j<=1000; j++)
{
A[i,j] = rand();
}
}
for(int i=0;i<=5; i++)
{
for(int n=100; n<=1000; n=n+100)
{
static int *B = new int[n];
B[n] = A[i,n];
cout << "\nLength\t: " << n << '\n';
long int t1 = clock();
insertionSort(B, n);
long int t2 = clock();
//t_insort
cout << "Insertion Sort\t: " << (t2 - t1) << " ms.\n";
}
}
for(int n=100; n<=1000; n=n+100)
{
//avt_insort[n]
}
return 0;
}
The pseudocode is relatively close to a C++ code with some syntactic changes. Note that this C++ code is a straightforward "translation". A better solution would be to use containers from C++ standard library.
int main()
{
int A[6][1001], B[1001]; //C++ starts indexing from 0
double t_insort[6][1000]; //should be of return type of time(), so maybe not double
int i,j,n;
for( i=1;i<=5;i++) //in C++ it is more common to start from 0 for(i=0;i<5;i++)
for(j=1;j<=1000;j++)
A[i][j] = rand(); //one has to include appropriate header file with rand()
//or to define his/her own function
for (i=1; i<=5; i++)
for (n=100; n<=1000; n=n+100)
{
B[n]=A[i][n];
t1 = time(); //one has firstly to declare t1 to be return type of time() function
insertionSort(B,n); //also this function has to be defined before
t2=time();
t_insort[i][n]=t2-t1; //this may be necessary to change depending on exact return type of time()
}
}
for (n=100; n<=1000; n=n+100)
for(i=1;i<=5;i++)
avgt_insort[n] += t_insort[i][n]
avgt_insort[n]/=5;
//plot graph with avgt_insort
A[i,j] is the same as A[j] (comma operator!), and wouldn't work.
You might want to declare a two dimensional array for A or even better an appropriate std::array:
int A[100][1000];
std::array<std::array<int,1000>, 100> A; // <- prefer this for c++
Also allocating B right away inside the for loop doesn't look right:
static int *B = new int[n];
and
B[n] = A[i,n];
won't work either as you intend (see above!).