-1
// An efficient program to randomly select a number from stream of numbers.
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <time.h>

/* A program to randomly select a item from stream[0], stream[1], ..
stream[i-1]*/


int main()
{
    int stream[] = { 1, 2, 3, 4 };
    int n = sizeof(stream) / sizeof(stream[0]);

    // Use a different seed value for every run.
    srand(time(0));
    cout << "Random no. selected: " << stream[(rand() % n)] << "\n";
    return 0;
}

The above C++ code requires memory ranging from 2.9...(something) MB or greater, to 3.04..(something) MB or greater.

And consider the following C code:

/* An efficient program to randomly select a number from
stream of numbers.*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* A function to randomly select a item from stream[0], stream[1], .. 
stream[i - 1]*/
int selectRandom(int x)
{
    static int res;    // The resultant random number
    static int count = 0;  //Count of numbers visited so far in stream

    count++;  // increment count of numbers seen so far

              // If this is the first element from stream, return it
    if (count == 1)
        res = x;

    else
    {
        // Generate a random number from 0 to count - 1
        int i = rand() % count;

        // Replace the prev random number with new number with 1/count 
        //probability
        if (i == count - 1)
            res = x;
    }
    return res;
}

// Driver program to test above function.
int main()
{
    int stream[] = { 1, 2, 3, 4 };
    int n = sizeof(stream) / sizeof(stream[0]);

    // Use a different seed value for every run.
    srand(time(NULL));
    for (int i = 0; i < n; ++i)
        printf("Random number from first %d numbers is %d \n",
            i + 1, selectRandom(stream[i]));
    return 0;
}

The above code, requires memory in the range 1.28..(something) MB or greater but surely less than 2MB.

My question is, why does the first program takes more space than the second one, and how?

scoder
  • 3
  • 5

1 Answers1

-1

Using your provided online editor the memory usage doesn't seem to correspond to actual allocations. If I write a program with malloc(1); the "memory" stat is the same as doing malloc(10000000);. I'm led to believe this stat is just the size of the executable.

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • Thanks for the answer, Yes I checked the same,but found that the use of malloc shows reduced size sometimes than, when it wasn't used....couldn't understand why? – scoder Aug 06 '17 at 06:28