Issue with C++ Srand Values - c++

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. :)

Related

Generate numbers from 2 to 10,000. The numbers printed can only be a multiple of 2 prime numbers

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

C++ Birthday Probability

I am trying to teach myself C++ in preparation for graduate school this coming fall but I am having some trouble with this birthday paradox problem. My code seems to run ok but I am not getting the correct output. If anyone has any suggestions please let me know.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
const int trials = 100000;
int birthdays[50];
int numMatches;
for(int i = 2; i <= 50; i++)
{
numMatches = 0;
for(int j = 1; j <= trials; j++)
{
for(int k = 1; k <= i; k++)
{
birthdays[k] = (rand() % 365) + 1;
}
int m = 1;
bool matched = false;
while(m < i && !matched){
int n = m + 1;
while(n <= i && !matched){
if(birthdays[m] == birthdays[n]){
numMatches++;
matched = true;
}
n++;
}
m++;
}
}
cout << "Probability of " << i << " people in a room sharing a birthday is \t"
<< ( float(numMatches) / float(trials) ) << endl;
}
}
Your code is not computing the probability of two people in a room of 50 sharing a birthday. There's several bugs, mostly with indexing, but here's the biggest issue:
for(int j = 1; j <= trials; j++) {
// assigns a random birthday to the first i people (should be 0 indexed)
for(k = 1; k <= i; k++)
birthdays[k] = (rand() % 365) + 1;
// Does *exactly* the same thing as the previous loop, overwriting what
// the initial loop did. Useless code
for(m = 1; m <= i; m++)
birthdays[m] = (rand() % 365) + 1;
// At this point, m = k = i + 1. Here you check if
// the i + 1st array value has the same b-day. It will, because they're
// the same thing. Note you never set the i + 1st value so the loops
// above did nothing
if(birthdays[k] == birthdays[m])
++numMatches;
}
So what you've got here is something like:
Perform 48 iterations of the following (from your first loop which goes from 2 to 50: no idea where those values came from)
For each of those 48 iterations, perform 10k iterations of:
assign a bunch of random stuff to an array overwriting stuff
Ignore the values you wrote in the array, do a comparison that's always true and increment numMatches by 1
Consider what's going on here:
for(int j = 1; j <= trials; j++) {
for(k = 1; k <= i; k++)
birthdays[k] = (rand() % 365) + 1;
for(m = 1; m <= i; m++)
birthdays[m] = (rand() % 365) + 1;
if(birthdays[k] == birthdays[m])
++numMatches;
}
You go through i birthdays and assign a random number, then you go through the same i birthdays and assign them a new random number. Then you try to find a match for just one value of k and m (which both happen to equal i+1, which isn't one of the values set!).
My suggestion is to break the problem down into smaller units that will make it easier to figure out how to code - here are the functions I would try to write.
/* randomizeBirthdays()
* Put n random birthdays into the pre-allocated array birthdays.
* birthdays must of course be of length <= n.
*/
void randomizeBirthdays(int * birthdays, int n);
/* hasMatchingBirthdays()
* Check if birthdays array has two people with the same birthday
* in the first n entries.
* Return value is boolean.
*/
bool hasMatchingBirthdays(int * const birthdays, int n);
/* probabilityOfMatch()
* Calculate the probability that at least 2 out of n people will
* have the same birthday, using nTrials number of trials.
* Return value is double.
*/
double probabilityOfMatch(int n, int nTrials);
If you break it down like this it becomes easier to write and easier to troubleshoot.
As I said in comments already:
I think your aim is to test if 2 people in room of 2-50 people share
birthday, not if 2-50 people share birthday as you say in output. And
that's 2 people out of 23 have 50.7%, not 24.
I completely reworked your code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
#define DAYS_IN_YEAR 365
#define TRIALS 10000
void clearArray (bool * array)
{
for (int i = 0; i < DAYS_IN_YEAR; i++)
array[i] = false;
}
int main()
{
srand(time(NULL));
bool birthdays[DAYS_IN_YEAR]; //we are trying to hit same day in year twice
int r, numMatches;
for(int i = 2; i < 50; i++)
{
numMatches = 0;
for(int j = 0; j < TRIALS; j++)
{
clearArray(birthdays);
for(int k = 0; k < i; k++)
{
r = rand() % DAYS_IN_YEAR; // == 0-364
if (birthdays[r])
{
numMatches++;
break; // 2 people already have same birthdays here
}
birthdays[r] = true;
}
}
cout << "Probability of 2 people having same birthday in room of " << i << " people is "
<< (float)numMatches / TRIALS << endl;
}
}
Output:
Probability of 2 people having same birthday in room of 23 people is 0.516
I think the code must be something like this.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int birthdays[10000][50];
int numMatches;
int trials=10000,check;
for(int n=0;n<trials;n++)
{
for(int j=0;j<50;j++)
{
birthdays[n][j]=rand()%365+1;
}
}
for(int i=2;i<=50;i++)
{
numMatches=0;
for(int n=0;n<trials;n++)
{
check=1;
for(int j=0;j<i;j++)
{
for(int k=j+1;k<=i;k++)
{
if(birthdays[n][j]==birthdays[n][k]&&check)
{
numMatches++;
check=0;
}
}
}
}
cout << "Probability of " << i << " people in a room sharing a birthday is \t" <<
(static_cast<float>(numMatches) / (trials)) << endl;
}
}

Bubble sort issue

Currently studying software engineering at college (first year) and made a program where the user enters how many entries there will be and then they input the times for each entry and it is sorted in descending order.
The problem I am having is when I enter a large number for the first input it doesn't sort correctly but the rest do. It would be great if someone could help me out with this and sorry for the noob question:P
The entire code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int TotalSize = 0;
void getSpeed(int *CalculationTime, int NoOfCalculations)
{
for (int i = 0; i < NoOfCalculations; i++)
{
cout << "Please enter the speed of calculation " << i + 1 << "(Ms): "; cin >> CalculationTime[i];
}
}
void sort_speeds(int *CalculationTime, int NoOfCalculations)
{
// Sorting speeds in decending order
bool swapped = true;
int i, j = 0;
int temp;
while (swapped)
{
swapped = false;
j++;
for (i = 1; i < NoOfCalculations - j; i++)
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}
// Output times decending order
for (int i = 0; i < NoOfCalculations; i++)
{
cout << CalculationTime[i] << "\n";
}
}
int main()
{
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
getSpeed(CalculationTime, NoOfCalculations);
// Sorting and displaying times
sort_speeds(CalculationTime, NoOfCalculations);
system("pause");
return 0;
}
You've never compare first element of your array with anything - for (i = 1; i < NoOfCalculations - j; i++) should be for (i = 0; i < NoOfCalculations - j; i++)
The issue is for (i = 1; i < NoOfCalculations - j; i++) You are starting at position 1, start at position 0 and it fixes the problem. for (i = 0; i < NoOfCalculations - j; i++)
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
Bzzzt. You allocate a zero-element array, and then don't reallocate it. I bet if you entered a large enough number for your number of calculations, your program would crash.
Really, you want to be using std::vector, an extremely useful datastructure, the use of which is a bit outside of the scope of this answer. Basically, you can do stuff like this:
std::vector<int> getSpeeds(int NoOfCalculations)
{
std::vector<int> speeds;
for (int i = 0; i < NoOfCalculations; i++)
{
int speed;
std::cout << "Please enter the speed of calculation " << i + 1 << "(Ms): ";
std::cin >> speed;
speeds.push_back(speed);
}
return speeds;
}
You can use the returned vector almost exactly as if it were an array:
std::vector<int> speeds = getSpeeds(10);;
if (CalculationTime[3] > CalculationTime[4])
// do something
Often, in a C++ application, the explicit use of pointers is a sign that you're not using the standard library, and as a result making life much, much harder for yourself.
Oh, and also:
for (i = 1; i < NoOfCalculations - j; i++)
You never look at NoOfCalculations[0] or NoOfCalculations[i - 1], so you never touch the first element.
while (swapped)
{
swapped = false;
j++;
for (i = 0; i < NoOfCalculations - j; i++) //try and start i from 0. I think you are missing the first element to check
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}

not declared in scope c++ [duplicate]

This question already has answers here:
'foo' was not declared in this scope c++
(3 answers)
Closed 6 years ago.
I am getting an error that breed is not declared in scope even though it is right below the fucntion. What is wrong?
The exact error is: prog.cpp: In function ‘void best(std::string*)’:
prog.cpp:131:15: error: ‘breed’ was not declared in this scope
breed(bestRats)
#include <iostream>
#include <sstream>
#include <vector>
#include <math.h>
#include <map>
#include <string.h>
#include <queue>
#include <regex>
#include <bitset>
#include <stdlib.h>
#include <climits>
// #include "dungeonrats.cpp"
using namespace std;
/*
Finds the maximum integer in an array of integers.
Size is the size of the given array.
*/
int getMax(int* numbers, int size) {
int maximum = INT_MIN;
for (int i = 0; i < size; i++) {
if (numbers[i] > maximum) maximum = numbers[i];
}
return maximum;
}
int getMaxi(int* numbers, int size) {
int maximum = INT_MIN;
int maxi;
for (int i = 0; i < size; i++) {
if (numbers[i] > maximum) {
maximum = numbers[i];
maxi = i;
}
}
return maxi;
}
/*
"randomly" generates a new maze (but is it REALLY random?)
aim is 65% empty tiles
10% food tiles
10% obstacles
15% pits
*/
string getNewMaze(string mapseed) {
string maze = mapseed.substr(6); // get everything except the 25:25:
for (int i = 0; i < 626; i++) {
int percentile = rand() % 100; // from 0 to 99
if (percentile < 65) {
maze[i] = '.';
}
else if (percentile >= 65 && percentile < 75) {
maze[i] = '$';
}
else if (percentile >= 75 && percentile < 85) {
maze[i] = '*';
}
else maze[i] = 'X';
}
return maze;
}
/*
A function used to print how many of each kind of tile
exist in the maze.
*/
void testFrequency(string mapseed) {
int numEmpty = 0;
int numFood = 0;
int numObs = 0;
int numPit = 0;
for (int i = 0; i < 626; i++) {
if (mapseed[i] == '.') {
numEmpty++;
}
if (mapseed[i] == '$') {
numFood++;
}
if (mapseed[i] == '*') {
numObs++;
}
if (mapseed[i] == 'X') {
numPit++;
}
}
cout << "Number of empty tiles is " << numEmpty << endl;
cout << "Number of food tiles is " << numFood << endl;
cout << "Number of obstacles is " << numObs << endl;
cout << "Number of pits is " << numPit << endl;
}
/*
Returns an array of size 2 containing the best two rats.
*/
void best(string r[]) {
// r is the array of five rat genomes
//int moves = simulator(mapseed, genome, start_row, start_col);
int* ratMoves = new int[5]; // array that stores how long each rat lasted
int maxIndex = 0;
int max = INT_MIN;
string originalMapseed = "25:25:..$.$.X.............X....$X.X*..X$..X...*X$..$...X$.$......X.$.X...XX.$.X*.*.*..X..X.**.......X..$$$...........XX.....................$...X...*.$..X..$X..........$.*..X.....$.X..$*.$X......$...X.*X$......$.**.X.X..XX$X..*....*..X.X....$...X...X........$.X....$...*...X$*........X..$*$$......$$...$*..X.$.$......$.$.$...$..X.*.....X..$......$.XX*..X.$.X......X$*.**.....X*...$..XX..X.....$....X....X...X....X.$X$..X..........$...*.X$..X...$*...........*....XXX$$.$.$..*$XX..XX..*.....$......X.XX$..$$..X$.XX.$$..X.*..*......X......$..$.$$..*...X.........$X....$X.$$.*.$.$.$..**.....X.$.$X.*.$.........$**..X.X.X$X.$.*X.X*..$*.";
for (int i = 0; i < 5; i++) {
string mapseed = getNewMaze(originalMapseed);
int sumTurns = 0;
for (int k = 0; k < 10; k++) {
string mapseed = getNewMaze(originalMapseed);
// sumTurns += simulator(mapseed,r[i],12,12); // uncomment this line once in correct file
}
ratMoves[i] = sumTurns / 10; // average of rat's performance
// over 10 random maps
if (ratMoves[i] > max) { // find the best
max = ratMoves[i];
maxIndex = i;
}
}
string bestRats[2];
bestRats[0] = r[maxIndex]; // store the best
ratMoves[maxIndex] = INT_MIN; // remove the best from array of rat moves
bestRats[1] = r[getMaxi(ratMoves, 5)]; // get the second best & store it
breed(bestRats);
}
void breed(string r[]) {
int cap = 10;
string c[5];
for (int j = 0; j<5; j++)
for (int i = 0; i<190; i++) {
int check = rand() % cap + 1;
if (check % 2 == 0) {
if (check == 0)
c[j] += rand() % 81 + 42;
else
c[j] += r[1][i];
}
else
c[j] += r[0][i];
}
best(c);
}
int main() {
string c[5];
for (int j = 0; j<5; j++)
for (int i = 0; i<190; i++)
c[j] += rand() % 81 + 42;
best(c);
}
Declare
void breed(string r[]);
on the top of file before first usage or include appropriate header file containing this declaration.
c++ checks for function names at the moment it reads them in the code (symbolically). if it hasn't read it yet, it doesn't know it exists. that's why you at least need to declare a function's prototype before using it in your code.
ergo, here you need to at least put
void breed(string r[]);
before using the function.
When the compiler processes your code, it starts at the top and goes to the end. At any given point in this process, it only "knows" about things it's already seen. So when you try to call the breed function from the best function, it doesn't know what you're talking about because it hasn't seen anything called breed yet.
To fix this, you need to let the compiler know what the breed function is before you attempt to use it. There are a few ways to do this. The easiest would be to move the entire breed function above the best function in your source file. An alternate would be to declare the breed function higher up in the file before defining it later. To declare it, simply include the line void breed (string r[]); somewhere (don't forget the ; at the end). This way the compiler knows that "breed" refers to a function that takes an array of strings and returns nothing, which is enough for it to compile calls to the function.

Duplicate numbers in an array [duplicate]

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