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.
Related
I can't figure it out. What is wrong with my code? I am new to programming.
Program required output: Write a C++ program to find the maximum-occurring character in an array, using a loop.
My code:
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
index = Word[i];
}
}
cout << index << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,100);
FindMaxChar(Word);
}
My Output:
Enter the Word = caaar
r is repeating 11 times.
You never reset count each loop. So you continue incrementing it but never clear it.
Add count = 0 to the beginning of the outer for loop:
for (int i = 0; i < length; i++)
{
count = 0; // Reset counter
You're also trying to use index for two different purposes. You're both using it to store the current character you're looking at (not an index, kind of confusing that you named it like that), AND the character you've seen the most (still not an index, also confusing).
Instead, you need another variable here.
Also note that if you declare Word as char Word[100], it can only hold a c-string of length 99 (to leave room for the null character). So your cin should actually be:
cin.get(Word, 99);
Thanks to the great people of this community.
I am able to find my error and corrected it.
Correct Code :
#include <iostream>
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
char final = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
count = 0;
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
final = index;
}
}
cout << final << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,99);
FindMaxChar(Word);
}
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 have a vector full of monster objects which are initialized onto a 10X10 map which works. I am now playing with some code to prevent monsters being spawned on the same map co-ordinate. when i run the code it cuts and brings up "vector subscript out of range" and i have no idea why. Any help would be great.
main function
#include "stdafx.h"
#include "character.h"
#include "monster.h"
#include "player.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
vector<monster*> monVec;
vector<int> monx;
vector<int> mony;
player player1;
bool collision();
void initialise();
int main(){
initialise();
player1.moveChar(3, 6);
bool temp;
temp = collision();
system("pause");
return 0;
}
initialize function
void initialize()
{
srand(time(NULL));
for (int n = 0; n < 10; n++)
{
int inx = rand() % 9;
int iny = rand() % 9;
if (n == 0){
monx.push_back(inx);
mony.push_back(iny);
}
for (int i = 0; i < n; i++)
{
-------->if (inx != monx[i] && iny != mony[i]){
monx.push_back(inx);
mony.push_back(iny);
}
else n--;
}
monVec.push_back(new monster());
monVec[n]->moveChar(inx, iny);
cout << endl << inx << ", " << iny << endl;
}
}
cout is just to check if its working once it runs and arrow indicates problem line.
thanks
In your initialize
you do the following
<for 10 times>
<when first time, add one item to the x,y vectors>
<access the up to 10nth element of the x,y vectors> //But vectors are only guaranteed to have at least one element each
<maybe add one item to the x,y vectors>
Problem is already that there is a path where there are not enough elements in your vectors. Plus the mistake about assignment and comparison in your if like #Michael Waltz already mentioned.
void initialize()
{
srand(time(NULL));
for (int n = 0; n < 10; n++)
{
int inx = rand() % 9;
int iny = rand() % 9;
if (n = 0){ //<<--------------------------- replace (n = 0) by (n == 0)
monx.push_back(inx);
mony.push_back(iny);
}
for (int i = 0; i < 10; i++)
{
// <<<< here monx and mony may contain only
// one element so monx[1] and mony[1] are invalid
if (inx != monx[i] && iny != mony[i]){
monx.push_back(inx);
mony.push_back(iny);
}
else n--;
}
monVec.push_back(new monster());
monVec[n]->moveChar(inx, iny);
cout << endl << inx << ", " << iny << 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;
}
}
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. :)