Question

You can help me with a different program. .. It introduces a range of numbers (no limit, you can repeat numbers) in which to display how many times each digit entered in.. Ex: 1 3 4 3 3 6 1 Result: 1-2x 3-3x 4-1x 6-1x

Thanks nice.

#include <iostream>
#include <cstdlib>
using namespace std;
int rnd()
{
    int iRand = (rand() % 100) + 1;
}

int hundred_random()
{
    for (int rCount=0; rCount < 100; ++rCount)
    {
        cout << rnd() << endl;
    }
}

int main()
{
    cout << " The list of Hundred random numbers are- " << endl;
    hundred_random();
    return 0;
}
Was it helpful?

Solution

In order to count how often each number occurs in a list of numbers, you can do the following:

#include <iostream>
#include <vector>
#include <map>
#include <cstdlib>

We need these headers for output, storing the numbers, storing the count, and rand() for generating the example.

std::vector<int> generate_numbers(int amount, int max_num)
{
    std::vector<int> numbers(amount);
    for (int i = 0; i < amount; ++i) {
        numbers[i] = rand() % max_num + 1;
    }
    return numbers;
}

A helper method to generate a bunch of random numbers.

std::map<int, int> count_numbers(const std::vector<int> &numbers)
{
    // Count numbers
    std::map<int, int> counts; // We will store the count in a map for fast lookup (C++11's unordered_map has even faster lookup)
    for (size_t i = 0; i < numbers.size(); ++i) { // For each number
        counts[numbers[i]]++; // Add 1 to its count
    }
    return counts;
}

The above method does the counting, which is the essence of your question. For each number that we encounter, we increment its count.

void print_counts(const std::map<int, int> &counts)
{
    for(std::map<int, int>::const_iterator it = counts.begin();
        it != counts.end(); ++it) { // For each number stored in the map (this automatically filters those with count 0)
        std::cout << it->first << ": " << it->second << std::endl; // Output its count
    }
}

Finally, a method to display our results. Since we never acted on any numbers that occur zero times, they are not in the map and will be omitted from the output.

int main() {
    srand(0); // So that we get the same result every time
    std::vector<int> numbers = generate_numbers(10000, 500);
    std::map<int, int> counts = count_numbers(numbers);
    return 0;
}

And putting it all together. See this code run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top