Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this 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;
}
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.
Related
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<double> numbers(input_number);
cout << "Enter numbers from 0 to 50: " << endl;
for (int i = 0; i < input_number; ++i) {
cin >> numbers[i];
}
unordered_map<int, int> freq;
for (int i = 0; i < numbers.size(); i++) {
freq[numbers[i]]++;
}
for (int i = 0; i < numbers.size(); i++) {
cout << freq[numbers[i]];
}
return 0;
}
When the use inputs numbers, for example 1,1,1,2 the output should be "1" because it is the most frequent number but the output here became "3,3,3,1" How to solve this problem?
You are most of the way there. Your frequencies are all stored, and you just need to search through the unordered_map now to find the item that has the largest value. Since you're already using <algorithm> you can leverage std::max_element to help:
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
int main()
{
std::vector<int> numbers = { 1, 2, 3, 2, 3, 2, 2 };
std::unordered_map<int, int> freq;
for (int n : numbers) ++freq[n];
if (!freq.empty())
{
auto it = std::max_element(freq.begin(), freq.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
std::cout << "Most frequent is " << it->first << "\n";
}
}
Output:
Most frequent is 2
Here, a custom comparison function is supplied that tests only the frequency part of the element (otherwise the default behavior will compare the full key/value pairs which will result in finding the largest number).
Note that because the map is unordered, there won't be a predictable outcome for tie-breakers (where more than one number is the most frequent). If you need to handle that in a more predictable way, you'll need to adjust the comparison function or possibly just loop over the container yourself if it requires additional work.
One option for tie-breaking is to choose the lowest number. That could be achieved by modifying the comparison to:
return std::make_pair(a.second, b.first) < std::make_pair(b.second, a.first);
The problem is that you just output all the values in map. In a naive implementation you have to iterate through map and register the maximum value and it's frequency:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
using std::cin, std::cout, std::endl;
using std::vector, std::unordered_map;
int input_number = 0, max_freq = 0, max_val = 0;
cout << "How many numbers you want to input: " << endl;
cin >> input_number;
// Making input double may creates questions
vector<int> numbers(input_number);
cout << "Enter numbers from 0 to 50: " << endl;
for (int i = 0; i < input_number; ++i) {
cin >> numbers[i];
}
unordered_map<int, int> freq;
for (int i = 0; i < numbers.size(); i++) {
freq[numbers[i]]++;
}
// iterating over the map and finding max value
for (auto val : freq) {
if( val.second > max_freq) {
max_val = val.first;
max_freq = val.second;
}
}
cout << max_val;
return 0;
}
Standard maps do store values as pairs of key and value (std::pair). This can be done in easier way: you can do that right while inputting the numbers.
for (int i = 0; i < numbers.size(); i++) {
int val = numbers[i];
int curfreq = ++freq[val];
if (curfreq > max_freq) {
max_val = val;
max_freq = curfreq;
}
}
cout << max_val;
Your array freq has to proper values in it. But your logic in the print out is wrong. You are printing the numbers twice. I guess you want to print all the numbers from 0 to 50.
cout << freq[i]
Then you see which entries have values or not. Then add some logic (which doesn't exist in your code) to pick the proper value. Like the biggest count..
This question already has answers here:
How to find Maximum value from 5 inputs by user? [closed]
(4 answers)
Closed 2 years ago.
I'm writing my first code in c++.
I want recieve in N number from user and find the biggest one.
I just have learnt itteration,if statement...(no list)
Please give me some guidance
If you like to learn C++, I suggest you directly start using the standard library (stl), its containers (such as std::vector) and its algorithm (in this case std::max_element).
A range based loop is not as good as a proper algorithm, but still better than a hand crafted index based loop.
Please refer to the Book "A tour of C++" by Stroustrup. He summarizes how C++ is meant to be used now.
Here is the code:
#include <vector>
#include <limits>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> arr;
const int N = 10;
for (int i = 0; i<N; i++) {
int value;
std::cin >> value;
arr.push_back(value);
}
const auto max_algorithm = std::max_element(arr.begin(), arr.end());
std::cout << "Largest is: " << *max_algorithm << std::endl;
auto max_range_based_loop = std::numeric_limits<int>::lowest();
for (const auto& item : arr) {
max_range_based_loop = std::max(item, max_range_based_loop );
}
std::cout << "Largest is: " << max_range_based_loop << std::endl;
return 0;
}
Initialize int max = INT_MIN.
While taking user input in an array, check if each input element is greater than max,
If greater, update max value.
when loop terminates return max.
Example:
int main()
{
int N = 10; // N is array size
int arr[N]; // Array declaration
int max = INT_MIN;
for(int i=0; i<N; i++)
{
cin>>arr[i]; // user input
if(arr[i]>max) //check each element if it's greater than max
{
max = arr[i];
}
}
cout<<"Largest is: "<<max<<endl; // print max Or return it in a method
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have ant task, to search most frequent odd number in vector array. I cant figure it out.
this is, how i am writing data, to array
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class oddNum {
private:
vector <int> numbers;
int number, n;
public:
void getData() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> number;
if(number % 2 != 0) {
numbers.push_back(number);
}
}
}
};
int main() {
oddNum n;
n.getData();
return 0;
}
my numbers
8 5 5 1 3
There are several ways to do it, I show you two. The first one is not intuitive and requires quite the bookmarking. However, the last solution uses the modern containers and their nature to do this in an elegant style.
First you sort the vector. This way all equal elements are next to each other. Than you iterate through this vector to look for the largest pack of elements while skipping all even numbers. Create a variable counter which resets if the elements change (this can be done by comparing the current element to the next element of the array) and a max variable that holds the largest value of said counter. Whenever this counter exceeds the value of max you have found the most common element so far which can be saved in a variable result. When you're done iterating, the variable result will contain the most frequent odd element of the vector. This implementation, in addition to <vector>, also needs the <algorithm> and <cassert> headers.
int get_most_frequent_odd(const std::vector<int>& vec) {
assert(!vec.empty());
std::vector<int> sorted = vec;
std::sort(sorted.begin(), sorted.end());
unsigned counter = 0u;
unsigned max = 0u;
int result;
for (unsigned i = 0u; i < sorted.size() - 1; ++i) {
if (sorted[i] % 2 != 0) {
if (sorted[i] == sorted[i + 1]) {
++counter;
if (max < counter) {
max = counter;
counter = 0u;
result = sorted[i];
}
}
else {
counter = 0u;
}
}
}
return result;
}
The function is quite specific (only for int's and odd elements). Also your getData() function already sorts out all even numbers. So here's a more generic function get_most_frequent<T>:
template<typename T>
T get_most_frequent(const std::vector<T>& vec) {
assert(!vec.empty());
std::vector<T> sorted = vec;
std::sort(sorted.begin(), sorted.end());
unsigned counter = 0u;
unsigned max = 0u;
T result;
for (unsigned i = 0u; i < sorted.size() - 1; ++i){
if (sorted[i] == sorted[i + 1]) {
++counter;
if (max < counter) {
max = counter;
counter = 0u;
result = sorted[i];
}
}
else {
counter = 0u;
}
}
return result;
}
Now a std::unordered_map or std::map will be superior over a std::vector for this task as they are build in a way that allows you to skip this ugly bookmarking. It's way more readable, too. But given you said you are a beginner I didn't put this at first place. The idea is to count the frequency by using a std::unordered_map. The elements are set to be the keys of the map and incrementing the values behind the keys will give you the occurrency of the elements. (Thanks #YSC) You can now use std::max_element which will return the pair with the highest saved occurrence. This implementation requires the <unordered_map>, <utility>, <algorithm> and <cassert> headers.
template<typename T>
T get_most_frequent(const std::vector<T>& vec) {
std::unordered_map<T, int> frequency_map;
for (auto i : vec) {
++frequency_map[i];
}
return std::max_element(frequency_map.begin(), frequency_map.end())->first;
}
example run using either of these 3 functions:
how many numbers?: 8
input number 1: 5
input number 2: 5
input number 3: 4
input number 4: 9
input number 5: 9
input number 6: 9
input number 7: 11
input number 8: 0
most common element is: 9
full code:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <cassert>
template<typename T>
T get_most_frequent(const std::vector<T>& vec) {
std::unordered_map<T, int> frequency_map;
for (auto i : vec) {
++frequency_map[i];
}
return std::max_element(frequency_map.begin(), frequency_map.end())->first;
}
class oddNum {
private:
std::vector<int> numbers;
public:
void getData() {
std::size_t size;
std::cout << "how many numbers?: ";
std::cin >> size;
int number;
for (int i = 0; i < size; ++i) {
std::cout << "input number " << i + 1 << ": ";
std::cin >> number;
if (number % 2 != 0) {
numbers.push_back(number);
}
}
std::cout << "most common element is: " << get_most_frequent(numbers) << '\n';
}
};
int main() {
oddNum n;
n.getData();
}
This question already has answers here:
How to sum up elements of a C++ vector?
(13 answers)
Closed 7 years ago.
I'm very new to coding and was just playing around with vectors however I cant seem to find out how to add all elements in a vector together when the amount of elements is user-defined.
#include <iostream>
#include <vector>
using namespace std;
int NoOfItems;
int i=1;
double Odds;
double Cost;
vector<double> CaseNumber;
int main()
{
cout << "How many items in the case: ";
cin >> NoOfItems;
while (true) {
if (NoOfItems == 0) {
break;
} else {
cout << "Odds for item " << i <<endl;
cin >> Odds;
CaseNumber.push_back(Odds);
NoOfItems = NoOfItems - 1;
i = i + 1;
}
}
}
You'll want to spend some time cleaning up your code. There's some very questionable code conventions being used.
Anyways, to sum all of the elements of your vector:
double sum = 0;
for(size_t index = 0; index < CaseNumber.size(); index++) {
sum += CaseNumber[index];
}
Or, in a way that's slightly more friendly to the semantics of C++:
double sum = 0;
for(double & d : CaseNumber) {
sum += d;
}
Either will result in the variable sum containing the sum total of all elements in CaseNumber
This question already has answers here:
rand() returns same values when called within a single function
(5 answers)
Closed 8 years ago.
I'm trying to write a simple function that generates an array with random integers.
I encountered with an interesting thing, when I run this program outputs -each cout
statements- seem the same.
However, when I am debugging and watching it step by step array values are changing.
Am I doing something wrong?
Thanks.
void generateRandomArray( int *&inputArray, int size){
if(inputArray != NULL){
delete []inputArray;
}
//create a new array
inputArray = new int [size];
//fill with random numbers
srand(unsigned (time (NULL)));
for (int i = 0; i < size ; i++)
inputArray[i] = (rand() % 100) ;
}
int main(){
//Variables
int *inputArray = NULL;
int size;
//Test
size = 10;
//first call
generateRandomArray( inputArray, size);
for(int i = 0 ; i < size; i++){
cout << inputArray[i] << endl;
}
cout << "------------------" << endl;
//second call
generateRandomArray( inputArray, size);
//output is the same with previous
for(int i = 0 ; i < size; i++){
cout << inputArray[i] << endl;
}
return 0;
}
The program runs too fast, srand(unsigned (time (NULL))); will get a seed having the same seconds (since epoch). Hence, the rand sequences are the same.
The problem is that if the calls to srand all happen withing the same second, the generator will be seeded with the same values and so generate the same sequence, always.
When you're debugging it will be slower, and allow time to pass and have different seed for the generator. When not debugging the time between calls will be too fast.
Don't call srand more than once, unless you know what you're doing. Put it at the start of the main function, and don't call it again.
Call srand(time(NULL)) and it will seed the current time and make a random number from it. Since time is changing all the time, it will give you a different number every time.
With C++11, you may use something like: (https://ideone.com/EIb0nY)
#include <iostream>
#include <random>
#include <vector>
std::vector<int> generateRandomArray(std::default_random_engine& generator, int size)
{
std::uniform_int_distribution<int> distribution(1, 100);
std::vector<int> res(size);
for (auto& e : res) {
e = distribution(generator);
}
return res;
}
int main()
{
std::default_random_engine generator;
const int size = 10;
//first call
for (auto e : generateRandomArray(generator, size)) {
std::cout << e << std::endl;
}
std::cout << "------------------" << std::endl;
//second call
for (auto e : generateRandomArray(generator2, size)) {
std::cout << e << std::endl;
}
return 0;
}
That use the new random facilities.
It avoids manual memory management (with std::vector).