Find Occurrences in Array - c++

I Have to find the occurrences of every element in array.
So far My code is this
void Occurrences()
{
int numers[10], count = 0, i;
for (i = 0; i < 10; i++)
{
cout << "Enter Number";
cin >> numers[i];
}
for (i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (numers[i] == numers[j])
{
count++;
}
}
cout << numers[i] << " is Occur " << count << " Time in Array" << endl;
count = 0;
}
}
int main()
{
Occurrences();
}
Output is coming multiply same numbers i.e If I entered six 1 and 4 2's. Output is
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
1 is occur 6 time in array.
2 is occur 4 time in array.
2 is occur 4 time in array.
2 is occur 4 time in array.
2 is occur 4 time in array.
But I want output like this:
1 is occur 6 time in array.
2 is occur 4 time in array.
How do I do this?

Since you tagged this C++11, I would use std::unordered_map:
void Occurrences()
{
std::unordered_map<int, int> occurrences;
// enter 10 numbers
for (int i = 0; i < 10; ++i) {
cout << "Enter Number";
int x;
cin >> x;
++occurrences[x]; // increment the count for x
}
// print results
for (const auto& pr : occurrences) {
std::cout << pr.first << " appears " << pr.second << " times." << std::endl;
}
}

Your problem is you're searching for items you've already output. you can skip those items if you sort the array first.
Just to be different, I'm going to tell you how to do this with your existing code, an array, and not a map.
read the values in the array.
sort the array.
enumerate the array, and ignore (but count) any elements matching the previous element. reset the counter when you discover a new element.
thats it.
Example:
#include <iostream>
#include <algorithm>
void Occurrences()
{
int numers[10], i;
for (i = 0; i < 10; ++i)
{
std::cout << "Enter Number";
if (!(std::cin >> numers[i]))
break;
}
// sort the array in ascending order , O(NlogN)
std::sort(numers, numers+i);
for (const int* it = numers; it != numers+i;)
{
unsigned int count = 1;
int value = *it;
for (++it; (it != numers+i) && *it == value; ++count, ++it);
std::cout << value << " occurs " << count << " times." << std::endl;
}
}
int main()
{
Occurrences();
}
Your Sample Run
Enter Number1
Enter Number1
Enter Number1
Enter Number1
Enter Number1
Enter Number1
Enter Number2
Enter Number2
Enter Number2
Enter Number2
1 occurs 6 times.
2 occurs 4 times.
No map required. if you choose to use a map, consider an unordered map (hash table) as it may produce better performance.
Best of luck.

Better store it in a map and display everything later.
void Occurrences()
{
int numers[10],count = 0,i;
std::map<int,int> mapCnt;
for(i =0;i<10;i++)
{
cout<<"Enter Number";
cin>>numers[i];
}
for( i = 0;i<10;i++)
{
for(int j = 0;j<10;j++)
{
if(numers[i] == numers[j])
{
count++;
}
}
mapCnt[numers[i]]=count;
count = 0;
}
// Print the map Here
typedef std::map<int,int>::iterator it_type;
for(it_type iterator = mapCnt.begin(); iterator != mapCnt.end(); iterator++) {
cout << iterator->first << " is Occur " << iterator->second << " Time in Array" << endl;
}
}
Looping through map https://stackoverflow.com/a/4844904/2466168

A variation from maandoo's code if you can process as your read the numbers in:
void Occurrences()
{
int i;
std::map<int,int> mapCnt;
for(i =0;i<10;i++)
{
int num;
cout<<"Enter Number";
cin>>num;
std::map< int, int >::iterator iter( mapCnt.find( num ) );
if( iter != mapCnt.end() )
mapCnt[num] = 1;
else
++( iter->second );
}
// Print the map Here
for( i = 0; i < mapCnt.size(); ++i )
std::cout << mapCnt[i].first << " occurs " << mapCnt[i].second << " times in array\n";
}

Related

why isn't my vector pushbacking even and odd numbers

i tried to separate even and odd numbers using vectors from a array ==>
so i made a function that returns true is number is even and false for if number is odd
then i used an if else statement where if the function returns true then it pushbacks the value in a vector and if the function returns false then it pushbacks the value in another vector , finally i printed all the elements in the vector but the output does not show any element except it shows one in the odd vector.
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
int i=0 ;
if(sort(arr , i)){
even.push_back(arr[i]);
sort(arr , i+1);
}else{
odd.push_back(arr[i]);
sort(arr,i+1);
}
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
As #TonyDelroy said, you have to make for loop around call to sort(arr, i). Also first loop should go up to i <= n instead of i < n.
Your fixed working code below (see also std::partition_copy variant afterwards):
Try it online!
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
for (int i = 0; i < n; ++i)
if (sort(arr, i))
even.push_back(arr[i]);
else
odd.push_back(arr[i]);
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
As #chris said you can also use std::partition_copy to implement your algorithm:
Try it online!
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::vector<int> arr(n), odd, even;
for (int i = 1; i <= n; ++i)
arr[i - 1] = i;
std::partition_copy(arr.cbegin(), arr.cend(),
std::back_insert_iterator(odd), std::back_insert_iterator(even),
[](auto const & x){ return (x & 1) == 1; });
std::cout << "the even numbers are : " << std::endl;
for (auto element: even)
std::cout << element << " ";
std::cout << std::endl << "the odd numbers are : " << std::endl;
for (auto element: odd)
std::cout << element << " ";
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
You only push one element - the first.
Your partitioning code is equivalent to
if(sort(arr , 0)){
even.push_back(arr[0]);
sort(arr , 1);
}else{
odd.push_back(arr[0]);
sort(arr,1);
}
You need to loop over all the input numbers.
You can also simplify matters with a more generally useful evenness function that doesn't depend on an array:
bool is_even(int x) { return x % 2 == 0; }
and then there is no need to store all the inputs before processing them:
int main(){
vector <int> even , odd;
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (is_even(x)) {
even.push_back(x);
}
else {
odd.push_back(x);
}
}
cout << "the even numbers are : " << endl;
for (auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for (auto element:odd){
cout << element << " ";
}
}

Checking for duplicates in an array using for loop

I am trying to check whether there is any duplicate integer in the user input array. The problem is that the validation of the duplicate does not work properly and I have no idea why it is not showing the desired output. Following is the code:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arr[i] == arr[k])
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
Current result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 5 5 5 4 4 4 3 3 2
Expected result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 4 3 2 1
Current result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : 5 5 5 5 Duplicate found 4 4 3
Expected result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : Duplicate found
I believe my loops is the source to the problem. The current result output 10 times and I do not understand why there will be so many same numbers appearing.
Do note that I am trying to apply the validation using loop only and not from C++ standard library.
The issue in your code is that you are printing out each array element every time a particular element is not matching another element. It seems that you only want to print out whether any duplicate values are found. For this, you can use a bool flag to indicate whether any element is duplicated:
bool found_dup = false;
for(int i = 0; i < length; i++)
for(int k = i + 1; k < length; k++)
if(arr[i] == arr[k])
{
found_dup = true;
break;
}
// else: don't print anything yet
and then at the end print out the array:
if (found_dup)
std::cout << "Duplicate found";
else
for(int i = 0; i < length; i++)
std::cout << arr[i] << " ";
You may achieve the program in a more enhanced way (where you don't need to define the length manually - notice the explanation given as comments in code):
#include <iostream> // for input/output operation
#include <vector> // for dynamic array management
#include <sstream> // to split the user inputs and assign them to the vector
#include <algorithm> // to sort the vector
#include <string> // to work with getline()
// using this statement isn't recommended, but for sake of simplicity
// and avoiding the use of std:: everywhere temporarily (for small programs)
using namespace std;
int main(void) {
vector<int> numbers;
vector<int> duplicates;
string input;
int temp;
// getting the user input as string
cout << "Enter the numbers: ";
getline(cin, input);
stringstream ss(input);
// splitting the user input string into integers and assigning
// them into the vector
while (ss >> temp)
numbers.push_back(temp);
// sorting the vector in increasing order
sort(numbers.begin(), numbers.end());
// getting the unique numbers (which are not repeated)
cout << "Unique numbers: ";
for (size_t i = 0, len = numbers.size(); i < len; i++) {
if (temp == numbers[i])
// if found a duplicate, then push into the 'duplicates' vector
duplicates.push_back(temp);
else
cout << numbers[i] << ' ';
temp = numbers[i];
}
// getting the duplicates
cout << "Total duplicates: ";
for (size_t i = 0, len = duplicates.size(); i < len; i++)
cout << duplicates[i] << ' ';
cout << endl;
return 0;
}
It'll output something like:
Enter the numbers: 1 4 8 9 3 2 3 3 2 1 4 8
Unique numbers: 1 2 3 4 8 9
Total duplicates: 1 2 3 3 4 8
Please change the if condition to something like this.
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arrValue == arr[k]) //change here.
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
I would also suggest to use a map data structure. Map allows you to count the frequency of numbers, and thus detect duplicates in linear time.
map<int, int> m; // specify the key-value data-type.
for(int i = 0;i<length;i++)
{
m[arr[i]]++;
}
map<int, int>::iterator it; // an iterator to iterate over the datastructure.
for(it = m.begin();it!=m.end();it++)
{
if(it->second>1) //it->second refers to the value(here, count).
{
cout<<it->first<<" "; //it->first refers to the key.
}
}
Your loops are actually iterating n-1 times for first element, n-2 times for second element etc., where n is the length of your array. This is why for 5 element array you have printed 5 4 times.
But generally, if the purpose is to detect duplicates in the array, this strategy is not the best one. Please note that having exemplary array 4 3 4, with current approach you will correctly detect for the first 4 that the third element is also 4 but once you will move to the third element, it will be marked as ok since it is not checked with the first one element.
You may consider another strategy: create another array of the n size. Then iterate through your original array and for each element check if that element is already in the new array. If you detect the presence, you may raise duplicate event. Otherwise you can add this element to the array.
It doesn't work because you're trying to print the same value everytime you find a different one. I got here a solution with one more array that will store the array. It would work too with just one array.
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
int *noDuplicateArr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
noDuplicateArr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << noDuplicateArr[i] << " ";
}
}
delete[] arr;
delete[] noDuplicateArr;
}
Here is the version with just one array:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
arr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << arr[i] << " ";
}
}
delete[] arr;
}

Bubble Sorting - How to use it?

Im a bit new to programming , Trying to get the idea of Algorithm so i started by Sorting Algorithms.So ive read a lot about it and tried to understand its idea then started by Bubble Sort,But im having a problem in my code , Can someone tell me if im thinking over this correctly ? Im not sure that im still on the right way for this.
EDIT: I want to have the user insert a certain amount of numbers in an array , Then these unarranged numbers to be swapped using the Bubble-Sort.
so here's the code :
#include <iostream>
using namespace std;
int main(){
int arr[6];
int temp;
cout << "Enter an unarranged amount of numbers(6) \n";
for(int i=0;i<6;i++){
cin>>arr[i];
}
cout << "Normal List : ";
for(int i=0;i<6;i++){
cout << arr[i] << " ";
}
//Sorting
for(int i=0;i<6;i++){
for(int x=0;x=i+1;x++){
if(arr[i]>arr[x]){
temp=arr[x];
arr[x]=arr[i];
arr[i]=temp;
}
}
cout << arr[i] << " ";
}
return 0;
}
This loop
for(int x=0;x=i+1;x++){
is an infinite loop because in the condition of the loop there is used the assignment
x=i+1
So the value of x that is the value of the condition is never will be equal to 0.
And the bubble sort algorithm compares and swaps adjacent elements of an array.
Also you could use the standard function std::swap to swap elements of the array.
The loops that implement the bubble sort can look for example the following way as it is shown in the demonstrative program below
#include <iostream>
#include <utility>
int main()
{
const size_t N = 6;
int arr[N];
std::cout << "Enter an unarranged amount of " << N << " numbers: ";
for ( auto &item : arr ) std::cin >> item;
std::cout << "Before sorting: ";
for ( const auto &item : arr ) std::cout << item << ' ';
std::cout << '\n';
for ( size_t n = N, last = n; !( n < 2 ); n = last )
{
for ( size_t i = last = 1; i < n; i++ )
{
if ( arr[i] < arr[i-1] )
{
std::swap( arr[i], arr[i-1] );
last = i;
}
}
}
std::cout << "After sorting: ";
for ( const auto &item : arr ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
Its output might look for example like
Enter an unarranged amount of 6 numbers: 6 3 1 2 4 5
Before sorting: 6 3 1 2 4 5
After sorting: 1 2 3 4 5 6
As for your code then the inner loop should look at least like
for(int x = 1; x < 6; x++ ){
if ( arr[x-1] > arr[x] ){
temp=arr[x];
arr[x]=arr[x-1];
arr[x-1]=temp;
}
}
and remove this statement after the loop
cout << arr[i] << " ";

sort and show the number of digits

I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}

Breaking a loop when entering a specific number?

How would I break a loop when the user enters 0 after entering a series of numbers? For this project I am trying to read the amount of time a number comes up.
Example: if the user enter 1 5 6 9 8 7 1 3 5
then the program would go
1 appeared 2 times
5 appeared 2 times
6 appeared 1 time
... and so on,
Another question I have is, how do I only print the elements that the user inputs instead of printing all elements?
I really appreciate any help. Thanks!
#include <iostream>
using namespace std;
void nums(int[]);
int main() {
cout << "Enter the however much numbers between 1-100 that you want, when you are done type 0 to finish: " << endl;
int myarray[100] = { 0 };
for (int i = 0; i < 100; i++) {
cin >> myarray[i];
if (myarray[i] == 0) {
break;
}
}
nums(myarray);
system("pause");
return 0;
}
void nums(int myarray[]) {
for (int i = 0; i < myarray[i]; i++) {
cout << myarray[i] << " "; //This code only prints out all the elements if the user inputs numbers in order. How do I get it to print out the elements the user inputs?
}
}
I used the indexes of each element to hold actual value and and the count as value of that index, hope it help :
#include <iostream>
#include <vector>
int main() {
//create a vector with size 100
std::vector<int> numberVector(100);
//init all elements of vector to 0
std::fill(numberVector.begin(), numberVector.end(), 0);
int value;
std::cout << "Enter the however much numbers between 1-100 that you want, when you are done type 0 to finish: " << std::endl;
while (true) {
std::cin >> value;
//braek if 0
if (value == 0) {
break;
}
//++ the value of given index
++numberVector.at(value);
}
//for all elements of the vector
for (auto iter = numberVector.begin(); iter != numberVector.end(); ++iter) {
//if the count of number is more than 0 (the number entered)
if (*iter > 0) {
//print the index and count
std::cout << iter - numberVector.begin() << " appeared " << *iter << " times\n";
}
}
//wait for some key to be pressed
system("pause");
return 0;
}
EDIT : If your are not using c++1z, replace auto iter with std::vector<int>::iterator iter