Bulls & Cows project: cow checking - c++

I'm almost done with my Bulls and Cows project however if I enter a word or a sequence of numbers with an alphabet or number repeating, the 'cow' portion of the code messes up. As an example: consider the following
Enter something that you want someone to guess: cool
Time to guess! The code is of size 4. book
COWS: 0 BULLS: 2
ozzo
COWS: 4 BULLS: 0
As you can see, after entering "ozzo", the cow value should be 2, not 4.
How can I fix this without having to change the entire code?
for (size_t i = 0; i != startg.getSize(); ++i){
if (guess[i] == origWord[i]){
bullCtr++;
} else {
for (size_t j = 0; j != startg.getSize(); ++j){
if (origWord[i] == guess[j]){
cowCtr++;
}
}
}
}
Code after applying fix:
for (size_t i = 0; i != startg.getSize(); ++i){
if (guess[i] == origWord[i]){
bullCtr++;
} else {
for (size_t j = 0; j != startg.getSize(); ++j){
if (origWord[i] == guess[j]){
origWord[i] = 'X';
cowCtr++;
}
}
}
origWord = origWordcpy;
}

Your cow checking is problematic.
What I would do for the sake of ease (not exactly) is this (I'm talking about the else statement only):
for(unsigned int j = 0 ; j != startg.getSize() ; j++)
{
if(origWord[i] == guess[j])
{
origWord[i] = 1; //Just assigning a certain value there to mark that we've already did something with it
cowCtr++;
}
}
And that should do the work.
EDIT:
You should obviously have a temporary string instead of origWord because changing it would affect the next iteration of the outer loop (getting the guess and comparing again) - I only showed you the way.

Here is one possible implementation of the Bulls & Cows game:
// used constants; numbers to be guessed
const int first_num = 2;
const int second_num = 4;
const int third_num = 1;
const int forth_num = 5;
int main(){
// vector holding the values to be guessed
vector<int>gamenum(4);
gamenum[0] = first_num;
gamenum[1] = second_num;
gamenum[2] = third_num;
gamenum[3] = forth_num;
// prompt message; input cycle till perfect guess (4 bulls)
int bulls = 0;
while (!(bulls == 4)){
// vector holding the guesses
vector<int>guesses;
// vector input values
int guess1(0), guess2(0), guess3(0), guess4(0);
cout << "\t\tPlay the game ""Bulls and Cows\n""" << endl;
cout << "Enter a set of four numbers, separated by whitespace space: ";
cin >> guess1 >> guess2 >> guess3 >> guess4;
guesses.push_back(guess1);
guesses.push_back(guess2);
guesses.push_back(guess3);
guesses.push_back(guess4);
// input confirmation; show your guess
cout << "\nYour guess is: ";
for (int i = 0; i < guesses.size(); ++i){
cout << guesses[i];
}
// bulls criterion
for (int j = 0; j < guesses.size(); ++j){
if (guesses[j] == gamenum[j]) ++bulls;
}
// cows criterion
int cows = 0;
for (int gue = 0; gue < guesses.size(); ++gue){
for (int gam = 0; gam < gamenum.size(); ++gam){
if (guesses[gue] == gamenum[gam] && gue != gam) ++cows;
}
}
// print result
if (bulls < 4){
cout << "\nBulls: " << bulls << " and Cows: " << cows <<endl;
cout << "\n\n\n" << endl;
// reset bulls
bulls = 0;
}
// empty guesses vector
guesses.clear();
// reset cows
cows = 0;
}
// print success
cout << "\nPerfect Guess!" << endl;
cout << "Bulls: " << bulls << endl;
cout << "\n\n\n" << endl;
keep_window_open();
return 0;
}
Not optimal by any means, rudimentary, but working. You can use it as benchmark.

Related

Difference of 2 sets retained in arrays - C++

Consider two sets retained in two arrays. Find the union, intersection and difference (relative complement) of the two sets.
I managed to solve the union and the intersection, but the difference is giving me a hard time. Any hints? And if possible, keep it as simple as possible, without functions or more complex aspects, because I'm a beginner and I still have a lot to learn.
Thank you in advance!
#include <iostream>
using namespace std;
int main()
{
int v1[100], v2[100], u[200], intersection[100], d[100];
unsigned int v1_length, v2_length, i, j, OK = 0, union_length;
cout << "Enter the number of elements of the first array:" << " ";
cin >> v1_length;
cout << "Enter the elements of the first array:" << '\n';
for (i = 0; i < v1_length; i++)
cin >> v1[i];
cout << "Enter the number of elements of the second array:" << " ";
cin >> v2_length;
cout << "Enter the elements of the second array:" << '\n';
for (i = 0; i < v2_length; i++)
cin >> v2[i];
//Union
union_length = v1_length;
for (i = 0; i < v1_length; i++)
u[i] = v1[i];
for (i = 0; i < v2_length; i++)
{
int ok = 0;
for (j = 0; !ok && j < v1_length; j++)
if (v1[j] == v2[i])
ok = 1;
if (!ok)
{
u[union_length] = v2[i];
union_length++;
}
}
cout << "The union of the two sets contained in the arrays is: ";
for (i = 0; i < union_length; i++)
cout << u[i] << " ";
cout << '\n';
//Intersection
unsigned int k = 0;
cout << "The intersection of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++)
if (v1[i] == v2[j])
{
intersection[k] = v1[i];
k++;
}
for (i = 0; i < k; i++)
cout << intersection[i] << " ";
cout << '\n';
//Difference
unsigned int l = 0, OK2 = 0;
cout << "The difference of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
{
for (j = 0; j < v2_length; j++)
{
if (v1[i] == v2[j])
OK2 = 1;
if (!OK2)
{
d[l] = v1[i];
l++;
}
}
}
for (i = 0; i < l; i++)
cout << d[i] << " ";
cout << '\n';
return 0;
}
It seems that the intersection is the best place to start. You want the items that only in appear in one of the two arrays, right?
So, for the inner loop, you need to compare all the elements. Then, if no match was found, you have the a unique element.
You need to add the curly braces {} to the for loop. I know that curly braces are distracting at times, but over time, you will probably find it safer to almost always include them to avoid confusion.
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++) {
if (v1[i] == v2[j]){
break; // this item is not unique
} else if(j == v2_length - 1){
d[l] = v1[i]; // This is the unique one, add it to the answer array
l++;
}
}
for (i = 0; i < l; i++)
cout << intersection[l] << " ";
cout << '\n';
You're on the right track!
You're doing a few things wrong. Here are some fixes you can try:
Only set OK2 to 0 once per inner-loop
Reset OK2 to 0 at the end of the inner-loop
Only do the insertion into d after the inner-loop has completed
As an optimization, consider breaking after you set OK2 to 1, as you know at that point it can never be set to 0 for the current value pointed to by the outer-loop.

Maximum number of vowels in a word in string array

I have written a program to input 2 strings in a string array.
And then print the maximum vowels stored in the list.
Where am i going wrong here,and is there a more elegant method to this.
#include<iostream.h>
#include<string.h>
int main()
int i,j,c=0,k=0,maxo=0,len1,maxo1=0,len3;
char vow[] = "AEIOUaeiou";
char list[100][100],vow[]={"AEIOUaeiou"};
for(i=0;i<2;i++) {
cout<<"Enter word: ";
gets(list[i]);
for(i=0;i<2;i++) {
len1=strlen(list[i]);
for(k=0;k<len1;k++) {
for(j=0;list[j][k]!='\0';j++)
if(list[j][k]==vow[j])
c++;
}
if(c>maxo)
maxo=c;
c=0;
}
cout<<"Maximum Vowel count:"<<maxo<<endl;
}
fflush(stdin);
getchar();
return 0;
}
The bigger programme where i am trying to incorporate this code.The necessary comments are in the code.I really cannot undertand where i am going wrong in the last part.
Should i include the last bit of code at first so that the program works?
#include<iostream.h>
#include<string.h>
int main()
{
int i,n,len=0,sum=0,j,max,min,c=0,c2=0,k=0,maxo=0,len1,maxi=0,c1=0,len2;
float avg;
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
for(i=0;i<2;i++)
{
cout<<"Enter word: ";
gets(list[i]);
len=strlen(list[i]);
sum=sum+len;
cout<<"Length of word: "<<len<<endl;
if(list[i][len-1]=='s')
{cout<<"The Word "<<list[i]<<" ends with s"<<endl;
c2++;
}
}
//Word input by user.Prints word along with length.
min=strlen(list[0]);
max=strlen(list[0]);
//Initialising max and min.
for(i=0;i<2;i++)
{
if(strlen(list[i])<min)
{min=strlen(list[i]);}
if(strlen(list[i])>max)
{max=strlen(list[i]);}
}
for(i=0;i<2;i++)
{
if(max==strlen(list[i]))
cout<<"The max value of the lengths stored:"<<list[i]<<endl<<"Word count:"<<max<<endl;
if(min==strlen(list[i]))
cout<<"The min value of the lengths stored:"<<list[i]<<endl<<"Word count:"<<min<<endl;
}
//Max and Min value of string lengths are printed.
avg=sum/2;
cout<<"Avg length:"<<avg<<endl;
//Average value printed.
cout<<"The number of words with s:"<<c2<<endl;
//Word ending with s.
{for (i = 0; i <2; i++)
len1 = strlen(list[i]);
for (k = 0; k < len1; k++)
{
for (j = 0; j < strlen(vow); j++)
//if (list[j][k] == vow[j])
if (list[i][k] == vow[j])
c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";
cout << "Maximum Vowel count:" << maxo << endl;
}
for(i = 0 ;i < 2 ;i++)
{ len3 = strlen(list[i]);
letter = list[i][0];
{for(j=0;j<len3;j++)
if(list[i][j]==letter)
counter++;
}
cout << "Number of identical letters as first letter in line " << i << ":
" << counter << '\n';
if (c>maxo1) maxo1 = counter;
counter = 0;
cout << "Maximum letter count so far:" << maxo1 << "\n\n";
cout << "Maximum letter count:" << maxo1 << endl;
}
PS:
I have edited my code one more time to display the alphabet which has occurred the maximum number of times as starting letter of a word in the list,and the number of times it has occurred.
This won't compile for me for two reasons:
1) gets()
The most recent revision of the C standard (2011) has definitively
removed this function from its specification. The function is
deprecated in C++ (as of 2011 standard, which follows C99+TC3).
And so I can't use the gets() function.
2) You can't declare
char list[100][100], char vow[] = {"AEIOUaeiou"};
both with a comma separator.
You read the input for the first line string into the first row of the array i = 0; then you instantly loop through i, which doesn't make sense. The following is not a good solution as in C++ you should be using std::vectors and std::string, and not generally mixing C and C++ but I've tried to keep it as close to your version, using my telepathic powers to read your mind about what you're trying to do.
#include <iostream>
#include <cstring>
using namespace std;
const int numLinesToGet = 10;
const int maxCharsPerLine = 100;
int main()
{
int i, j, c = 0, k = 0, maxo = 0, len1;
//char list[100][100], char vow[] = {"AEIOUaeiou"};
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
//for (i = 0; i < 2; i++)
for (i = 0; i < numLinesToGet; i++)
{
cout << "Enter word: ";
std::cin.getline(list[i], maxCharsPerLine);
//gets(list[i]);
//for (i = 0; i < 2; i++) Get rid of this second loop entirely
len1 = strlen(list[i]);
for (k = 0; k < len1; k++)
{
//for (j = 0; list[j][k] != '\0'; j++)
for (j = 0; j < sizeof(vow); j++)
//if (list[j][k] == vow[j])
if (list[i][k] == vow[j])
c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";
}
cout << "Maximum Vowel count:" << maxo << endl;
fflush(stdin);
getchar();
return 0;
}
Online example here
#include<stdio.h>
int main ()
{
char a[] = "i love to code in education";
int i, count = 0, vow = 0, mvow = 0;
for (i = 0; a[i] != '\0'; i++)
{
if (a[i] == 'a' || a[i] == 'e' || a[i] == 'i' || a[i] == 'o'
|| a[i] == 'u')
{
vow++;
}
if (a[i]==' ')
{
count++;
mvow = vow;
vow = 0;
}
}
printf ("Total words: %d\n", count+1);
if(vow>mvow) printf ("Max Vowels in a word: %d", vow);
else printf("Max Vowels in a word: %d", mvow);
return 0;
}

Replace characters in old array

I'm solving a problem and stuck on last part now what i am doing. Taking 5 characters from user and save it on character array and than saying enter 3 characters to check does array has your enter characters in it.
For example: User enter 5 characters dagpl.Than second array subArray which search characters from main array now user enter 3 charactersdgl.Result saying 3 characters found. Are you want to replace these 3 characters with new characters? So enter 3 new replace characters now user enter xyz.
Final array would be replace like this xaypz.
My Code doesn't working fine for replacing characters i don't know what i'm doing wrong.
#include<iostream>
#include<cstdlib>
using namespace std;
int main(int argc, char**argv) {
bool check = false;
char arr[6] = { '\0' };
char subarr[4] = { '\0' };
int count = 0;
cout << "Enter Characters : ";
for (int i = 0; i < 5; i++) {
cin >> arr[i];
}
cout << "Enter 3 Characters and see how many times does array has your Search Characters : ";
for (int i = 0; i < 3; i++) {
cin >> subarr[i];
}
//Sub Array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
if (subarr[i] == arr[j]) {
if (!check) {
cout << "Found characters are: ";
}
count++;
cout << subarr[i] << ",";
check = true;
}
}
}
if (check) {
cout << '\b';
cout << " ";
cout << endl;
}
if (!check) {
cout << "Sorry Nothing Found" << endl;
}
cout << "total Found : " << count << endl;
//SECTION 3
if (check) {
int n = count + 1;
char* replace = new char[n]();
cout << "You can only replace " << count << " new characters because of find operation! so enter it will be replace old array with it: ";
for (int i = 0; i < n - 1; i++) {
cin >> replace[i];
}
//Replace characters
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < 5; j++) {
if (subarr[i] == arr[j]) {
arr[j] = replace[j];
}
}
}
delete[]replace;
replace = NULL;
cout << "New Array would be: ";
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
cout << endl;
}
system("pause");
return EXIT_SUCCESS;
}
You're not marking the matched characters from arr
Replace the matched characters from arr[j] with a distinct character so that you can determine where to replace later. you can use null terminator
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
if (subarr[i] == arr[j]) {
if (!check) {
cout << "Found characters are: ";
}
count++;
cout << subarr[i] << ",";
check = true;
arr[j]='\0'; //replacing the matched character with null terminator
}
}
}
Now traverse through your arr and replace null terminators with characters from replace array
int i=0;
for (int j = 0; j < 5; j++) {
if (arr[j]=='\0') { //replace when it equals to null terminator
arr[j] = replace[i++];
}
}
You want to ask the user to replace a specific number of chars, counting how many chars appear in subarr.
arr is input, subarr is from:
int replacecount[3] = { 0 };
for (int x=0; x<6; x++)
for (int i=0; i<3; i++)
if (input[x] == from[i]) {
++replacecount[i];
break;
}
int count = 0;
for (int i=0; i<3; i++)
if (replacecount[i] > 0)
++count;
std::cout << " you can replace " << count << " characters..." << std::endl;
char to[3];
for (int i=0; i<3; i++)
if (replacecount[i] > 0) {
std::cout << "enter replace character for '" << from[i] << "'" << std::endl;
std::cin >> to[i];
}
for (int x=0; x<6; x++)
for (int i=0; i<3; i++)
if (input[x] == from[i]) {
input[x] = to[i];
break;
}
std::cout << "replaced string is: " << input << std::endl;

Not all code executes, but program exits properly

This is a program which is supposed to find circular primes below certain max value. It works for max<=1000, but if max=10000 , the program ends without errors, but does not print the last two lines to console, even though it always should. It also doesn't print any more circular primes out, but that might be my algorithm problem, and I will worry about it later.
Note: I'm using MVS 2010, and there are unnecessary std:: before cout, because it sometimes says that cout is ambigous.
using namespace std;
int main(){
const int max = 10000;
int nrOfPrimes = 0;
int* primes = findIfPrimes(max);
for(int i = 2; i < max; i++){
//check if number is prime
if(primes[i] == 0){
nrOfPrimes++;
int l = 0;
int* permutations = findPermutations(i, l);
//variable saying lf all permutations are prime
bool allPrime = true;
//check all permutations, if they are not prime change allPrime
for(int j = 0; j < l; j++){
if(primes[permutations[j]] != 0){
allPrime = false;
break;
}
}
//if it wasnt circular prime- continue
if(allPrime == false)
continue;
//if it was circular prime, change all permutations to "circular prime"
std::cout << "Circular primes: ";
for(int j = 0; j < l; j++){
primes[permutations[j]] = 2;
std::cout << permutations[j] << " " << endl;
}
std::cout << endl;
}
}
//find total count
int result = 0;
for(int i = 2; i < max; i++)
if(primes[i] == 2)
result++;
std::cout << "total number of primes " << nrOfPrimes << endl;
std::cout << "total number of circular primes " << result << endl;
return 0;
}
Put just before return 0 in main():
bool fail = cout.fail();
cout.clear();
cout << fail << endl;
cin.ignore(cin.rdbuf()->in_avail()); // clears all remaining input
cin.get(); // waits for ENTER
What tells it for fail?
Do the same with fail = cout.good();. What tells it then?

how to process an array of even numbers from a users input and display them with spaces in C++

I need help with getting this users input of an integer and retrieving the even numbers and displaying them with spaces.I already have the input processed into an array and have it reversed (thanks to stackoverflow) now need to extract the even numbers from the array and display them.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int evenNumbers(char even[], int num[], int indexing[]);
int main()
{
char integers[5];
int numbers[5];
int even[5] = {0,2,4,6,8};
int evens;
cout << "Please enter an integer and press <ENTER>: " << endl;
for (int j = 0; j < 5; j++)
cin >> integers[j];
for (int j = 0; j < 5; j++)
{
numbers[j]= integers[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << integers[j - 1] << " ";
}
cout << endl;
//having problems finding the even numbers and displaying the even numbers
//from the users input of integers, i have only learned how to display the
//subscript by a linear search
evens = evenNumbers(integers, numbers, even);
if (evens == -1)
cout << "There are no even numbers" << endl;
else
{
cout << "The even numbers are: " << (evens + 1) << endl;
}
system("pause");
return 0;
}
int evenNumbers(char even[], int num[], int indexing[])
{
int index = 0;
int position = -1;
bool found = false;
for (int j = 0; j < 5; j++)
{
num[j]= even[j] - '0';
}
while (index < 5)
{
if (num[index] == indexing[index])
{
found = true;
position = index;
}
index++;
}
return position;
}
If you want to display the even numbers from the array integers you can use a simple for loop and if statement:
for(int i = 4; i >= 0; i--)
{
if(integers[i] % 2 == 0)
cout << integers[i] << " ";
}
Your approach is all wrong, you can't detect even numbers by searching a list, you need a mathematical test for evenness. Write a function called is_even which tests one number and returns true if it is even and false if it is not. Then you can use that function, very simply, like this
for (int j = 0; j < 5; j++)
{
if (is_even(integers[j]))
cout << integers[j] << " ";
}
cout << endl;
Now you just need to write the is_even function.
void evennumbers(int num[])
{
for(int i=0;i<5;i++)
{
if(num[i]%2==0)
cout<<num[i]<<" ";
}
}
And avoid taking input to char what if user enters a number with more than one digit
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void validNum(char valid[]);
void reverseNum(char rev[], int num2[]);
void evenNumbers(char even[], int num3[]);
void oddNumbers(char odd[], int num4[]);
int main()
{
char integer[5];
int number[5];
cout << "Your number is: ";
validNum(integer);
cout << "Your number in reverse is: ";
reverseNum(integer, number);
cout << "Even numbers: ";
evenNumbers(integer, number);
cout << endl;
cout << "Odd numbers: ";
oddNumbers(integer, number);
cout << endl;
system("pause");
return 0;
}
void validNum(char valid[])
{
char ch;
cout << "Please enter an integer and press <ENTER>: " << endl;
ch = cin.get;
while (ch < 0 || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
cout << "ERROR: Please enter a positive integer and press <ENTER>: ";
for (int i = 0; i < 5; i++)
cin >> valid[i];
}
for (int j = 0; j < 5; j++)
{
cout << valid[j] - '0';
}
}
void reverseNum(char rev[], int num2[])
{
for (int j = 0; j < 5; j++)
{
num2[j]= rev[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << rev[j - 1]<< " ";
}
cout << endl;
}
void evenNumbers(char even[], int num3[])
{
for (int i = 0; i < 5; i++)
{
if (even[i] % 2 == 0)
{
cout << num3[i] << " ";
}
}
}
void oddNumbers(char odd[], int num4[])
{
for (int i = 0; i < 5; i++)
{
if (odd[i] % 2 == 1)
{
cout << num4[i] << " ";
}
}
}