Program to print duplicate values of array only once in C++ - c++

int array[5]={3,3,3,3,1,1};
output:
3 1
I am unable to do this, please help me out. I tried 2 for loops with boolean check , it didn't work.
int main()
{
int a[5]={3,3,3,1,1};
int n=sizeof(a)/sizeof(a[0]);
for (int i =0 ; i<n; i++){
bool checked=true;
for (int j=0 ;j<i; j++){
if(a[i]==a[j]){
bool checked=false;
}
}
if(checked==true){
cout<<a[i]<<",";
}
}
}

I used a function to remove duplicate values from the array and then printed the array without the duplicates. I don't have boolean functions.
int removeDuplicate (int arr[], int size) {
if (size == 0 || size == 1) {
return size;
}
int* temp = new int[size]; /* Create a temporary
array with size*/
int j = 0;
for (int i = 0; i < size - 1; i++) {
if (arr[i] != arr[i + 1]) {
temp[j++] = arr[i]; //strore element if its unique
}
}
temp[j++] = arr[size - 1];
for (int i = 0; i < j; i++) {
arr[i] = temp[i]; //modify the existing array
}
return j; //j is the new size for the array without duplicates
}
int main(){
int arr[5] = {3,3,3,1,1};
int size = removeDuplicate(arr, 5);
for (int i = 0; i < size; i++) {
cout << arr[i] << " ; ";
}
}

Please note bool checked=false; you are defining again checked variable.
Please see the fix.
int main()
{
int a[5]={3,3,3,1,1};
int n=sizeof(a)/sizeof(a[0]);
for (int i =0 ; i<n; i++)
{
bool checked=true;
for (int j=i+1 ;j<n; j++)
{
if(a[i] == a[j])
{
checked=false;
}
}
if(checked == true)
{
std::cout<<a[i]<<",";
}
}
}
output : 3,1,
Even you can do it in a better way with std::unique algorithm.
#include <iostream> // std::cout
#include <algorithm> // std::unique, std::distance
#include <vector> // std::vector
int main () {
int a[5]={3,3,3,1,1}; // 3 3 3 1 1
std::vector<int> myvector (a, a+5);
// Sorting the array
std::sort(myvector.begin(), myvector.end());
// using default comparison:
auto it = std::unique (myvector.begin(), myvector.end());
myvector.resize( std::distance(myvector.begin(), it));
// print out content:
std::cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
output : myvector contains: 3 1

Related

SelectionSort in c++ not sorting*

I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.

Showing the original index of an element in a vector after bubblesort

I'm new to c++ and i'm having a problem with my code. I need to show the original indexes of a vector before it was sorted, after sorted. I tried it like this:
#include <vector>
using namespace std;
void bubblesort(vector<int> &a, int n) {
for (int j = 0; j < n - 1; j++) {
for (int i = n - 1; i > j; i--) {
if (a.at(i) < a.at(i-1)) {
int aux = a.at(i);
a.at(i) = a.at(i-1);
a.at(i-1) = aux;
}
}
}
}
int main()
{
int n;
cout << "Digite o tamanho do vetor: ";
cin >> n;
vector<int> v;
vector<int> vold;
vector<int> pos;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
vold.push_back(a);
}
bubblesort(v, n);
for (int i = 0; i < n; i++) {
if (vold.at(i) == v.at(i)) {
pos.push_back(i);
}
else {
for (int j = i+1; j < n - 1; j++) {
if (vold.at(i) == v.at(j)) {
pos.at(j) = i;
break;
}
}
}
}
for (const int& i : pos) {
cout << i << " ";
}
system("pause>0");
}
But it didn't worked, if someone could help me to see what I'm doing wrong I would be glad, thanks in advance.
If your goal is to show the indices of the sorted vector, then another approach is to not sort the original vector, but instead to sort a vector of index values based on the original vector.
The index vector would be initialized to 0, 1, 2, etc. up until the vector's size, minus 1.
Here is an example:
#include <vector>
#include <numeric>
#include <iostream>
void bubblesort(std::vector<int> &a, std::vector<int>& index)
{
// Make sure the index vector is the same size as
// the original
index.resize(a.size());
if ( a.size() <= 1 )
return;
// This is just a shortcut way of setting the values to 0,1,2,etc.
std::iota(index.begin(), index.end(), 0);
size_t n = a.size();
// Here is your sort, but with one difference...
for (size_t j = 0; j < n - 1; j++)
{
for (size_t i = n - 1; i > j; i--)
{
// Look at the comparison being done here using the index array
if (a.at(index[i]) < a.at(index[i-1]))
{
// We swap the index values, not the values
// in the vector
int aux = index.at(i);
index.at(i) = index.at(i-1);
index.at(i-1) = aux;
}
}
}
}
int main()
{
std::vector<int> v = {3, 1, 65, 23, 4};
std::vector<int> index;
bubblesort(v, index);
// Display the index values of the sorted items
for (const int& i : index)
std::cout << i << " ";
}
Output:
1 0 4 3 2
Note that the bubblesort function takes a vector of indices, and not n. There is no need to pass n, since a vector already knows its own size by utilizing the size() function.
The output shows the original index of each of the sorted items.

find frequency in array using vector

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] << " ";
}

C++ Selection Sort (vectors)

int temp;
for (int j = 0; j < vecsize - 1; ++j) {
int min = sort.at(j);
for (int i = j+1; i < vecsize; ++i) {
if (min > sort.at(i)) {
min = sort.at(i);
temp = i;
}
}
swap(sort.at(j), sort.at(temp));
}
I am trying to sort (in ascending order) the vector of: 23 42 4 16 8 15
However, my attempt at using selection sort outputs: 4 8 15 23 16 42
What am I doing wrong?
When you define min, you seem to be assigning it the value of the array sort at jth index. Yet, you are using an extra variable tmp to swap the elements, and you seem to fail to initialize it before the inner for loop, similar to how you initialize min. And if all the other elements in the array are smaller than the element at sort[j], tmp will be uninitialized for that iteration of the outer loop, possibly causing it to have an incorrect value in it.
int temp;
for (int j = 0; j < vecsize - 1; ++j) {
int min = sort.at(j);
temp = j; # HERE'S WHAT'S NEW
for (int i = j+1; i < vecsize; ++i) {
if (min > sort.at(i)) {
min = sort.at(i);
temp = i;
}
}
swap(sort.at(j), sort.at(temp));
}
You may see this code at work here. It seems to produce the desired output.
Try this : corrected-code
#include <iostream>
#include <vector>
using namespace std;
void print (vector<int> & vec) {
for (int i =0 ; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout << endl;
}
int main() {
int temp;
vector<int> sort;
sort.push_back(23);
sort.push_back(42);
sort.push_back( 4);
sort.push_back( 16);
sort.push_back( 8);
sort.push_back(15);
print(sort);
int vecsize = sort.size();
for (int j = 0; j < vecsize - 1; ++j) {
int min = j;
for (int i = j+1; i < vecsize; ++i) {
if (sort.at(min) > sort.at(i)) {
min = i;
}
}
if (min != j)
swap(sort.at(j), sort.at(min));
}
print(sort);
return 0;
}
If you can use C++11, you can also solve sorting (as in your example) with lambdas. It's a more powerful and optimized way. You should try it maybe in the future.
[EDITED]:
A short example:
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> myVector;
myVector.emplace_back(23);
myVector.emplace_back(42);
myVector.emplace_back(4);
myVector.emplace_back(16);
myVector.emplace_back(8);
myVector.emplace_back(15);
std::sort(myVector.begin(), myVector.end(),
[](int a, int b) -> bool
{
return a < b;
});
}

Program Times Out When Only Blank Newline Is Entered

The assignment was to write a program that receives numbers as an inputs (each one on a new line) and then sorts them from smallest to largest. The way to end the input is to enter a blank newline after the numbers are entered. My program works fine except for when I enter only a blank line. Then the program times out.
Here is my code:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
void sort(vector<int>& v)
{
for(int i = 0; i < v.size() - 1; ++i)
{
int min = i;
for(int j = i; j < v.size(); ++j)
{
if(v[j] < v[min])
{
min = j;
}
}
if(min != i){
int temp = v[min];
v[min] = v[i];
v[i] = temp;
}
}
}
void print(vector<int> v)
{
for(int i = 0; i < v.size(); ++i)
{
cout << v[i];
if(i != v.size() - 1)
{
cout << ", ";
}
}
cout << endl;
}
int main()
{
cout << "Enter integers (one on each line, entering an empty line quits):" << endl;
vector<int> v;
string str;
while(getline(cin, str))
{
if(str == "")
{
cout << "Sorted: ";
break;
}
else
{
v.push_back(atoi(str.c_str()));
}
}
sort(v);
print(v);
return 0;
}
Any help is appreciated.
You don't check for empty vector in sort() and v.size() - 1 causes integer underflow. Add check for empty vector:
void sort(vector<int>& v)
{
if (!v.empty()) {
for(int i = 0; i < v.size() - 1; ++i)
{
int min = i;
for(int j = i; j < v.size(); ++j)
{
if(v[j] < v[min])
{
min = j;
}
}
if(min != i){
int temp = v[min];
v[min] = v[i];
v[i] = temp;
}
}
}
}