The result wasn't what I expected what i expect - c++

The problem is to delete all the biggest number
for example:
cin: 1 2 3 4 5
cout: 1 2 3 4
cin: 5 1 2 3 5
cout: 1 2 3
cin: 5 5 1 2 5
cout: 1 2
cin: 5 5 5 1 5
cout: 1
and here is where things go wrong:
whenever my biggest number locate in the first and the last location with other location, the code print out the wrong result
please look at these example for better understanding:
cin: 5 5 1 2 5
expected cout: 1 2
but instead it cout: 5 1
cin: 5 5 1 5 5
expected cout: 1
but instead it cout: 5
I think the problem occured in the delete function but I can't figure out what went wrong no matter how many time i rechecked, i would be very happy if someone can help me solve this problem.
and sorry for my sloppy writing and bad english
here is my code:
#include <iostream>
using namespace std;
void Insert(int a[] ,int n)
{
for (int i=0; i<n; i++)
{
cout << "a[" << i << "]= ";
cin >> a[i];
}
}
void Delete(int a[], int n, int Biggestt)
{
int BiggestLocation;
for (int i=0; i<n-1; i++)
{
if (a[i]==Biggestt)
{
BiggestLocation=i;
}
}
for (int i=BiggestLocation; i<n-1; i++)
{
a[i]=a[i+1];
}
}
int Biggest(int a[],int n)
{
int Biggesttt=a[0];
for (int i=0; i<n; i++)
{
if (Biggesttt<a[i])
{
Biggesttt=a[i];
}
}
return Biggesttt;
}
void PrintOut(int a[],int n)
{
for (int i=0; i<n; i++)
{
cout << a[i] << " ";
}
}
int main()
{
int n,OriginalCount;
int Count=0;
cout << "Insert n: ";
cin >>n;
int a[100];
Insert(a,n);
int Biggestttt=Biggest(a,n);
for (int i=0; i<n-1; i++)
{
if(a[i]==Biggestttt)
{
Count++;
}
}
OriginalCount=Count;
while(Count!=0)
{
{
Delete(a,n,Biggestttt);
}
Count--;
}
if (a[n-1]==Biggestttt && OriginalCount==0)
{
PrintOut(a,n-1);
}
else if (a[n-1]!=Biggestttt && OriginalCount!=0)
{
PrintOut(a,n-OriginalCount);
}
else if (a[n-1]==Biggestttt && OriginalCount!=0)
{
PrintOut(a,n-OriginalCount-1);
}
return 0;
}

You are not far off. You biggest issues have to do with using void function () for all your functions. By using void as the type, you lose the ability to return valid (and needed) information.
For example in void Delete(int a[], int n, int Biggestt) the number of elements that remain in a[] will change as each element matching the Biggestt are removed from the array -- but you have no way of returning the final number of elements in the array after the removals take place. You can either change your return type from void to int and return an updated n, or you can pass n as a pointer parameter so when it is update within the function, its updated value is available back in the calling function when Delete() returns.
Additionally, your logic in main() is quite jumbled. You already have functions created to handle your needs, so main() should be relatively clean and have no more than a couple of variables to deal with. You could do something like:
int main (void)
{
int n, b,
a[MAXINT];
cout << "Insert n: ";
if (!(cin >> n)) { /* validate ALL user input */
cerr << "(invalid conversion or user canceled)\n";
return 1;
}
Insert (a, n); /* insert all array values */
cout << "original: "; /* output the original */
PrintOut (a, n);
b = Biggest (a, n); /* find the biggest number in the arry */
Delete (a, &n, b); /* delete all occurrences in array */
cout << "big deleted: "; /* output array with biggest removed */
PrintOut (a, n);
return 0;
}
(note: since your Delete() function has been left void a pointer to n was passed as a parameter so the final value of n after element deletion will be available back in the calling function (main() here))
Putting it altogether and making adjustments to the logic in Delete(), you could do something like the following:
#include <iostream>
using namespace std;
#define MAXINT 100
void Insert (int a[], int n)
{
for (int i=0; i<n; i++)
{
cout << "a[" << i << "]= ";
cin >> a[i];
}
}
void Delete(int *a, int *n, int Biggestt)
{
for (int i = 0; i < *n;)
{
if (*n > 1 && a[i] == Biggestt)
{
for (int j = i + 1; j < *n; j++)
a[j-1] = a[j];
(*n)--; /* if biggest removed, decrement n */
}
else
i++; /* only advance if biggest not removed at index */
}
}
int Biggest(int a[],int n)
{
int Biggesttt=a[0];
for (int i=1; i<n; i++)
{
if (Biggesttt<a[i])
{
Biggesttt=a[i];
}
}
return Biggesttt;
}
void PrintOut(int a[],int n)
{
for (int i=0; i<n; i++)
{
cout << " " << a[i];
}
cout << '\n';
}
int main (void)
{
int n, b,
a[MAXINT];
cout << "Insert n: ";
if (!(cin >> n)) { /* validate ALL user input */
cerr << "(invalid conversion or user canceled)\n";
return 1;
}
Insert (a, n); /* insert all array values */
cout << "original: "; /* output the original */
PrintOut (a, n);
b = Biggest (a, n); /* find the biggest number in the arry */
Delete (a, &n, b); /* delete all occurrences in array */
cout << "big deleted: "; /* output array with biggest removed */
PrintOut (a, n);
return 0;
}
Exmple Use/Output
$ ./bin/remove_biggest
Insert n: 5
a[0]= 5
a[1]= 1
a[2]= 2
a[3]= 3
a[4]= 5
original: 5 1 2 3 5
*n: 3
*n: 3
*n: 3
big deleted: 1 2 3
$ ./bin/remove_biggest
Insert n: 4
a[0]= 5
a[1]= 5
a[2]= 1
a[3]= 5
original: 5 5 1 5
*n: 1
big deleted: 1
What if all number in a[...] are the same? You have to be able to handle that case. The logic in Delete() now retains 1 number if the are all the same number. You may also choose to leave them ALL as there is no Biggestt. The are simultaneously the largest and smallest at the same time. How you handle it is up to you.
$ ./bin/remove_biggest
Insert n: 4
a[0]= 5
a[1]= 5
a[2]= 5
a[3]= 5
original: 5 5 5 5
*n: 1
big deleted: 5
If they were all the same Big number we just deleted all of them leaving 1 as it is also the minimum.
Using a Reference int& n Instead of a Pointer
In response to your comment and the suggestion by Fei Xiang, C++ allows you to pass a reference to n in Delete() instead of a pointer to ensure changes to n are visible back in the calling function (main here). The crux of the matter is when you simply pass a parameter to a function, the function receives a copy and any changes made to the variable within the function are lost on return. C++ provides a reference (e.g. int& n) which essentially passes an alias to the original and any changes made to the reference are changes made to the original. This is a refinement over passing the address of the variable because it does avoid having to dereference the pointer.
Using a reference, Delete() could be re-written as follows:
void Delete (int *a, int& n, int Biggestt)
{
for (int i = 0; i < n;)
{
if (n > 1 && a[i] == Biggestt)
{
for (int j = i + 1; j < n; j++)
a[j-1] = a[j];
n--; /* if biggest removed, decrement n */
}
else
i++; /* only advance if biggest not removed at index */
}
}
The call to Delete() in main() would be:
Delete (a, n, b); /* delete all occurrences in array */
And you have gotten rid of the so-called '*' marks :) (that Fei)

#include <iostream>
using namespace std;
void Insert(int a[] ,int n)
{
for (int i=0; i<n; i++)
{
cout << "a[" << i << "]= ";
cin >> a[i];
}
}
void Delete(int a[], int n, int Biggestt)
{
int BiggestLocation;
for (int i=0; i<n-1; i++)
{
if (a[i]==Biggestt)
{
a[i]=-1;
}
}
for (int i=1; i<n; i++)
{
if(a[i-1]==-1)
a[i-1]=a[i];
}
}
int Biggest(int a[],int n)
{
int Biggesttt=a[0];
for (int i=0; i<n; i++)
{
if (Biggesttt<a[i])
{
Biggesttt=a[i];
}
}
return Biggesttt;
}
void PrintOut(int a[],int n)
{
for (int i=0; i<n; i++)
{
cout << a[i] << " ";
}
}
int main()
{
int n,OriginalCount;
int Count=0;
cout << "Insert n: ";
cin >>n;
int a[100];
Insert(a,n);
int Biggestttt=Biggest(a,n);
for (int i=0; i<n-1; i++)
{
if(a[i]==Biggestttt)
{
Count++;
}
}
OriginalCount=Count;
while(Count!=0)
{
{
Delete(a,n,Biggestttt);
}
Count--;
}
if (a[n-1]==Biggestttt && OriginalCount==0)
{
PrintOut(a,n-1);
}
else if (a[n-1]!=Biggestttt && OriginalCount!=0)
{
PrintOut(a,n-OriginalCount);
}
else if (a[n-1]==Biggestttt && OriginalCount!=0)
{
PrintOut(a,n-OriginalCount-1);
}
return 0;
}
TRY THIS CODE.
Just equate all the instances of biggest number to -1 and later overwrite them with the neighboring elements which are not equal to -1.

Related

what should i write in main function to test my problem for t no of times?

for example, I have to take input in the format:
2 // no of test cases
7 // n->size of an array
9 7 5 9 2 20 3 //n array elements
5 // second test case array size
4 5 8 96 6 // second test case array elements
I don't know what to write in the main function.
void sort(int arr[],int n)
{
for(int i=1;i<n;i++)
{
int current =arr[i];
int j;
for(j=i-1;j>=0;j--)
{
if(current<arr[j])
{
arr[j+1]=arr[j];
}
else
{
break;
}
}
arr[j+1]=current;
}
}
int main(){
// what should I write in the main func to test my problem for t no of times
// I have to take all inputs first then print the sorted arrays given by the user
// separated by space and new line for the next sorted array
}
I think this what you want.
const int N = 10;
int main(){
int t, n, arr[N];
cin >>t;
for(int T;T<t;++T){
cin >>n;
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Make sure to put the value if N is the maximum possible size of the array. Or you can declare the array as a dynamic array with the entered n (or use one of the STL like vector)
for example:
int main(){
int t, n;
cin >>t;
for(int T;T<t;++T){
cin >>n;
int * arr = new int [n];
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Or by using Vector:
#include<vector>
using namespace std;
//your sort func here, but make sure to change it to have a vector instead of an array
int main(){
int t, n;
vector<int>arr;
cin >>t;
for(int T;T<t;++T){
arr.clear();
cin >>n;
arr.resize(n);
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
PS: I would recommend to see websites like codeforces, Hackerrank and others to practice on competitive programming question which contains a lot of question that will help (If you're interested)
int main()
{
int t; // number of test cases
std::cin >> t;
while (t--) // repeat t times
{
// what you had before
}
}
to test you can
define an input and a desired output, i.e an array "unsorted" and how it SHOULD look like after sorted
define a method that sorts input "a" and allows you to verify that by eather returning the sorted array or modifying the reference given as parameter.
defined a compare method that takes x1 and x2 as parameter and returns a bool indicating if the operation failed or no. x1 can be the desired sorted array and x2 the array returned from step1
loop in a for with DIFFERENT unsorted arrays and theis according sorted values...
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
cin >> size;
int *arr = new int[size];
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
sort(arr, size);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
cout << endl;
}
return 0;
}
I think this will work
this is a code example for what I mean
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int numOfTest = 0;
std::vector<int>vec;
std::cin>>numOfTest ;
for(int j=; j<=numOfTest; ++j) // loop for num of tests
{
int n=0;
for(int i=0; i<n; ++i) // loop for num of veriabels in one test
{
int var=0;
std::cin >> var;
vec.push_back(var);
}
// option one
int* arr = new int[n] ;
std::copy(vec.begin(),vec.end(),arr);
sort(arr, n);
//option two
sort(&vec[0], n);
//option three
sort(vec.data(), n);
for(int f=0; j<=n ++j)
{
std::cout << arr[f] << " "; // print the sorted array;
}
delete [] arr;
}
return 0;
}
if your choosing option two or three you can using range base loop instead of for loop:
it will look like this:
for(auto& e: vec)
{
std::cout << e << " ";
}

Getting a weird negative number in my output when using an array I modified in one function, in another function

I am writing a program that takes a user-inputted list of up to 25 integers, then prints the sorted list using bubble sorting, the sorted list in descending order, and some other info about the list like the median, minimum and maximum, and mode.
I have tested all of my functions within the program individually on an array I created using initializer lists (not from user input/cin) and they work fine, but when I run the program something is off. For example, when I input 1,2,3,4, the function that prints the sorted list in descending order prints 3,2,1, -858993460. It always leaves out the greatest integer and adds on -858993460 at the end no matter what values I put into the input array. Here's the relevant part of my code:
#include <iostream>
using namespace std;
void input(int ulist[26], int& n);
void Bubblesort(int ulist[26], int slist[26], int n);
void print(int list[26], int n);
int n;
void reversesort(int slist[26], int n);
void main()
{
int ulist[26], slist[26];
input(ulist, n);
cout << "Unsorted";
print(ulist, n);
cout << "Sorted";
Bubblesort(ulist, slist, n);
print(slist, n);
reversesort(slist, n);
cin >> n;
}
void input(int ulist[26], int& n)
{
int i(0), value;
cout << "enter value : \n";
cin >> value;
while (i < 25 && value != -999)
{
ulist[i] = value;
i++;
if (i < 25)
{
cin >> value;
}
}
n = i;
}
void Bubblesort(int ulist[26], int slist[26], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
slist[i] = ulist[i];
for (j = 25 - 1; j > 0; j--) //25 is Length of the array
for (i = 0; i < j; i++)
if (slist[i] > slist[i + 1])
{
temp = slist[i];
slist[i] = slist[i + 1];
slist[i + 1] = temp;
}
}
void print(int list[26], int n)
{
int i;
cout << " list of numbers are : \n";
for (i = 0; i < n; ++i)
{
cout << list[i] << '\n';
}
cout << "\n\n";
}
void reversesort(int slist[26], int n) //checked w online compiler, works
{
cout << "List of numbers in descending order is: \n";
for (int i = n - 1; i >= 0; --i)
cout << slist[i] << ", ";
cout << "\n";
}
I'm assuming this is some sort of memory problem and that the source of this has to do with passing slist, which was modified in the bubblesort function, through the functions I wrote. I'm pretty new to C++ (coming from python) so I'm assuming I'm missing something as far as passing arrays to functions is concerned.
EDIT: I guess to sum everything up - how can I take the data inputted in the input function and use that array in another function? And how can I take the array that has been sorted by the bubblesort function and use that array in another function?
The first instance of undefined behavior in your code is
if (slist[i] > slist[i + 1])
in Bubblesort.
Due to
for (j = 25 - 1; j > 0; j--)
for (i = 0; i < j; i++)
the maximum index accessed by this loop is slist[24] (24 from i + 1 where i < j and j = 25 - 1 = 24, so i = 23).
Your input is only 4 numbers, so only slist[0] through slist[3] are initialized. The remaining elements (slist[4] through slist[25]) are uninitialized. Reading from an uninitialized variable has undefined behavior.

How to debug my C++ program?

I try to enter 2d array and to sum all numbers in one row. Then I convert that number to binary (8 bit) and to set it again in new 2d array. Here's my code. I get output in negative numbers and I expect binary number.
I input
1 2 3
4 5 6
7 8 9
And i want this output
00000110
00001111
00011000
i get
00000000
00000000
00000000
#include<iostream>
using namespace std;
int main()
{
int n,m,j,i;
int a[50][50],b[50][8],c[50];
cin>>n>>m;
for(i=0;i<n;i++)
{
c[i]=0;
for(j=0;j<m;j++)
{
cin>>a[i][m];
cin.ignore();
c[i]+=a[i][j];
}
}
for(i=0;i<n;i++)
for(j=0;j<8;j++)
{
b[i][j]=c[i]%2;
c[i]/=2;
}
for(i=0;i<n;i++)
{
for(j=0;j<8;j++)
{
cout<<b[i][j];
}
cout<<endl;
}
}
I attempted to revise your code but I soon realised that you were doing some weird unnecessary things so I just started fresh and here's what I've got for you:
#include <iostream>
#include <vector>
using namespace std;
void add_array(int arr1[], int arr2[], int arrLength, int ret[]) {
for(int i = 0; i < arrLength; i++) {
ret[i] = arr1[i]+arr2[i];
}
return;
}
void to_binary(int n, vector<int> *ret) {
while(n!=0) {
ret->push_back(n%2==0 ?0:1);
n/=2;
}
}
int main() {
int a[5] = {1,2,3,4,5};
int b[5] = {6,7,8,9,10};
int c[5];
add_array(a, b, 5, c);
cout << "A:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << a[i] << endl;
}
cout << "B:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << b[i] << endl;
}
cout << "C:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << c[i] << endl;
}
vector<int> vec;
for(int i = 0; i < 5; i++) {
to_binary(c[i], &vec);
for(int j = 0; j < vec.size(); j++) {
cout << vec[j];
}
cout << endl;
vec.clear();
}
return 0;
}
I don't know how you were handling the adding of the two functions so I just wrote a really simple function there, I'll start with the parameters
int arr1[], int arr2[]
These are the two functions you'll be adding, simple.
int arrLength
This tells the function what the length of the two arrays is for the 'for loop'
int ret[]
Ret is the return array and is passed in so that it can be modified with the added arrays, now you could do that with either of the other two arrays but this is better practice especially if you want to reuse the other arrays later.
Now here's the function itself
for(int i=0;i<arrLength;i++){ ret[i]=arr1[i]+arr2[i];}
Here we loop through each position in the arrays and place them in the variable 'ret', this is the whole thing.
The function
void to_binary(int n, vector<int> *ret)
handles the decimal to binary using a vector for variable sizes, it's basically what you were doing just in a function.
In the function main we create the three arrays and call add_array with the necessary arguments, then we create the vector vec and then proceed to loop through the array c getting the binary number of each position and then since we stored the binary number in an int vector instead of a string we loop through the vector
for(int j = 0; j < vector.size(); j++)
We are using vector.size() to get the dynamic size of the vector, then we print out each binary digit and then print an endl and clear the vector for reuse.

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.

Count how many times elements in an array are repeated

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