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;
}
Related
I am trying to write a C++ program to ask user to input a list of 5 numbers and print out the counts of the first number in the input. I have been trying to use array[] but I have some problems. The ideal inputs and outputs are :
Input : 1 1 2 3 1 Output: 3 because there are 3 counts of 1
Input : 1 2 3 4 5 Output: 1
Input : 1 1 1 0 0 Output: 3
Here are my codes, my code allows me to take the inputs but it does not do anything with it. Any help is appreciated!
#include <iostream>
using namespace std;
//frequency function
int frequency(int a[])
{
int count = 0;
for (int i=0; i < 6; i++)
if (a[i] == a[0])
{
count++;
}
cout << count << endl ;
return count;
}
// Driver program
int main() {
int i;
cout << "Please enter your numbers: ";
int a[5] = {a[0],a[1],a[2],a[3],a[4]};
for (i = 1; i < 6; i++)
{
// Reading User Input value Based on index
cin >> a[0] >> a[1] >> a[2]>> a[3] >> a[4];
return 0;
}
int n = sizeof(a)/sizeof(a[0]);
cout << frequency(a);
}
I tried another simpler approach but it needs a little more help
#include <iostream>
#include <string>
using namespace std ;
int main(){
cout << "Please enter your numbers: ";
int a[5];
int repeat;
int first = a[0];
int i;
for (i = 0; i < 6; i++)
{
// Reading User Input value Based on index
cin >> a[i];
}
if (a[i] == first){
repeat++;
}
cout << "Count: " << repeat;
}
you have an odd mixture of techniques for reading a set of numbers. You simply need
cout << "Please enter your numbers: ";
int a[5];
for (int i = 0; i < 5; i++)
{
// Reading User Input value Based on index
cin >> a[i];
}
and you certainly dont want that return as it will end the program
you would be better off using std::vector then you would not need to hard code the array size.
Note at the moment you have 6 as the arrays size in 'frequency' but 5 in main
I want to create a flag array to see whether an element is present or not.
Input:
2 1 4
+ 1
+ 2
- 1
- 2
Desired Output:
0 0 0
0 0 0
0 0 0
#include <iostream>
#include <stdio.h>
using namespace std;
// Create a function
// Function is passed with values n=2, m=1, q=4,
// and an array of string
// where str[0] = "+ 1", str[1] = "+ 2", str[2] = "- 1", str[3] = "- 2"
void func(int n, int m, int q, string s[])
{
// Create an array
int *array;
array = new int[n + 1];
// OUTPUT:: Print array element values to check elements
for (int i = 0; i <= n; i++)
{
cout << array[i] << " ";
}
cout << endl;
// Iterate over the string s[array]
for (int i = 0; i < q; i++)
{
// Check if str[i] starts with '+'
if (s[i][0] == '+')
{
// Set the index
int index = s[i][2];
// Set the array element to 1 to identify
array[index] = 1;
/*
Check if "index is correct" and "array[index] is set to 1" ----- YES YES YES
cout << "index is: " << s[i][2] << ". "
<< "ptr[s[i][2]] is: " << ptr[index] << endl;
*/
// OUTPUT:: Iterate over the array to see its elements
for (int j = 0; j <= n; j++)
{
cout << array[j] << " ";
}
cout << endl;
}
}
}
int main()
{
int n, m, q;
cin >> n >> m >> q;
cin.ignore();
string str[q];
for (int i = 0; i < q; i++)
{
getline(cin, str[i]);
}
func(n, m, q, str);
return 0;
}
Please check it. I have made it simple by writing comments in the above code.
I am new to C++ and do not understand why the array elements are not changing to 1.
Whether it is a new C++ concept, or my code has mistakes. As far as I know, it should work. But it is not working.
I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}
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";
}
so far this is my code what i am trying to do is say the user inputs 1 2 3 and then presses -1, he or she will be asked to input another set of numbers say 9 8 7, what my programs is suppose to do is display them out as such 1 2 3 9 8 7, but rather it is displaying them like this 6 6 6 6 6 6, basically it counts how many numbers there are and displays that amount of numbers with that number. So can anyone help me out here, how do i make it so that it displays the two sets of numbers combined?
#include <iostream>
#include <vector>
using namespace std;
vector<int> append(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for (i = 0; i < n; i++)
c[i] = a[i];
for (i = 0; i < m; i++)
c[n + i] = b[i];
return c;
}
int main()
{
cout << "Please enter a set of numbers, insert -1 when done.\n";
vector<int>a;
bool more = true;
while (more)
{
int n;
cin >> n;
if (n == -1)
more = false;
else
a.push_back(n);
}
cout << "Please enter another set of numbers, insert -1 when done.\n";
vector<int>b;
more = true;
while (more)
{
int m;
cin >> m;
if (m == -1)
more = false;
else
b.push_back(m);
}
vector<int>d = append(a,b);
{
int i;
for (i= 0; i < d.size(); i++)
cout << d.size() << "\n";
}
}
That's because at the end you're printing the size, not the value:
cout << d.size() << "\n";
Should be:
cout << d[i] << "\n";
It is because when you are printing it, you are printing d.size instead of d[i].
cout << d.size() << "\n";
Would needs to be:
cout << d[i] << endl;