Question: Find unique elements from the given array and print them
I have dry run below given code many times but i am not getting what is the problem in the code.
#include <iostream>
using namespace std;
void findingUniqueElement(int array[], int size)
{
int brray[100];
int count = 0;
bool equal = 0;
for (int i = 0; i < size; i++)
{
equal = 0;
int value = array[i];
for (int j = 0; j < size; j++)
{
if (i != j && value == array[j])
{
equal = 1;
break;
}
}
if (equal == 0)
{
brray[i] = value;
count++;
}
}
for (int i = 0; i < count; i++)
{
cout << brray[i] << " ";
}
}
int main()
{
int arr[6] = {1, 2, 2, 5, 3, 7};
findingUniqueElement(arr, 6);
}
i was expecting as an output
1 5 3 7
but when i run the code, getting as output
1 1877357483 1878039440 5
Welcome to SO! Here is the code modified by me:
#include <cstring>
#include <iostream>
using namespace std;
void findingUniqueElement(int array[], int size) {
int brray[100];
memset(brray, 0, 100); // modified here
int count = 0;
bool equal = 0;
for (int i = 0; i < size; i++) {
equal = 0;
int value = array[i];
for (int j = 0; j < size; j++) {
if (i != j && value == array[j]) {
equal = 1;
break;
}
}
if (equal == 0) {
brray[i] = value;
count++;
}
}
for (int i = 0; i < size; i++) { // modified here
if (brray[i] != 0) // modified here
cout << brray[i] << " ";
}
}
int main() {
int arr[6] = {1, 2, 2, 5, 3, 7};
findingUniqueElement(arr, 6);
}
I modified three places in your code:
You should initialize brray when you declare it, the strange values output are because they were in the memory when you defined brray, you should clean the memory before you use it.
The way you store unique number in brray is not very correct, when array[i] is not unique, you will add i, which leave 0 at brray[i], so to fit your code, you should make i from 0 to size. To get more clear about what I'm talking about, you can check the memory of brray.
Since I assume there is no 0 in your test data, so if there is a 0 in barray, you know it is not a valid value, just skip it. Also, you can use a more elegant way to do this, like #Anand Sowmithiran commented:
int brray[100];
memset(brray, 0, 100);
int count = 0;
for (/* conditions... */) {
// if there is a unique number
brray[count++] = unique_number;
}
for (int index = 0; index < count; index++) {
cout << brray[index] << " ";
}
Hope my answer is helpful!
Related
I wanna sort an array from largest to smallest number and make a new array which has it sorted...
so here is my code:
#include <iostream>
using namespace std;
int main()
{
int size, sum = 0, answer = 0,pos, max;
int array[size];
int array2[size];
cin >> size;
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
When I put my input:
5
1 2 3 4 5
The output I get is:
0, 0, 0, 0, 5,
but I expect it to be 5, 4, 3, 2, 1,
First of all always initialize a variable when you create it as by default it has some garbage value in C++,
Also you are trying to assign a size variable (as size for an array) that has nothing assign to it yet which will create problems, Secondly you are initializing an array first and then you are taking the size variable from user which is completely opposite of the flow, for creating arrays with dynamic size see How Dynamic Array works and is implemented in C++
Updated Code:
#include <iostream>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
int array[size];
int array2[size];
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Here is the Output
Edit:
As Per #PaulMcKenzie method, the other way which is considered the appropriate one, uses the std::Vector method to initialize a dynamic array in C++, people who use the first method in visual studio might face errors,
Second Method Updated Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
std::vector<int> array(size), array2(size);
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Second Output
The size of an array variable must be a compile-time constant. A user-supplied value at runtime is probably unknowable at compile time.so I recommend using std::vector instead of array.
#include <iostream>
#include<vector>
#include <algorithm>
int main()
{
int size=0, input=0;
std::cout << "enter size :";
std::cin >> size;
std::vector<int> vec;
for (size_t i{ 0 }; i < size; ++i)
{
std::cout << "enter "<<i<< ".input:";
std::cin >> input;
vec.push_back(input);
}
// Sort the elements of the vector in descending order
for (const auto& i : vec)
std::sort(vec.begin(), vec.end(), std::greater <>());
//Print the elements of the vector
for (const auto& i : vec)
std::cout << i << " ,";
return 0;
}
Output:
enter size :5
enter 0.input:1
enter 1.input:2
enter 2.input:3
enter 3.input:4
enter 4.input:5
5 ,4 ,3 ,2 ,1 ,
I want to find duplicate elements in a dynamic array. In most cases it works, but how can it work for this case. I'm finding duplicate elements in a given array. But there is one problem that my duplicate elements can repeat too. How can I solve that part.
#include <iostream>
int main() {
unsigned n;
std::cin >> n;
int count = 0;
int* dynArr = new int[n];
for (int i = 0; i < n; i++) {
std::cin >> dynArr[i];
}
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(dynArr[j] == dynArr[i]){
std::cout<<dynArr[j]<<" ";
break;
}
}
}
}
I have a problem with this part. When I'm inputting a my array length 6, and elements {1,1,2,1,2,2}.
I got (1,1,2,2).
But I need to get only 1,2.
input 6
1 1 2 1 2 2
output 1 1 2 2
but must be
output 1 2
Here's a simple and fast solution.
std::map<int,size_t> element_count;
for(int i = 0; i < n; i++){
if ( ++element_count[dynArr[i]] == 2 ){
// Only report on the second occurrance
std::cout<<dynArr[j]<<" ";
}
}
const int listSize = 5;
int list1[listSize] = {0,0,1,1,3};
bool dupList[listSize] = {false};
for (int index = 0; index < listSize; index++) {
int val = list1[index];
for (int i = 0; i < listSize; i++) {
if (i != index) {
if (list1[i] == val) {
dupList[index] = true;
}
}
}
}
int printList[listSize];
int addNum = 0;
for (int index = 0; index < listSize; index++) {
if (dupList[index] == true) {
bool run = true;
int print = list1[index];
for (int i = 0; i < listSize; i++) {
if (printList[i] == print) {
run = false;
}
}
if (run == true) {
std::cout << print << " ";
printList[addNum] = print;
addNum++;
}
}
}
Note this code will NOT run quickly at all only use it if the operation does not need to get run very many times but it will only display the single numbers that are duplicates. It will defernatly need to get optimised more
You can simply get it done using two std::set<int>s.
#include <set>
#include <iostream>
int main() {
unsigned n;
std::cin >> n;
int count = 0;
std::set<int> all;
std::set<int> redundant;
for (int i = 0; i < n; i++) {
int input = 0;
std::cin >> input;
// You cant enter the entry because its present. This will return a std::pair<,> with the second value false.
if (!all.insert(input).second)
redundant.insert(input); // We store this in another set so we dont duplicate the redundant entries.
}
for (auto itr = redundant.begin(); itr != redundant.end(); itr++)
std::cout << *itr << " ";
}
How can I change my code to get a count for every element?
With my code everything is okay. And it works, but how can I change only that part?
#include <iostream>
#include <vector>
void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Skip this element if already processed
if (visited[i] == true)
continue;
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
std::cout<<count<<" ";
}
}
int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++){
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}
And about the result`
input 10
1 1 2 2 3 3 4 4 5 5
output 2 2 2 2 2
but I want to get
output 2 2 2 2 2 2 2 2 2 2
(for every element)
Your function contains extra code that ends up confusing you. The visited variable is essentially unnecessary. Start the count at 0 and make no special case for the "current" cell and you'll find that some very simple code will do what you need:
void countFreq(int arr[], int n)
{
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Count frequency
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
std::cout << count << " ";
}
}
You need to save the result to an array for each number. Then when you find any processed number then print counter from the saved array.
#include <iostream>
#include <vector>
#include <unordered_map>
void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);
std::unordered_map<int, int> counter;
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++)
{
// Skip this element if already processed
if (visited[i] == true)
{
std::cout << counter[arr[i]] << " ";
continue;
}
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
visited[j] = true;
count++;
}
}
counter[arr[i]] = count;
std::cout<<count<<" ";
}
}
int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++)
{
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}
The issue is that you discard the values already visited.
One possibility is instead to memorize the count when the value is visited the first time,
and to memorize the index value of the first value appearance, when a value is visited the 2nd, 3rd ... time.
#include <iostream>
#include <vector>
void countFreq(const std::vector<int>& arr) {
int n = arr.size();
// Mark all array elements as not visited
std::vector<int> mem_count(n, n);
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Skip this element if already processed
if (mem_count[i] != n) {
std::cout << mem_count[mem_count[i]] << " ";
continue;
}
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
mem_count[j] = i;
count++;
}
}
mem_count[i] = count;
std::cout << count << " ";
}
}
int main() {
int n;
std::cin>>n;
std::vector<int> arr(n);
for(int i = 0; i < n; i++){
std::cin >> arr[i];
}
countFreq(arr);
return 0;
}
You can find the frequencies of numbers this way if you know the what is your maximum element in the input array. lets say m is maximum number in your array.
so you have to create a new array of size m. you can simply co-relate them as m buckets. from 0 to m. And each bucket will hold the count of each element in the input array. The index of each bucket will refer to element in the input array. This has time complexity O(1) if we know what is the max element the array.
You can do this way:
std::vector<int> frequencey(std::vector<int>& nums){
auto max = *(std::max_element(nums.begin(), nums.end()));
std::vector<int> frequencies(max + 1, 0);
for(int i = 0; i < nums.size(); ++i){
frequencies[nums[i]] +=1;
}
return frequencies;
}
This is very simple
#include <vector>
#include <map>
#include <iostream>
void main()
{
std::vector<int> v { 1,1,2,2,3,3,4,4,5,5 }; // Your input vector
// Count "frequencies"
std::map<int, int> m;
for (auto i : v)
m[i]++;
// Print output
for (auto i : v)
std::cout << m[i] << " ";
}
I am trying to write a program which checks if 3 (or more) elements of an array are the same.
I have written a code which works almost perfectly, but it gets stuck when there are 3 pairs of equal elements and I'm not sure how to fix it.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, a[10],skirt=0;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
cout<<skirt<<endl;
if(skirt>=3)
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
}
When I input
6
3 3 2 2 1 1 i
get "TAIP" but I need to get "NE".
You can use the following algorithm: first sort the array. Then iterate each adjacent pair. If they are equal, then increment counter, if not then reset counter to 1. If counter is 3, return true. If loop does not return true, then return false.
Add the following condition in the outer for loop
for(int i = 0; i < n - 2 && skirt != 3; i++)
^^^^^^^^^^^^^^^^^^^^^^^
{
skirt = 1;
^^^^^^^^^
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
Of course before the loop you should check whether n is not less than 3. For example
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
}
Here is a demonstrative program
#include <iostream>
using namespace std;
int main()
{
int a[] = { 6, 3, 3, 2, 2, 1, 1 };
int n = 7;
int skirt = 0;
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if ( a[i] == a[j] )
{
skirt++;
}
}
}
}
cout << skirt << endl;
if ( skirt == 3 )
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
return 0;
}
Its output is
1
NE
because the array does not have 3 equal elements.
Reset skirt to 0 every time you increase i if it is less than 3, or break out the loop otherwise.
Another way to do this is using a std::map, which keeps a count of the number of times a given value occurs in your array. You would stop looking as soon as you have a number that has three occurrences.
Here's a 'minimalist' code version:
#include <iostream>
#include <map>
using std::cin; // Many folks (especially here on SO) don't like using the all-embracing
using std::cout; // ... statement, "using namespace std;". So, these 3 lines only 'use'
using std::endl; // ... what you actually need to!
int main() {
int n, a[10], skirt = 0;
std::map<int, int> gots;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n && skirt < 3; i++) {
skirt = 1;
if (gots.find(a[i]) != gots.end()) skirt = gots[a[i]] + 1;
gots.insert_or_assign(a[i], skirt);
}
cout << (skirt >= 3 ? "TAIP" : "NE") << endl;
return 0;
}
I'm not saying this is any better (or worse) than the other answers - just another way of approaching the problem, and making use of what the Standard Library has to offer. Also, with this approach, you could easily modify the code to count how many numbers occur three or more times, or any number of time.
Feel free to ask for further clarification and/or explanation.
I'm trying to write a function that will return the smallest value of an array. So far I have this, but all it returns is 0.
I don't see how it would return 0 since I am using a for loop to cycle through the array. Perhaps it is not cycling through the arrays values as I would think it does. Can anyone elaborate on the logic and the fallacy in this code?
#include <iostream>
using namespace std;
int newArray[9] = {4,5,9,3,6,2,1,7,8};
int minArray()
{
int index = 1;
int minimum;
for (int i = 0; i < 9; i++)
{
if (newArray[i] > newArray[index])
{
minimum = newArray[index];
}
index++;
}
return minimum;
}
int main()
{
cout << "original array:\n ";
for (int i = 0; i < 9; i++)
{
cout << newArray[i] << ", ";
}
cout << "minimum value of array: ";
cout << minArray();
return 0;
}
A good idea might be to initialize minimum with an element in the array.
So:
minimum = newArray[0]
In your loop (pseudocode assuming you don't want the answer):
if: newArray[pos] < minimum
minimum = newArray[pos];
I'd do something like this:
#include <iostream>
int minArray(int a[], int size) {
if (size <= 0) return 0; //
int m = a[0];
for (int i = 1; i < size; ++i) {
if (a[i] < m) m = a[i];
}
return m;
}
int main() {
int a[] = { 4, 3, 6, 2 };
std::cout << minArray(a, 4);
return 0;
}
You should initialize minimum with some known value or with maximum integer value.
int minArray()
{
int minimum = newArray[0];
for (int i = 1; i < 9; i++)
{
if (minimum > newArray[i])
{
minimum = newArray[i];
}
}
return minimum;
}
And you are dealing wrong with index (actually you don't need it at all). Example of how index can be used instead of minimum:
int minArray()
{
int index = 0;
for (int i = 1; i < 9; i++)
{
if (newArray[index] > newArray[i])
{
index = i;
}
}
return newArray[index];
}
Both examples should work fine, but I recommend to use first.
The minimum variable should be initially assigned to a value in the array, then compare each element in the array with minimum. If less than, assign minimum with that value:
int minArray()
{
int minimum = newArray[0];
int index = 0;
for (int i = 0; i < 9; i++)
{
if (newArray[i] < minimum)
{
minimum = newArray[i];
}
index++;
}
return minimum;
}