This question already has answers here:
Deleting duplicates in the array
(2 answers)
Closed 8 years ago.
I need to write a program where I have to print the numbers which occur twice or more than twice in the array. To make things simpler, I am working on a sorted array.
Here is my code.
#include <stdio.h>
int main()
{
int n,i;
int a[10]={2,2,2,4,6,6,9,10,10,11};
printf("%d\n",a[10]);
for(i=0;i<10;++i)
{
if(a[i]==a[i+1] && a[i]!=a[i-1])
printf("%d ",a[i]);
else
continue;
}
return 0;
}
The code seems to work fine but I do not like my code because at some point, the loop compares the value of a[0] with a[-1] and a[9] with a[10] and both of these, a[-1] and a[10], are garbage values. I am sure there are better ways to do it but I am unable to think of any.
Also, I need to extend the above program to count the frequency of duplicate numbers.
Help is appreciated. Thanks!
First, you can't access a[10] in your printf line, this is outside your array.
This should work fine.
#include <stdio.h>
int main()
{
int n,i;
int a[10]={2,2,2,4,6,6,9,10,10,11};
for(i=0; i < 9; ++i)
{
if(a[i] == a[i+1])
if(i > 0 && a[i] == a[i-1])
continue;
else
printf("%d ",a[i]);
}
return 0;
}
Edit: Or you can use the shorter yet harder to read:
for(i=0; i < 9; ++i)
{
if(a[i] == a[i+1] && (!i || a[i] != a[i-1]))
printf("%d ",a[i]);
}
See code below for the solution, which will print only the duplicate numbers from the array and how many times they occur.
I added the int c which is used for your count. It is initially set to 1, and increased by 1 for each duplicate number.
#include <stdio.h>
using namespace std;
int main() {
int n,i,c;
int a[10]={2,2,2,4,6,6,9,10,10,11};
c = 1;
for(i=0; i < 9; ++i)
{
if (a[i] == a[i+1]) {
n = a[i];
c += 1;
} else {
if (c > 1) {
printf("Number: %d, Occurences: %d \n",n,c);
c = 1;
}
}
}
return 0;
}
Since the array is already sorted, it'd be easier to do something like this, with another loop inside the for loop.
int duplicateCount = 1; // Must be at least one instance of a value in the array
for(int i = 0; i < 9; ++i) {
int j = i;
while(j != 9 && a[j] == a[j + 1]) {
++j;
++duplicateCount;
}
i = j; // j is now at end of list of duplicates, so put i at the end as well,
// to be incremented to the next unique value at end of for loop iteration
printf("%d: %d\n", a[j], duplicateCount);
duplicateCount = 1; // Reset for next values
}
If you want to count the frequency of all the numbers, you can easily turn duplicateCount into an array of values to count the frequency of each unique value. For a better solution, you could use another data structure, such as a map.
You are really going to need to have two indexes that walk through your array.
Here's a start:
int i = 0;
int j;
while (i < 10) {
for (j = i+1; j < 10; ++j) if (a[i] != a[j]) break;
if (j !+ i+i) printf("%d\n", a[i]);
i = j;
}
You could use a functor, overload operator() and return a set (unique values). Assuming your array is sorted it's just a matter of comparing the previous one with the next and inserting it in the set if they equal. If they are not sorted then you have to go through the whole array for every entry. Below are two examples with output as an explanation.
#include <set>
using namespace std;
Unsorted array:
struct UnsortedArrayDuplicateEntries {
set<int> operator()(int* array, int size) {
set<int> duplicates;
for (int i = 0; i < size - 1; i++)
for (int j = i + 1;j < size; j++)
if (array[i] == array[j])
duplicates.insert(array[j]);
return duplicates;
}
};
Sorted array:
struct SortedArrayDuplicateEntries {
set<int> operator()(int* array, int size) {
set<int> duplicates;
for (int i = 0; i < size - 1; i++)
if (array[i] == array[i+1])
duplicates.insert(array[j]);
return duplicates;
}
};
Test sorted:
SortedArrayDuplicateEntries d;
int sorted[10]={2,2,2,4,6,6,9,10,10,11};
set<int> resultSorted = d(sorted,10);
for (int i : resultSorted) cout << i << endl;
Output sorted:
2
6
10
Test unsorted:
UnsortedArrayDuplicateEntries d;
int unsorted[10]={2,6,4,2,10,2,9,6,10,11};
set<int> resultUnsorted = d(unsorted,10);
for (int i : resultUnsorted) cout << i << endl;
Output unsorted:
2
6
10
I hope it helps!
#include <stdio.h>
int main(){
int i, a[10]={2,2,2,4,6,6,9,10,10,11};
int size = 10;
for(i=0;i<size;++i){
int tmp = a[i];
int c = 1;
while(++i < size && tmp == a[i])
++c;
if(c > 1)
printf("%d times %d\n", tmp, c);
--i;
}
return 0;
}
Related
I'm very new to C++ or even coding. I was trying to make a simple array sorter, where the I first input the number of elements that will be in the array and then input the elements. My outcome should be the array sorted in ascending order. I have not thought about the case if elements inserted are same. So I would love to get some help from you folks.
The main error that I'm facing is that only the first unsorted element is sorted while the rest are either interchanged or left the same.
int main(){
int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];
for (int i = 0;i<x;i++){
cin>>A[i];
}
for(int i=0;i<x;i++)
cout<<A[i]<<",";
int count=0;
if(count <= (x-1)){
for (int i=0;i<(x-1);i++){
if(A[i]>A[i+1]){
int a;
a = A[i];
A[i] = A[(i+1)];
A[i+1] = a;
}
else if(A[i]<A[i+1])
count++;
}
}
cout<<"Sorted array:";
for(int i=0;i<x;i++)
cout<<A[i]<<",";
return 0;
}
You declared a variable length array
int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];
because its size is not a compile-time constant.
However variable length arrays are not a standard C++ feature though some compilers have their own language extensions that support variable length arrays,
It is better to use the class template std::vector.
Another problem is that it seems you are trying to use the bubble sort method to sort the array. But this method requires two loops.
Here is a demonstration program that shows how the bubble sort algorithm can be implemented.
#include <iostream>
int main()
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << '\n';
for (size_t last = N, sorted = N; not ( last < 2 ); last = sorted)
{
for (size_t i = sorted = 1; i < last; i++)
{
if (a[i] < a[i - 1])
{
// std::swap( a[i-1], a[i] );
int tmp = a[i - 1];
a[i - 1] = a[i];
a[i] = tmp;
sorted = i;
}
}
}
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << '\n';
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
Let us try the following method:
find the largest element in the array and move it to the end, by swapping with the last element;
repeat with the array but the last element, and so on.
To find the largest element in A[0..m-1], scan the array and keep an index to the largest so far, let l. This index can be initialized to 0.
// Move the largest to the end
int l= 0;
for (int i= 1; i < m; i++)
{
if (A[i] > A[l]) l= i;
}
// A[l] is the largest in A[0..m-1]
Swap(A[l], A[m-1]);
// A[m-1] is the largest in A[0..m-1]
To sort, repeat with decreasing m. You can stop when the subarray just holds one element:
// Sort
for (int m= n-1; m > 1; m--)
{
// Move the largest to the end
....
}
Writing the Swap operation and assembling the whole code is your task. Also check
correctness of the Move for the limit cases m= 0, 1, 2.
correctness of the Sort for the limit cases n= 1, 2, 3.
how you could instrument the code to verify that the Move does its job.
how you could instrument the code to verify that the Sort does its job.
what happens in case of equal keys.
Your code can be fixed a bit to make it working.
Just replace if (count <= (x - 1)) with while (count < (x - 1)) and also set count = 0; at start of loop, plus replace else if (A[i] < A[i + 1]) with just else. And your code becomes working!
Necessary fixes I did in code below. Also I did formatting (indents and spaces) to make code looks nicer. Rest remains same.
As I see you have a kind of Bubble Sort.
Try it online!
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter no. of elements" << endl;
cin >> x;
int A[x];
for (int i = 0; i < x; i++) {
cin >> A[i];
}
for (int i = 0; i < x; i++)
cout << A[i] << ",";
int count = 0;
while (count < (x - 1)) {
count = 0;
for (int i = 0; i < (x - 1); i++) {
if (A[i] > A[i + 1]) {
int a;
a = A[i];
A[i] = A[(i + 1)];
A[i + 1] = a;
} else
count++;
}
}
cout << "Sorted array:";
for (int i = 0; i < x; i++)
cout << A[i] << ",";
return 0;
}
Input:
10
7 3 5 9 1 8 6 0 2 4
Output:
7,3,5,9,1,8,6,0,2,4,Sorted array:0,1,2,3,4,5,6,7,8,9,
If you are taking the size of array as input from user you have to create your array dynamically in c++ like
int *array=new int(x)
and after taking the inputs of the elements just run a nested loop from 0 to size and
the inner loop from 0 to size-1 and check if(A[i]>A[i+1]) if true then swap the values else continue
Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}
I am working on codechef practice problem in which I have to find longest common substring. ( Its practice problem so don't down vote )
Following wiki and some resources online I got the algorithm
https://en.wikipedia.org/wiki/Longest_common_substring_problem
After understanding I wrote the algorithm in c++ , but its compiling but not running successfully . Throwing error while assigning value to vector matrix .
An invalid parameter was passed to a function that considers invalid parameters fatal.
1) Whats wrong with my LCSubstring function
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
int LCSubString(string str1 , string str2) {
// create 2d matrix
vector<vector<int>> matrix;
int maxlength = 0;
for (int i = 0; i <= str1.length(); i++) {
for (int j = 0; j <= str2.length(); j++) {
if (i == 0 && j == 0) {
matrix[i][j] = 0;
continue;
}
if (str1[i - 1] == str2[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
maxlength = max(maxlength, matrix[i][j]);
}
else {
matrix[i][j] = 0;
}
}
}
return maxlength;
}
int main()
{
int t;
int count = 0;
string str;
int len;
cin >> t;
while (t--) {
cin>> str;
len = LCSubString(str, "chef");
if (len >= 2) {
count++;
}
}
cout << count << endl;
return 0;
}
You did not properly initialize std::vector<std::vector<int>> matrix. They do not automatically resize when you access them with [], you need to set the proper size beforehand, like this:
vector<vector<int>> matrix(str.length()+1);
for (int i = 0; i <= str1.length(); ++i)
matrix[i] = vector<int>(str2.length()+1, 0);
Additionally, you are not properly checking for i == 0 or j == 0. If only one of them is zero then the first if in your loop won't hit and you subsequently try to read string[-1]. I don't know whether it would be correct for your algorithm, but try using logical or (||) instead of and (&&).
So I'm creating a lottery ticket with random values and then sorting it. I'm not worried about the sorting technique since the teacher isn't looking for classes etc. on this assignment and it works, however, my ticket values that I produce - despite using srand (time(0)) and then later the rand() % 40 + 1 - which I think should make my randoms between 1-40... but mainTicket[0] always equals 0. Any ideas? Sorry about the formatting, made me add extra spaces and mess up my indention.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void mainLotto (int main[]);
void lottoSort (int ticketArr[]);
int main()
{
int mainTicket[5];
srand (time(0));
mainLotto(mainTicket);
do
{
lottoSort(mainTicket);
} while (mainTicket[0] > mainTicket[1] || mainTicket[1] > mainTicket[2] || mainTicket[2] > mainTicket[3] || mainTicket[3] > mainTicket[4] || mainTicket[4] > mainTicket[5]);
for (int i = 0; i < 5; i++)
{
cout << mainTicket[i] << "\n\n";
}
return 0;
}
///
/// <> Creates the actual lottery ticket
///
void mainLotto (int main[])
{
// Creating the ticket
for (int i = 0; i < 5; i++)
{
main[i] = rand() % 40 + 1;
}
}
///
/// <> Sorts the actual lottery ticket
///
void lottoSort (int ticketArr[])
{
// Sorting the ticket
for (int j = 0; j < 5; j++)
{
if (ticketArr[j] > ticketArr[j+1])
{
int temp;
temp = ticketArr[j+1];
ticketArr[j+1] = ticketArr[j];
ticketArr[j] = temp;
}
}
}
I see two problems with your arrays being accessed out of bounds:
Here:
int main()
{
int mainTicket[5];
srand(time(0));
mainLotto(mainTicket);
do
{
lottoSort(mainTicket);
}
while(mainTicket[0] > mainTicket[1] || mainTicket[1] > mainTicket[2]
|| mainTicket[2] > mainTicket[3] || mainTicket[3] > mainTicket[4]);
// || mainTicket[4] > mainTicket[5]); // OUT OF BOUNDS!!!
for(int i = 0; i < 5; i++)
{
cout << mainTicket[i] << "\n\n";
}
return 0;
}
And here:
void lottoSort(int ticketArr[])
{
// Sorting the ticket
for(int j = 0; j < 4; j++) // j < 4 NOT 5!!! <== WAS OUT OF BOUNDS
{
if(ticketArr[j] > ticketArr[j + 1])
{
int temp;
temp = ticketArr[j + 1];
ticketArr[j + 1] = ticketArr[j];
ticketArr[j] = temp;
}
}
}
Likely the sort routine was dragging in a zero from out side the array bounds.
I just printed the item you claim to be always zero, after the mainLotto() and it yielded 30.
I suspect the problem lies where you tell us not to look. :)
In the sorting function you do:
for (int j = 0; j < 5; j++) {
if (ticketArr[j] > ticketArr[j + 1]) {
The array is of size 5. Your j will take eventually a value equal to 4.
Then you do ticketArr[j + 1], which is actually an out of bound access.
The fix is to go until 4 in your loop, not 5.
As Galik said, mainTicket[4] > mainTicket[5] is also an out of bounds access and after reading my answer, you should be able to understand why. :)
I need to get the unique value from 2 int arrays
Duplicate is allowed
There is just one unique value
like :
int arr1[3]={1,2,3};
int arr2[3]={2,2,3};
and the value i want to get is :
int unique[]={1}
how can i do this?
im already confused in my 'for' and 'if'
this was not homework
i know how to merge 2 arrays and del duplicate values
but i alse need to know which array have the unique value
plz help me :)
and here is some code i did
int arr1[3]={1,2,3}
int arr2[3]={2,2,3}
int arrunique[1];
bool unique = true;
for (int i=0;i!=3;i++)
{
for (int j=0;j!=3;j++)
{
if(arr1[i]==arr2[j])
{
unique=false;
continue;
}
else
{
unique=true;
}
if(unique)
{
arrunique[0]=arr1[i]
break;
}
}
cout << arrunique[0];
Assuming:
You have two arrays of different length,
The arrays are sorted
The arrays can have duplicate values in them
You want to get the list of values that only appear in one of the arrays
including their duplicates if present
You can do (untested):
// Assuming arr1[], arr2[], and lengths as arr1_length
int i = 0,j = 0, k = 0;
int unique[arr1_length + arr2_length];
while(i < arr1_length && j < arr2_length) {
if(arr1[i] == arr2[j]) {
// skip all occurrences of this number in both lists
int temp = arr1[i];
while(i < arr1_length && arr1[i] == temp) i++;
while(j < arr2_length && arr2[j] == temp) j++;
} else if(arr1[i] > arr2[j]) {
// the lower number only occurs in arr2
unique[k++] = arr2[j++];
} else if(arr2[j] > arr1[i]) {
// the lower number only occurs in arr1
unique[k++] = arr1[i++];
}
}
while(i < arr1_length) {
// if there are numbers still to read in arr1, they're all unique
unique[k++] = arr1[i++];
}
while(j < arr2_length) {
// if there are numbers still to read in arr2, they're all unique
unique[k++] = arr2[j++];
}
Some alternatives:
If you don't want the duplicates in the unique array, then you can skip all occurrences of this number in the relevant list when you assign to the unique array.
If you want to record the position instead of the values, then maintain two arrays of "unique positions" (one for each input array) and assign the value of i or j to the corresponding array as appropriate.
If there's only one unique value, change the assignments into the unique array to return.
Depending on your needs, you might also want to look at set_symmetric_difference() function of the standard library. However, its treatment of duplicate values makes its use a bit tricky, to say the least.
#include <stdio.h>
#include <stdlib.h>
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
int main()
{
int arr1[5] = {5,4,6,3,1};
int arr2[3] = {5, 8, 9};
int unique[8];
qsort(arr1,5,sizeof(arr1[0]),cmp);
printf("\n");
qsort(arr2,3,sizeof(arr2[0]),cmp);
//printf("%d", arr1[0]);
int i = 0;
int k = 0;
int j = -1;
while (i < 5 && k < 3)
{
if(arr1[i] < arr2[k])
{
unique[++j] = arr1[i];
i++;
}
else if (arr1[i] > arr2[k])
{
unique[++j] = arr2[k];
k++;
}
else
{
i++;
k++;
}
}
//int len = j;
int t = 0;
if(i == 5)
{
for(t = k; t < 3; t++)
unique[++j] = arr2[t];
}
else
for(t = i; t < 5; t++)
unique[++j] = arr2[t];
for(i = 0; i <= j; i++)
printf("%d ", unique[i]);
return 0;
}
This is my codes,though there is a good answer .
I didn't realize the idea that know which array have the unique value.
I also think that the right answer that you chose didn't , either.
Here is my version of the algorithm for finding identical elements in sorted arrays on Python in C ++, it works in a similar way
def unique_array(array0 : (int), array1 : (int)) -> (int):
index0, index1, buffer = 0, 0, []
while index0 != len(array0) and index1 != len(array1):
if array0[index0] < array1[index1]:
buffer.append(array0[index0])
index0 += 1
elif array0[index0] > array1[index1]:
buffer.append(array1[index1])
index1 += 1
else:
index0 += 1; index1 += 1
buffer.extend(array0[index0 : len(array0)])
buffer.extend(array1[index1 : len(array1)])
return buffer