I've got this small piece of code
int row[7];
bool equals = false;
std::vector<int>range;
for(int i = 1; i <= 35; ++i)
{
range.push_back(i);
}
for(int i = 0; i < 7; i++){
int number = range[rand() % range.size() + 1];
std::vector<int>::iterator pos = find(range.begin(), range.end(), number);
row[i] = number;
range.erase(range.begin() + (*pos - 1));
std::cout << row[i] << endl;
}
return 0;
It takes away random elements from the vector, the problem I've got is that every time I remove a object from the vector the size updates but the positions doesn't seem to change on the individual numbers in the vector, making the program crash since I sometimes travel outside the bounds of the vector.
I've tried with vector::shrink_to_fit but it didn't seem to re-evaluate the vectors item positions.
What am I missing? It seems like such a simple thing to do but I just can't wrap my head around it.
P.S
I'm a c++ scrub so if you have any input on the code being bad/unsafe I'm open for suggestions/constructive criticism.
rand() % range.size() + 1
can go outside the bounds of the vector
use
rand() % range.size()
use this piece of code instead :
std::vector<int>range;
for(int i = 1; i <= 35; ++i)
{
range.push_back(i);
}
srand(time(0)) ;
for(int i = 0; i < 7; i++){
int index = rand() % range.size() ;
int number = range[index];
row[i] = number;
range.erase(range.begin() + index);
std::cout << row[i] << endl;
}
Related
Beginner here, and I'm stuck. The main program is provided to us, and we're supposed to write 3 functions. readBig(), addBig(), and printBig(). I'm stuck on the addBig() function. It's supposed to sum two arrays, and perform the carry operation. I cannot figure out where I'm going wrong. The carry operation is working out for me.
Any help/direction is appreciated.
#include <iostream>
using namespace std;
//This program will test three functions capable of reading, adding,
//and printing 100-digit numbers.
// Do not change these function prototypes:
void readBig(int[]);
void printBig(int[]);
void addBig(int[], int[], int[]);
// This constant should be 100 when the program is finished.
const int MAX_DIGITS = 100;
//There should be no changes made to the main program when you turn it
in.
int main(){
// Declare the three numbers, the first, second and the sum:
int num1[MAX_DIGITS], num2[MAX_DIGITS], sum[MAX_DIGITS];
bool done = false;
char response;
while (not done)
{
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(num1);
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(num2);
addBig(num1, num2, sum);
printBig(num1);
cout << "\n+\n";
printBig(num2);
cout << "\n=\n";
printBig(sum);
cout << "\n";
cout <<"test again?";
cin>>response;
cin.ignore(900,'\n');
done = toupper(response)!='Y';
}
return 0;
}
//ReadBig will read a number as a string,
//It then converts each element of the string to an integer and stores
it in an integer array.
//Finally, it reverses the elements of the array so that the ones digit
is in element zero,
//the tens digit is in element 1, the hundreds digit is in element 2,
etc.
void readBig(int num[])
{
for(int i = 0; i < MAX_DIGITS; i++){
num[i] = 0;
}
string numStr;
getline(cin,numStr);
string temp;
//store into array
for (int i = 0; i < numStr.length(); i++){
temp = numStr.at(i);
num[i] = stoi(temp);
}
int arrayLength = MAX_DIGITS;
int temp2;
for (int i = 0; i < (arrayLength/2); i++){
temp2 = num[i];
num[i] = num[(arrayLength - 1) - i];
num[(arrayLength - 1) - i] = temp2;
}
}
//AddBig adds the corresponding digits of the first two arrays and
stores the answer in the third.
//In a second loop, it performs the carry operation.
void addBig(int num1[], int num2[], int sum[])
{
for (int i = 0; i < MAX_DIGITS; i++){
sum[i] = num1[i] + num2[i];
if (sum[i] > 9){
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 10;
}
}
}
//PrintBig uses a while loop to skip leading zeros and then uses a for
loop to print the number.
void printBig(int array[])
{
int i = 0;
while (array[i] == 0){
i++;
}
for (int j = i; j < MAX_DIGITS;j++){
cout << array[j] << endl;
}
}
Looks like readBig function isn't correct, it stores least significiant digit into num[numStr.length()-1], after reversing it became num[MAX_DIGITS -1 - ( numStr.length()-1], but addNum assumes last digit is num[0].
Correct variant:
void readBig(int num[])
{
//clear num, read numStr...
//store into array
int count = 0;
for (int i = numStr.length()-1; i >= 0; --i){
temp = numStr.at(i);
num[count++] = stoi(temp);
}
|
So this
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 10;
should most likely be this
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 1;
Since its the next decimal place it shouldnt be incremented by 10
Also when you get to the last cell in your array
sum[i+1] = sum[i+1] + 1;
this will be out of bounds, so depending on the requirments you will want to change this
I am trying to create many arrays consisting of random numbers and of random size between the range of, say, 1 and 20 elements. My code works SOMETIMES.
I am using a random number between my desired range to determine the array size. If the first iteration produces an array size of value 10, say, then for some reason my code does not want to create any arrays of size larger than 10. Various arrays will be created (and the list of those arrays will be outputed) until a certain iteration produces a random number larger than 10. Then I get this error:
Array index out of range numbers->[11] valid upto numbers[9]
"numbers" is the name of the array. Here is the relevant portion of my code:
srand(time(0));
int j, flag = 0;
int temp;
int rand=1;
for(int t=0; t<50; t++)
{
int length = rand()% 20 + 1;
cout<<"length is " << length << endl;
int numbers[length];
for(int i = 0; i < length; i++)
{
numbers[i]=rand();
cout << numbers[i] << endl;
}
for(j=0; (j<=length); j++)
{
for (int i=0; i<(length-1); i++)
{
if(numbers[i+1]<numbers[i])
{
temp=numbers[i];
numbers[i]=numbers[i+1];
numbers[i+1]=temp;
flag++;
}
}
}
cout << "Number of Swaps : " << flag << endl;
}
As #Bob__ wrote, allocating variable length arrays is not C++ standard. It might work sometimes on specific compilers, but it may break on others.
But there are good alternatives. You can allocate dynamic memory with new. For instance:
int *array = new int[size];
array[0] = 3;
array[1] = 5;
cout << array[1];
delete [] array;
Don't forget to delete the memory with delete afterwards.
Or you could use vector<int>. It's a STL-container, that was made for exactly this purpose.
#include <vector>
using namespace std;
...
vector<int> vec(size);
vec[0] = 3;
vec[1] = 5;
cout << vec[1];
Variable Length Arrays are not in C++ standard, but only offered as extension by some compilers. I wouldn't trust them and you don't really need anything like that in your code.
You can declare your array outside the outer for loop as you know its max lenght:
#define MAXL 20
int numbers[MAXL];
for ...
int length = rand() % MAXL + 1;
...
Besides, if you are implementing a bubble sort I think that the condition of the inner i loop should be i < length - j
rand is used in two contexts. As a variable int rand and as a function std::rand(). I'd suggest to delete any using namespace std; but since the variable is not needed anyways you could as well delete int rand = 1;. Note that rand() is a C function. You may use it but IMHO std::rand() is more pure C++.
int numbers[length]; will not compile because length is a non-constant. Use std::vector<int> numbers(length); instead.
And that's about it.
#include <iostream>
#include <vector>
#include <time.h>
int main()
{
std::srand(time(0));
int j, flag = 0;
int temp;
for (int t = 0; t < 50; t++)
{
int length = std::rand() % 20 + 1;
std::cout << "length is " << length << std::endl;
std::vector<int> numbers(length);;
for (int i = 0; i < length; i++)
{
numbers[i] = std::rand();
std::cout << numbers[i] << std::endl;
}
for (j = 0; (j <= length); j++)
{
for (int i = 0; i < (length - 1); i++)
{
if (numbers[i + 1] < numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
flag++;
}
}
}
std::cout << "Number of Swaps : " << flag << std::endl;
}
}
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;
}
}
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;
}
}
}
I've written out this particular code in C++ to try and find out all the multiples of the integers 3 & 5 below 1000 by using a while loop and then storing it in integer arrays. I also want to print each of those multiples out. But every time I debug this program, it endlessly prints out '0'. I just don't understand. Can someone please explain how to correct this code and why that unusual output occurs?
#include <iostream>
using namespace std;
int main()
{
const int three_limit = 334;
const int five_limit = 200;
int threeArray[three_limit] = {0};
int fiveArray[five_limit] = {0};
int i = 1, j = 1;
while (i < three_limit)
{
int multiples = 3*i;
multiples = threeArray[i - 1];
cout << threeArray[i - 1] << endl;
i++;
}
while (j < five_limit)
{
int multiples = 5*i;
multiples = fiveArray[j - 1];
cout << fiveArray[j - 1] << endl;
j++;
}
char response;
cin >> response;
return 0;
}
Your output will have duplicates when the number contains multiples of 3 and 5, e.g. 15, 30.
Some of the suggestions use multiplication or mod (%) which are quite slow, but there's a much faster solution using a binary array that will also help you avoid the duplication problem. Something like:
int main() {
bool nums[1001];
for(int i = 1; i < 1001; ++i)
nums[i] = 0;
for(int i = 3; i < 1001; i += 3)
nums[i] = 1;
for(int i = 5; i < 1001; i += 5)
nums[i] = 1;
for(int i = 1; i < 1001; ++i)
if(nums[i])
cout << i << endl;
}
It should be
threeArray[i - 1] = multiples;
instead of
multiples = threeArray[i - 1];
See the following code, to generate multiples of 5
#include<stdio.h>
int main(){
int max=1000;
int i=1,result=0;
while(result!=max && i!=200)
{
result=5*i; // change the 5 by 3 for multiples of 3
printf("\n %d",result);
i++;
}
}
I guess this
multiples = threeArray[i - 1];
should really be
threeArray[i - 1] = multiples;
Try debugging it again and watch multiples while executing this line.
multiples = threeArray[i - 1];
You're overwriting the local int with the (empty) contents of the array - you have your assignment the wrong way around.
You never modify the values in your array. It should be something like this:
while (i < three_limit)
{
int multiples = 3*i;
threeArray[i-1] = multiples;
cout << threeArray[i - 1] << endl;
i++;
}