Count how many times elements in an array are repeated - c++
The program I'm trying to write allows me to enter 10 numbers and it should get tell me Number X is repeated X times and so on.
I've been trying this but the problem is I get the result as follows:
For example...{1,1,1,1,4,6,4,7,4}
The number 1 is repeated 4 times
The number 1 is repeated 3 times
The number 1 is repeated 2 times
The number 1 is repeated 1 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 4 is repeated 2 times
The number 7 is repeated 1 times
The number 4 is repeated 1 times
The problem is that it checks the next number with the following numbers without skipping it, or without knowing it has written it before
#include <iostream>
#include <string>
using namespace std;
int main() {
int x[10];
for (int i=0;i<10;i++) {
cin>>x[i];
}
for (int i=0;i<9;i++) {
int count=1;
for (int j=i+1;j<10;j++) {
if (x[i]==x[j]) count++;
}
cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
}
}
The problem with your code is that you re-process numbers that you've already processed. So if there is an occurrence of 1 at position 0 and another occurrence of 1 at position 5, then you will process the 1 at position 5 again when you get there in the loop.
So you need a way to decide if a number has been processed already or not. An easy way is to add a second array (initially all values are set to 0) and whenever you process a number you mark all positions where that element occurs. Now before processing an element you check if it's been processed already and do nothing if that's the case.
Also, try to indent your code properly :)
C++ Code:
int main( void ) {
const int N = 10;
int A[N];
for(int i = 0; i < N; i++)
cin >> A[i];
int seen[N];
for(int i = 0; i < N; i++)
seen[i] = 0;
for(int i = 0; i < N; i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < N; j++)
if(A[j] == A[i]) {
count += 1;
seen[j] = 1;
}
cout << A[i] << " occurs " << count << " times" << endl;
}
}
return 0;
}
Here's a fairly simple implementation using std::map.
#include <map>
#include <vector>
#include <cstdlib>
#include <iostream>
std::map<int, unsigned int> counter(const std::vector<int>& vals) {
std::map<int, unsigned int> rv;
for (auto val = vals.begin(); val != vals.end(); ++val) {
rv[*val]++;
}
return rv;
}
void display(const std::map<int, unsigned int>& counts) {
for (auto count = counts.begin(); count != counts.end(); ++count) {
std::cout << "Value " << count->first << " has count "
<< count->second << std::endl;
}
}
int main(int argc, char** argv) {
std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
display(counter(mem));
return 0;
}
Output:
Value 1 has count 4
Value 4 has count 3
Value 6 has count 1
Value 7 has count 1
Compiled using the C++14 standard, but it should also work with C++11. Get rid of the vector initializer and use of auto and it should work with C++98.
Update:
I've updated this code a bit to use std::unordered_map instead of std::map, since order doesn't seem to be an issue. Also, I have simplified the loop controls based on some newer C++ features.
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <iostream>
std::unordered_map<int, unsigned int> counter(const std::vector<int>& vals) {
std::unordered_map<int, unsigned int> rv;
for (auto val : vals) {
rv[val]++;
}
return rv;
}
void display(const std::unordered_map<int, unsigned int>& counts) {
for (auto count : counts) {
std::cout << "Value " << count.first << " has count " << count.second << std::endl;
}
}
int main(int argc, char** argv) {
std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
display(counter(mem));
return 0;
}
Output:
Value 7 has count 1
Value 6 has count 1
Value 4 has count 3
Value 1 has count 4
In this case, the order of the counts will be random since std::unordered_map is a hash table with no intrinsic ordering.
The most effective way I have recently come across with this...
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int array[10]={1,1,1,1,4,6,4,7,4};
int a[100];
memset(a,0,sizeof(a));
for(int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
a[array[i]]++;
}
for(int i=1; i<sizeof(a)/sizeof(a[0]); i++)
{
if(a[i]>0)
{
cout<<"The number "<<i<<"is repeated "<<a[i]<<" times"<<"\n";
}
}
OUTPUT:
The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times
Pretty simple using map!
See the Repl.it
#include <iostream>
#include <map>
int main()
{
int foo[]{1,1,1,1,4,6,4,7,4};
std::map<int, int> bar;
for (auto const &f : foo)
bar[f]++;
for (auto const &b : bar)
std::cout << "The number " << b.first
<< "is repeated " << b.second
<< "times\n";
}
Expected output:
The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"enter length of array:"<<endl;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cout<<"enter element:";
cin>>arr[i];
}
sort(arr,arr+n);
/*this is for sort the array so we can find maximum element form user input and
using this element we make one array of that size
*/
int m=arr[n-1];
m++;
int a[m];
for(int i=0;i<m;i++)
{
a[i]=0;
}
for(int i=0;i<n;i++)
{
a[arr[i]]++;
}
cout<<endl;
for(int i=0;i<m;i++)
{
if(a[i]>0)
cout<<i<<"is repeat:"<<a[i]<<"time"<<endl;
}
}
output is like this:
enter length of array:
6
enter element:6
enter element:5
enter element:5
enter element:6
enter element:2
enter element:3
2is repeat:1time
3is repeat:1time
5is repeat:2time
6is repeat:2time
package DP;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class countsofRepeatedNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {1,1,1,1,4,4,6,4,7};
int n=arr.length;
countNumber(arr,n);
}
private static void countNumber(int[] arr, int n) {
TreeMap<Integer,Integer>list= new TreeMap<Integer,Integer>();
Arrays.sort(arr);
int count=1;
for(int i=0;i<n-1;i++) {
if(arr[i]==arr[i+1]) {
count++;
}else {
list.put(arr[i], count);
count=1;
}
}
list.put(arr[n-1], count);
printDatas(list);
}
private static void printDatas(TreeMap<Integer, Integer> list) {
for(Map.Entry<Integer, Integer>m:list.entrySet()) {
System.out.println("Item "+m.getKey()+": "+m.getValue());
}
}
}
#include<bits/stdc++.h> using namespace std; int Duplicate(int a[],int n){ int i; int c=1; for(i=0;i<n;i++){ if(a[i]==a[i+1]){c++;continue;} if(c>1) cout<<a[i]<<" occured: "<<c<<" times"<<endl; c=1; }
} int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); Duplicate(a,n); } }
This code is in just O(n) time and O(1) space
#include<bits/stdc++.h> using namespace std; int Duplicate(int a[],int n){ int i; int c=1; for(i=0;i<n;i++){ if(a[i]==a[i+1]){c++;continue;} if(c>1) cout<<a[i]<<" occured: "<<c<<" times"<<endl; c=1; } } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); Duplicate(a,n); } }
#include <iostream>
#include<map>
using namespace std;
int main()
{
int arr[]={1,1,1,1,4,6,4,7,4};
int count=1;
map<int,int> mymap;
try
{
if(sizeof(arr)/sizeof(arr[0])<=1)
{
throw 1;
}
}
catch(int x)
{
cout<<"array size is not be 1";
return 0;
}
for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)
{
for(int j=i;j<(sizeof(arr)/sizeof(arr[0]));j++)
{
if(arr[i]==arr[j+1])
{
count++;
}
}
if(mymap.find(arr[i])!=mymap.end())
{
auto it = mymap.find(arr[i]);
if((it)->second<=count)
(it)->second=count;
count=1;
}
else if(count)
{
mymap.insert(pair<int,int>(arr[i],count));
count=1;
}
}
for(auto it=mymap.begin();it!=mymap.end();it++)
{
cout<<it->first<<"->"<<it->second<<endl;
}
return 0;
}
Expected Output:
1->4
4->3
6->1
7->1
Related
C++ How to read input N and then read a series of numbers N long?
I'm working on an assignment where I need to create a program that reads a non-empty sequence of integer numbers, and tells how many of them are equal to the last one. It should read the amount of integers the sequence has and then read the sequence itself and return the amount of times the last number repeats itself excluding the last one. Input would be like this: 9 1 7 3 2 4 7 5 8 7 and the output should be: 2 Now, I have no problem with the functionality of the program but I'm struggling on having it read the inputs. This is what I got: #include <iostream> #include <vector> #include <sstream> int NumbersEqualToLast(int limit, std::vector<int> elements) { int check = elements[limit], counter = 0; for (int i = limit; i >= 0; i--) { if (elements[i] == check) { counter++; } } return(counter); } int main() { int amount, number; std::cin >> amount; std::string input; getline(std::cin, input); std::stringstream iss(input); std::vector<int> numbers; while ( iss >> number ) { numbers.push_back( number ); } std::cout << NumbersEqualToLast(amount, numbers) << std::endl; } The problem is after reading the amount of integers (in this case 9) I get a Segmentation fault (core dumped) error. EDIT AFTER SOLUTION This is what worked for me using your suggestions. Thank you. I understand if it's not pretty or there are better more efficient ways but I'm just starting out. :) #include <iostream> #include <vector> int NumbersEqualToLast(int limit, std::vector<int> elements) { int check = elements[limit - 1], counter = 0; for (int i = limit - 2; i >= 0; i--) { if (elements[i] == check) { counter++; } } return(counter); } int main() { int quantity; std::cin >> quantity; int number; std::vector<int> numbers; for (int i = 0; i < quantity; i++) { std::cin>>number; numbers.push_back(number); } std::cout << NumbersEqualToLast(quantity, numbers) << std::endl; }
Just don't judge harshly, please. I suggest another way to solve this problem. #include <iostream> #include <vector> using namespace std; int special, count; void dfs(int current, int previous, vector<int>& visited, vector<int>& input) { if(visited[current]==1) { return; } visited[current]=1; if(current==(input.size()-1)) { special=input[current]; } for(int next=(current+1); next<input.size(); ++next) { if(next==previous) { continue; } dfs(next, current, visited, input); } if(special==input[current]) { ++count; } if(current==0) { --count; cout<<count; } return; } void solve() { int quantity; cin>>quantity; int number; vector<int> numbers; for(int i=0; i<quantity; ++i) { cin>>number; numbers.push_back(number); } vector<int> visited(quantity); dfs(0, -1, visited, numbers); return; } int main() { solve(); return 0; } Input: 9 1 7 3 2 4 7 5 8 7 Here is the result: 2
How can I start a loop from middle of the array?
There is a given pseudo code. int Function(X : array[P..Q] of integer) 1 maxSoFar = 0 2 for L = P to Q I was using C and trying to change it into C++ code. The reason that I am struggling with it is I have no idea how to express it is start from 'P' in the loop. I do not know how to do that before initilization even without parameter. int Function(vector<int> X) { int maxSoFar = 0; for (int I = 0; I < X.size(); I++) ; } This is what I did. I wonder if it is same with the pseudo code or not.
You can just divide your vector size by 2: #include <vector> #include <iostream> using namespace std; int f(vector<int> v) { int maxSoFar = 0; int len = v.size(); for (int i = len / 2; i < len; i++) { // i = len / 2, starts from the middle maxSoFar += v[i]; cout << v[i] << ' '; cout << maxSoFar << endl; } } int main(void) { vector<int> v = {1, 3, 5}; f(v); } output: 3 3 5 8 You should take a closer look at the for loop on wikipedia: for (initialization; break condition; incrementation)
#include<iostream> using namespace std; int main() { int i,n; cout<<"enter the number of elements : "; cin>>n; int a[n]; cout<<endl<<"enter the value of this array : "; for(i=0;i<n;i++) { cin>>a[i]; } cout<<endl<<"print the last half elements of this array : "; for(i=(n/2);i<n;i++) cout<<a[i]<<" "; cout<<endl; return 0; }
I want to print out the last result done by the loop C++
#include <iostream> #include <conio.h> using namespace std; int main() { int i; int n=0; int F[10]; F[0]=0; F[1]=1; cin>>n; for(i=2; i<n+1; ++i) { F[i]=(F[i-1])+F[i-2]; cout <<F[i]<<endl; } getch(); return 0; } now this is a sort of a fibonacci number generator, but it outputs all previous numbers in the fibonacci series. I want it to print the last one. For example, if the input is 8, i want it to output "21" instead of 1 2 3 5 8 13 21.
#include <iostream> #include <conio.h> int main() { int F[10]; F[0] = 0; F[1] = 1; int n = 0; cin >> n; for (int i = 2; i <= n; ++i) { F[i] = F[i-1] + F[i-2]; } std::cout << F[n] << std::endl; getch(); } Since you already know the index of the last element (n), you can just print that after the loop. I also did some other cleanup that didn't change the functionality of the program. Note that the program originally and still assumes that n is less than 10.
Just store only 2 last values: #include <iostream> using namespace std; int main() { int F[2] = { 1, 1 }; int n = 0; cin>>n; for(int i=2; i<n; ++i) { swap( F[0], F[1] ); F[1] += F[0]; } std::cout << F[1] << std::endl; return 0; }
Error implementing selection sort in C++
I've written this code to sort an array using selection sort, but it doesn't sort the array correctly. #include <cstdlib> #include <iostream> using namespace std; void selectionsort(int *b, int size) { int i, k, menor, posmenor; for (i = 0; i < size - 1; i++) { posmenor = i; menor = b[i]; for (k = i + 1; k < size; k++) { if (b[k] < menor) { menor = b[k]; posmenor = k; } } b[posmenor] = b[i]; b[i] = menor; } } int main() { typedef int myarray[size]; myarray b; for (int i = 1; i <= size; i++) { cout << "Ingrese numero " << i << ": "; cin >> b[i]; } selectionsort(b, size); for (int l = 1; l <= size; l++) { cout << b[l] << endl; } system("Pause"); return 0; } I can't find the error. I'm new to C++. Thanks for help.
The selectionSort() function is fine. Array init and output is not. See below. int main() { int size = 10; // for example typedef int myarray[size]; myarray b; for (int i=0;i<size;i++) //------------^^--^ { cout<<"Ingrese numero "<<i<<": "; cin>>b[i]; } selectionsort(b,size); for (int i=0;i<size;i++) //------------^^--^ { cout<<b[l]<<endl; } system("Pause"); return 0; } In C and C++, an array with n elements starts with the 0 index, and ends with the n-1 index. For your example, the starting index is 0 and ending index is 9. When you iterate like you do in your posted code, you check if the index variable is less than (or not equal to) the size of the array, i.e. size. Thus, on the last step of your iteration, you access b[size], accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question. I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input: #include <iostream> void selectionsort(int* b, int size) { int i, k, menor, posmenor; for(i=0;i<size-1;i++) { posmenor=i; menor=b[i]; for(k=i+1;k<size;k++) { if(b[k]<menor) { menor=b[k]; posmenor=k; } } b[posmenor]=b[i]; b[i]=menor; } } int main(int argc, char **argv) { int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0}; selectionsort(a, 10); for (auto v:a) { std::cout << v << ' '; } std::cout << std::endl; } The resulting output was as follows: -5 -4 -3 0 2 3 4 6 100 200 These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.
Find unique numbers in array
Well, I have to find how many different numbers are in an array. For example if array is: 1 9 4 5 8 3 1 3 5 The output should be 6, because 1,9,4,5,8,3 are unique and 1,3,5 are repeating (not unique). So, here is my code so far..... not working properly thought. #include <iostream> using namespace std; int main() { int r = 0, a[50], n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int j = 0; j < n; j++) { for (int k = 0; k < j; k++) { if (a[k] != a[j]) r++; } } cout << r << endl; return 0; }
Let me join the party ;) You could also use a hash-table: #include <unordered_set> #include <iostream> int main() { int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 }; const size_t len = sizeof(a) / sizeof(a[0]); std::unordered_set<int> s(a, a + len); std::cout << s.size() << std::endl; return EXIT_SUCCESS; } Not that it matters here, but this will likely have the best performance for large arrays. If the difference between smallest and greatest element is reasonably small, then you could do something even faster: Create a vector<bool> that spans the range between min and max element (if you knew the array elements at compile-time, I'd suggest the std::bitset instead, but then you could just compute everything in the compile-time using template meta-programming anyway). For each element of the input array, set the corresponding flag in vector<bool>. Once you are done, simply count the number of trues in the vector<bool>.
A std::set contains only unique elements already. #include <set> int main() { int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 }; std::set<int> sa(a, a + 9); std::cout << sa.size() << std::endl; }
How about this? #include <list> int main() { int a[] = {1, 9, 4, 5, 8, 3, 1, 3, 5}; std::list<int> la(a, a+9); la.sort(); la.unique(); std::cout << la.size() << std::endl; return 0; }
Since you've stated that you cannot use the standard library and must use loops, let's try this solution instead. #include <iostream> using namespace std; // you're a bad, bad boy! int main() { int r = 0, a[50], n; cout << "How many numbers will you input? "; cin >> n; if(n <= 0) { cout << "What? Put me in Coach. I'm ready! I can do this!" << endl; return -1; } if(n > 50) { cout << "So many numbers! I... can't do this Coach!" << endl; return -1; } cout << "OK... Enter your numbers now." << endl; for (int i = 0; i < n; i++) cin >> a[i]; cout << "Let's see... "; // We could sort the list but that's a bit too much. We will choose the // naive approach which is O(n^2), but that's OK. We're still learning! for (int i = 0; i != n; i++) { // Go through the list once. for (int j = 0; j != i; j++) { // And check if this number has already appeared in the list: if((i != j) && (a[j] == a[i])) { // A duplicate number! r++; break; } } } cout << "I count " << n - r << " unique numbers!" << endl; return 0; } I urge you to not submit this code as your homework - at least not without understanding it. You will only do yourself a disservice, and chances are that your instructor will know that you didn't write it anyways: I've been a grader before, and it's fairly obvious when someone's code quality magically improves.
I think the location for increasing the value of r is incorrect #include <iostream> using namespace std; int main() { int r=0,a[50],n; cin >>n; for(int i=0;i<n;i++) { cin >> a[i]; } for (int j=0;j<n;j++) { bool flag = true; for(int k=;k<j;k++) { if(a[k]!=a[j]) { flag = false; break; } } if (true == flag) { r++; } } cout << r << endl; return 0; } However, my suggestion is using more sophisticated algorithms (this algorithm has O(N^2)).
this should work, however its probably not the optimum solution. #include <iostream> using namespace std; int main() { int a[50],n; int uniqueNumbers; // this will be the total numbers entered and we will -- it cin >>n; uniqueNumbers = n; for(int i=0;i<n;i++) { cin >> a[i]; } for (int j=0;j<n;j++) { for(int k=0;k<n;k++) { /* the and clause below is what I think you were missing. you were probably getting false positatives when j == k because a[1] will always == a[1] ;-) */ if((a[k] == a[j]) && (k!=j)) { uniqueNumebers--; } } } cout << uniqueNumbers << endl; return 0; }
We can use C++ STL vector in this program . int main() { int a[] = {1, 9, 4, 5, 8, 3, 1, 3, 5}; vector<int>v(a, a+9); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); cout<<v.size()<<endl; return 0; }
Please dry run your code See in the outer for loop for each element it is counted more than one inside inner loop.let us say the loop contains 1,2,3,4.1.....elements dry run it in the second iteration and third iteration 1 is counted because 1 is 1!=2 as well as 1!=3 Now solution time!! #include<iostream> #include<vector> #include<algorithm> #define ll long long using namespace std; ll arr[1000007]={0}; int main() { ios_base::sync_with_stdio(false);//used for fast i/o ll n;cin>>n; for(ll i=1;i<=n;i++) cin>>arr[i]; sort(arr,arr+n); ll cnt=0; for(ll i=1;i<=n-1;i++) { if(arr[i+1]-arr[i]==0) cnt++; } cout<<n-cnt<<endl; cin.tie(NULL); return 0; }
#include<bits/stdc++.h> using namespace std; int find_unique(int arr[], int size){ int ans = 0; for(int i = 0; i < size; i++){ ans = ans^arr[i]; // this is bitwise operator .its call XOR it's return only unique value.. } return ans; } void print_array(int arr[], int size){ for(int i = 0; i < size; i++){ cout << arr[i] << " "; } cout << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); // use for fast input and output.... int arr[5] = {1, 3, 5, 3, 1}; cout <<"Orginal array: " << endl; print_array(arr, 5); int result = find_unique(arr, 5); cout << result << endl; return 0; }