C++ Erasing Vector element - c++

vector<char>teikums(count);
Having problems when trying to erase a element from vector.
For Example i input:
a b c d e f
and when trying to erase a element
teikums.erase(teikums.begin() + 3);
it will output
a b d e e f
Been trying to figure out why it doesn't output
a b c d f
Code:
int main() {
system("cls"); // Notira Ekranu
patsk = 0; // Pieskir vertibu
cout << "Ievadi Massiva lielumu: ";
cin >> count;
vector<char>teikums(count);
cout << "Vai aizpildit burtus automatiski (Y/Cits): ";
cin >> aizp;
srand(time(NULL));
cout << "\n";
if (aizp == 'y' || aizp == 'Y') {
for (int i = 1; i <= count; i++) {
teikums[i] = (rand() % 26) + 'a';
cout << teikums[i] << " ";
}
}
else {
do {
cout << "Ievadi " << count << " burtus vienu pa vienam\n";
for (i = 1; i <= count; i++) {
cin >> teikums[i];
if (!((teikums[i] >= 'a' && teikums[i] <= 'z') || (teikums[i] >=
'A' && teikums[i] <= 'Z'))) {
cout << "Kluda! Ievadiet tikai burtus\n";
i = i - 1;
}
}
}
while (i <= count);
}
teikums.erase(teikums.begin() + 3);
do {
cout << "\n";
cout << "\n1.Izpildit individualo uzdevumu";
cout << "\n2.Pievienot jaunu elementu vektoram";
cout << "\n3.Dzest elementu no vektroa";
cout << "\n4.Sakt programmu no jauna";
cout << "\n5.Beigt Darbu";
cout << "\nIevadi izveli : ";
cin >> opcijas;
switch (opcijas) {
case 1:
izpildit_uzdevumu(teikums);
break;
case 2:
pievienot_elementu(teikums, count);
break;
case 3:
dzest_elementu(teikums);
break;
case 4:
no_jauna();
break;
case 5:
return 0;
}
}
while (opcijas != 4);
getch();
}
void izpildit_uzdevumu(vector<char>& teikums) {
patskani = 0;
for (i = 0; i <= count; i++) {
cout << " " << teikums[i];
}
cout << "\nIzmantotie Patskani:";
for (i = 1; i < count; i = i + 2) {
if (teikums[i] == 'a' || teikums[i] == 'e' || teikums[i] == 'i' ||
teikums[i] == 'o' || teikums[i] == 'u' || teikums[i] == 'A' ||
teikums[i] == 'E' || teikums[i] == 'I' || teikums[i] == 'O' ||
teikums[i] == 'U') {
patskani = patskani + 1;
cout << teikums[i];
}
}
cout << "\nPatskanu Skaits: " << patskani;
}

When you erase the element, you should also decrease count, or use teikums.size() to monitor the size of your vector.
You had 6 elements, you did:
teikums.erase(teikums.begin() + 3);
which erases the 4th element, thus now the vector has 5 elements in number.
Check the example in the ref too.

Related

boolean check behaving unexpectedly when returning value

#include <iostream>
#include <string>
bool is_favorite(std::string word)
{
int isTrueCounter = 0;
std::cout << "\nisTrueCounter: " << isTrueCounter;
if (isTrueCounter == word.length())
{
return true;
}
else {
for (int i = 0; i < word.length(); i++)
{
if (word[i] == 'a' || word[i] == 'A')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'c' || word[i] == 'C')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else {
if (word[i] == 'd' || word[i] == 'D')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'e' || word[i] == 'E')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'f' || word[i] == 'F')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
}
}
}
}
}
} //for
}
std::cout << "\nisTrueCounter: " << isTrueCounter;
}
int main()
{
std::string favWord;
std::cout << "Please input your word: ";
std::cin >> favWord;
std::cout << "\nFavWord Length: " << favWord.length();
if (is_favorite(favWord) == true)
{
std::cout << "\nThis is a favorite word!";
}
else
{
std::cout << "\nThis is NOT a favorite word!";
}
}
Here is my code, I am attempting to pass a string into a boolean function that will return true if all criteria is met by the string passed. The qualifications for a "passing" word is that it contains ONLY the letters a-f (of either case) so words like AaAa or Cafe or Bad should pass, but after trial and error, even words that I know should pass are failing and I feel like I am keeping track of the letters' qualifications properly, by incrementing on a variable (isTrueCounter) to count if all the characters in the string are qualifying characters, but even when the function should be returning true, the false case displays. What am I doing wrong? What am I not seeing? When I run this code it will display the variables to help keep track of when stuff is being added to the holder variables but even when all the numbers are right the false case displays.
You didn't return anything, you can do this in many way. For example from your code, return false immediatly after condition is not true (not in a-f).
bool is_favorite(std::string word)
{
int isTrueCounter = 0;
std::cout << "\nisTrueCounter: " << isTrueCounter;
if (isTrueCounter == word.length())
{
return true;
}
else {
for (int i = 0; i < word.length(); i++)
{
if (word[i] == 'a' || word[i] == 'A')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'c' || word[i] == 'C')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else {
if (word[i] == 'd' || word[i] == 'D')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'e' || word[i] == 'E')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'f' || word[i] == 'F')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
} else { //add this else clause
return false;
}
}
}
}
}
}
} //for
}
std::cout << "\nisTrueCounter: " << isTrueCounter;
}
But some of your code can improve.
1.I don't know why you add these lines. This will never true unless word.length() is 0.
if (isTrueCounter == word.length())
{
return true;
}
2.Don't split condition that can write in one if into many if, it's a bad behavior.
if (word[i] == 'a' || word[i] == 'A')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
This is better.
if (word[i] == 'a' || word[i] == 'A' || word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
3.You can compare char, instead of check if word[i] == 'a'... Use > < >= <=.
if (word[i] >= 'a' && word[i] <= 'f' || word[i] >= 'A' && word[i] <= 'F')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
4.string is already in iostream you don't have to import it again.
In conclusion your code can turn into this
bool is_favorite(std::string word)
{
int isTrueCounter = 0;
for (int i = 0; i < word.length(); i++)
{
if (word[i] >= 'a' && word[i] <= 'f' || word[i] >= 'A' && word[i] <= 'F') {
isTrueCounter++;
std::cout << "\nisTrue +1 ";
} else {
return false;
}
}
std::cout << "\nisTrueCounter: " << isTrueCounter;
return true;
}

C++ Program leaving my for loop prematurely

I'm working on a little poker application and i've run into the first problem I just can't seem to comprehend.
while (allplayersGood != 1) { //round table till all decided
cout << "TOP OF WHILE LOOP";
for (int i = 0; i < PLAYER_COUNT; i++) { //for loop for decisions from non button or blinds
int player_decision = 1;
char choice;
if ((players[i].playerhand.card1.value != 'F') && (players[i].playerhand.card1.value != 'C')) {
if ((players[i].blind != 1 && players[i].blind != 2) && players[i].button != true) {
cout << "\n\n";
cout << " POT: " << playerTable->currentPot;
cout << "\n";
for (int i = 0; i < PLAYER_COUNT; i++) {
cout << "Player " << players[i].playernumber;
cout << " (" << players[i].chip_amount << ") ";
}
while (player_decision == 1) {
if (playerTable->currentBet > players[i].currentBet) {
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "Type F for Fold, B for Call, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'F') {
player_decision = 0;
players[i].fold();
}
if (choice == 'R') {
player_decision = 0;
players[i].bet(playerTable);
}
if (choice == 'B') {
player_decision = 0;
players[i].call(playerTable);
}
}
if ((playerTable->currentBet == players[i].currentBet) && player_decision != 0) { //big blind after round table
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "Type C for Check, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'B') {
player_decision = 0;
players[i].bet(playerTable);
}
if (choice == 'C') {
if (players[i].check(playerTable) == true) {
player_decision = 0;
}
}
}
}
}
else if (players[i].blind == 1 || players[i].blind == 2) {
if (players[i].blind == 1) {
players[i].chip_amount -= sblind;
playerTable->currentPot += sblind;
players[i].blind = 0;
players[i].currentBet = sblind;
}
if (players[i].blind == 2) {
players[i].chip_amount -= bblind;
playerTable->currentPot += bblind;
players[i].blind = 0;
players[i].currentBet = bblind;
}
}
}
}
for (int i = 0; i < PLAYER_COUNT; i++) { //seperate loop for button and blinds that were ignored in loop above
int player_decision = 1;
char choice;
if (players[i].button == true || players[i].blind == 1) { //button and small blind
cout << "\n\n";
cout << " POT: " << playerTable->currentPot;
cout << "\n";
for (int i = 0; i < PLAYER_COUNT; i++) {
cout << "Player " << players[i].playernumber;
cout << " (" << players[i].chip_amount << ") ";
}
while (player_decision == 1) {
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "Type F for Fold, B for Call, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'F') {
player_decision = 0;
players[i].fold();
}
if (choice == 'R') {
player_decision = 0;
players[i].bet(playerTable);
}
if (choice == 'B') {
player_decision = 0;
players[i].call(playerTable);
}
}
}
cout << i;
if (players[i].blind == 2) { //big blind
cout << "\n\n";
cout << " POT: " << playerTable->currentPot;
cout << "\n";
for (int i = 0; i < PLAYER_COUNT; i++) {
cout << "Player " << players[i].playernumber;
cout << " (" << players[i].chip_amount << ") ";
}
while (player_decision == 1) {
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "C for Check, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'C') {
if (players[i].check(playerTable) == true) {
player_decision = 0;
}
}
if (choice == 'R') {
player_decision = 0;
players[i].bet(playerTable);
}
}
}
}
int playersBetting = 0;
int playersGood = 0;
int playersChecked = 0;
int playersNot = 0;
for (int i = 0; i < PLAYER_COUNT; i++) {
if (players[i].playerhand.card1.value != 'F') {
playersBetting++;
if (players[i].currentBet == playerTable->currentBet) {
playersGood++;
}
}
}
for (int i = 0; i < PLAYER_COUNT; i++) {
if (players[i].playerhand.card1.value != 'F') {
if (players[i].isChecked == true) {
playersChecked++;
}
else {
playersNot++;
}
}
}
cout << playersBetting << playersGood;
if ((playersBetting == playersGood) || (playersNot == 0)) {
cout << "NEXT ROUND STARTED";
}
}
The issue is, during the second for loop with comment "seperate loop for button and blinds that were ignored in loop above" after the first if statement succeeds because players[0] has button equal to true, the player will make the terminal input as a decision, and the program will exit the for loop and go down to the end with the playersBetting and playersGood loops, then return back to the for loop at index 1 correctly.
I'm sorry if this is a little complicated to understand there is a lot of code that I probably didn't put into context very well, if you need any extra information please let me know.
Thank you.
You seem to have different loops inside one another. This is possible, but in that case, you need to use another loop variable (j instead of i), let me show you what happens:
for i ...
for j ...
This causes the following values to be taken for i and j:
i j
1 1
1 2
1 ...
1 n
2 1
2 2
2 ...
2 n
...
n 1
n 2
...
n n
... and here it stops.
If you keep using i in the inner loop, this is what you get:
i (outside loop) i (inside loop)
1 1
2 2 // indeed: changing i inside also changes i outside
... ...
n n
So you jump out of the outside loop, even after just having looped the inside loop one time.
I figured it out, it was unrelated to the actual loop and actually had to do with a value I changed upstream. Thank you for the few who tried to help with such little context haha
Have a good one

What's wrong with this Minimax implementation for Tic-Tac-Toe?

I wanted to expand on an older Tic Tac Toe game I made where two players can play versus each other. I want to give the user the option of playing against a difficult AI. The issue is that the AI won't pick the best move all the time. For instance, it will always pick spot 1 if going first. If the user picks spot 2, it will pick spot 4. After this, no matter what the user picks (besides spot 7) the AI won't pick spot 7. Victory for the AI is far from inevitable (the user can still win the game at this point), so that's not the problem.
Any help is appreciated. Thanks!
I'm positive the problem is with my minimax or bestmove functions. It may just be that I haven't properly implemented by minimax function, but I can't spot the issue.
#include <iostream>
#include <iomanip>
#include <string>
#include <array>
// This is a program to play a single game of tic-tac-toe
// between either two human (non-AI) players or an AI.
using namespace std;
void PrintBoard(array <char, 9>);
int programprogress();
int checkwin(array <char, 9>);
int minimax(array <char, 9>, int, int, bool);
int bestMove(array <char, 9>, int);
int Opposite(int);
char PlayerSymbol(int);
const int SIZE = 9;
array <char, SIZE> Pos = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int player_number = 1;
int k = -11, result;
bool AI = false, first;
// Global variables used by 2 or more functions.
// Array had to be initialized with numbers instead of blank spaces
// because the check win function wouldn't work properly.
int main()
{
string userinp;
cout << "This is tic tac toe! Here's your board!" << endl;
PrintBoard(Pos);
cout << "Would you like to play versus an AI? (Y/N)" << endl;
cin >> userinp;
if (userinp[0] == 'Y')
{
cout << "Excellent! Would you like to start first, or second? (F/S)" << endl;
cin >> userinp;
if (userinp[0] == 'F')
{
cout << "You will start first!" << endl;
first = false;
player_number = 2;
}
else
{
cout << "The AI will start first!" << endl;
first = true;
}
AI = true;
}
else
{
cout << "Excellent! Your game will start soon." << endl;
}
result = programprogress();
player_number--;
PrintBoard(Pos);
if (result == 1)
cout << endl << "Player " << player_number << " has won!!!\n";
else if (result == 10)
cout << endl << "The AI has won! Better luck next time!\n";
else if (result = -10)
cout << endl << "You beat the world's best AI! Congratulations!\n";
else
cout << endl << "The game has been drawn!" << endl;
return 0;
}
void PrintBoard(array <char, 9> Pos)
{
system("cls");
cout << setw(6) << "|" << setw(6) << "|" << endl << setw(3) << Pos[0] << setw(3) << "|" << setw(3) << Pos[1] << setw(3) << "|" << setw(3) << Pos[2] << " TIC TOE" << endl;
cout << "_____|_____|_____" << endl;
cout << setw(6) << "|" << setw(6) << "|" << endl << setw(3) << Pos[3] << setw(3) << "|" << setw(3) << Pos[4] << setw(3) << "|" << setw(3) << Pos[5] << " TAC " << endl;
cout << "_____|_____|_____" << endl;
cout << setw(6) << "|" << setw(6) << "|" << endl << setw(3) << Pos[6] << setw(3) << "|" << setw(3) << Pos[7] << setw(3) << "|" << setw(3) << Pos[8] << " TIC TOE " << endl;
cout << " | |" << endl;
}
int programprogress()
{
while (k == -11 && AI)
{
bool InvalidChoice = false;
char letter;
//player_number = (player_number % 2) ? 1 : 2;
int PlayerChoice;
if (player_number == 2)
{
cout << endl << "What is your move?" << endl;
cin >> PlayerChoice;
while ((PlayerChoice < 1) || (PlayerChoice > 9))
{
cout << "That's an invalid choice! Please choose a number that is 1-9!" << endl;
cin >> PlayerChoice;
}
PlayerChoice--;
letter = (!first) ? 'X' : 'O';
if (Pos[PlayerChoice] == '1' || Pos[PlayerChoice] == '2' || Pos[PlayerChoice] == '3' || Pos[PlayerChoice] == '4' || Pos[PlayerChoice] == '5' || Pos[PlayerChoice] == '6' || Pos[PlayerChoice] == '7' || Pos[PlayerChoice] == '8' || Pos[PlayerChoice] == '9')
{
Pos[PlayerChoice] = letter;
PrintBoard(Pos);
}
/*else
{
cout << "That space is already taken!" << endl;
player_number--;
}*/
k = checkwin(Pos);
if (k != -11)
k = k * -10;
player_number = 1;
}
else
{
cout << endl << "The computer has made its move!" << endl;
letter = (first) ? 'X' : 'O';
if (first)
PlayerChoice = bestMove(Pos, 1);
else
PlayerChoice = bestMove(Pos, 2);
Pos[PlayerChoice] = letter;
PrintBoard(Pos);
k = checkwin(Pos);
if (k != -11)
k = k * 10;
player_number = 2;
}
}
while (k == -11 && !AI)
{
bool InvalidChoice = false;
char letter;
player_number = (player_number % 2) ? 1 : 2;
int PlayerChoice;
cout << endl << "What's player " << player_number << "'s move?" << endl;
cin >> PlayerChoice;
while ((PlayerChoice < 1) || (PlayerChoice > 9))
{
cout << "That's an invalid choice! Please choose a number that is 1-9!" << endl;
cin >> PlayerChoice;
}
PlayerChoice--;
letter = (player_number == 1) ? 'X' : 'O';
if (Pos[PlayerChoice] == '1' || Pos[PlayerChoice] == '2' || Pos[PlayerChoice] == '3' || Pos[PlayerChoice] == '4' || Pos[PlayerChoice] == '5' || Pos[PlayerChoice] == '6' || Pos[PlayerChoice] == '7' || Pos[PlayerChoice] == '8' || Pos[PlayerChoice] == '9')
{
Pos[PlayerChoice] = letter;
PrintBoard(Pos);
}
else
{
cout << "That space is already taken!" << endl;
player_number--;
}
k = checkwin(Pos);
player_number++;
}
return k;
}
int checkwin(array <char, SIZE> Pos)
{
if (Pos[0] == Pos[1] && Pos[1] == Pos[2])
return 1;
else if (Pos[3] == Pos[4] && Pos[4] == Pos[5])
return 1;
else if (Pos[6] == Pos[7] && Pos[7] == Pos[8])
return 1;
else if (Pos[0] == Pos[3] && Pos[3] == Pos[6])
return 1;
else if (Pos[1] == Pos[4] && Pos[4] == Pos[7])
return 1;
else if (Pos[2] == Pos[5] && Pos[5] == Pos[8])
return 1;
else if (Pos[0] == Pos[4] && Pos[4] == Pos[8])
return 1;
else if (Pos[2] == Pos[4] && Pos[4] == Pos[6])
return 1;
else if (Pos[0] != '1' && Pos[1] != '2' && Pos[2] != '3'
&& Pos[3] != '4' && Pos[4] != '5' && Pos[5] != '6'
&& Pos[6] != '7' && Pos[7] != '8' && Pos[8] != '9')
return 0;
else
return -11;
}
int minimax(array <char, SIZE> newpos, int depth, int player, bool opp)
{
int scale = 0;
if ((player == 1 && first) || (player == 2 && !first))
scale = 10;
else
scale = -10;
//cout << scale;
int score = scale*checkwin(newpos);
if (score < 0)
score += depth;
else if (score > 0)
score -= depth;
if (score == -10 || score == 10 || score == 0)
return score;
if (opp)
{
int best = -1000;
for (int i = 0; i < SIZE; i++)
{
if (newpos[i] != 'X' && newpos[i] != 'O')
{
char temp = newpos[i];
newpos[i] = PlayerSymbol(player);
best = max(best, minimax(newpos, depth + 1, Opposite(player), !opp));
newpos[i] = temp;
}
}
return best;
}
else
{
int best = 1000;
for (int i = 0; i < SIZE; i++)
{
if (newpos[i] != 'X' && newpos[i] != 'O')
{
char temp = newpos[i];
newpos[i] = PlayerSymbol(player);
best = min(best, minimax(newpos, depth + 1, Opposite(player), !opp));
newpos[i] = temp;
}
}
return best;
}
}
int bestMove(array <char, SIZE> newpos, int player)
{
int best = -1000;
int bestpos = -1;
for (int i = 0; i < SIZE; i++)
{
if (newpos[i] != 'X' && newpos[i] != 'O')
{
char temp = newpos[i];
newpos[i] = PlayerSymbol(player);
int move = minimax(newpos, 0, player, !first);
newpos[i] = temp;
if (move > best)
{
//cout << "I like pineapple on pizza" << endl;
bestpos = i;
best = move;
}
/*if (move == best)
{
cout << "I like pineapple on pizza" << endl;
}*/
}
}
cout << bestpos;
return bestpos;
}
int Opposite(int x)
{
if (x == 1)
return 2;
else
return 1;
}
char PlayerSymbol(int x)
{
if (x == 1)
return 'X';
else
return 'O';
}
An out of bounds error due to the -1 value of bestpos. I'm not sure how to change this, though.
There are 4 issues that I could find. Solving them seems to lead to the intended behavior.
Firstly, when you call minimax(newpos, 0, player, !first); from inside the bestMove function, you pass player rather than Opposite(player), indicating that the first minimax step will be performed by the same player as the bestMove step. In other words: The AI makes two successive moves for itself. Therefore player needs to be changed to Opposite(player).
Secondly, minimax has a bool variable named opp that seems to indicate whether it is the AI or its opponent making the move. For the first minimax step, opp is set to !first, indicating that only if the AI goes first, the opponent will make a move after the AI. That is incorrect. It is always the opponent making a move after the AI. So bestMove should call minimax with true rather than !first. As an aside, opp is redundant, because you can use (player == 1 && first) || (player == 2 && !first) to check whether it's the AI or its opponent making the move.
Thirdly, the scale is set the wrong way around. With (player == 1 && first) || (player == 2 && !first) you check whether its the AI making a move. But you do that in the next minimax step, after the potentially winning move. So if the AI is making a move and the game is already won, then the opponent made the winning move, not the AI. Ergo, the scale should be
if ((player == 1 && first) || (player == 2 && !first))
scale = -10;
else
scale = 10;
instead.
Lastly, you check whether the score is 10 or -10 after adding the depth. If depth is not 0, then this check will always fail. So beyond depth 0, the AI can only see a draw, never a win. You could instead write
if (score == -10 || score == 10 || score == 0)
{
if (score < 0)
score += depth;
else if (score > 0)
score -= depth;
return score;
}
Hope this answers your question fully.

TicTacToe in C++ won't work? Help please

So I'm trying to get this simple Multiplayer TicTacToe game to work in eclipse (C++ version), but it seems that whenever I run my program, only for the top row of a TicTacToe can people win.
Here's my code:
#include <iostream>
using namespace std;
string board[3][3]; // creates the game board
void draw(int player, int num)
{
num--;
int row = num/3;
int col = num%3;
if ( player == 1 ) board[row][col] = "X";
else board[row][col] = "O";
}// end draw method
bool checkWin(int num)
{
bool win = false;
if (num == 1 || num == 2 || num == 3)
{
if ( board[0][0] == board[0][1] && board[0][0] == board[0][2])
return true;
}
if (num == 4 || num == 5 || num == 6)
{
if ( board[1][0] == board[1][1] && board[1][0] == board[1][2])
return true;
}
if (num == 7 || num == 8 || num == 9)
{
if ( board[2][0] == board[2][1] && board[2][0] == board[2][2])
return true;
}
if (num == 1 || num == 4 || num == 7)
{
if ( board[0][0] == board[1][0] && board[0][0] == board[2][0])
return true;
}
if (num == 2 || num == 5 || num == 8)
{
if ( board[0][1] == board[1][1] && board[0][1] == board[2][1])
return true;
}
if (num == 3 || num == 6 || num == 9)
{
if ( board[0][2] == board[1][2] && board[0][2] == board[2][2])
return true;
}
if (num == 1 || num == 5 || num == 9)
{
if ( board[0][0] == board[1][1] && board[0][0] == board[2][2])
return true;
}
if (num == 3 || num == 5 || num == 7)
{
if ( board[0][2] == board[1][1] && board[0][2] == board[2][0])
return true;
}
return win;
} // end checkWin method
int main()
{
cout << "C++ TIC TAC TOE GAME" << endl;
cout << "The board is labeled from 1-9 in row-major order." << endl;
bool winner = false;
int turns = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = "-";
cout << board[i][j] << " ";
}
cout << endl; // "enters" to next line
} // prints the game board 2d array
while (winner == false && turns < 9)
{
int player = 0;
int placedAt = 0;
if ( turns % 2 == 0 )
{
int num1;
cout << "Player 1 enter what space to place X: ";
cin >> num1;
player = 1;
draw(player,num1);
placedAt = num1;
}
else
{
int num2;
cout << "Player 2 enter what space to place O: ";
cin >> num2;
player = 2;
draw(player,num2);
placedAt = num2;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << board[i][j] << " ";
}
cout << endl; // "enters" to next line
} // prints the game board 2d array
winner = checkWin(placedAt);
if (winner == true)
{
cout << endl << "Player " << player << " WINS!";
}
turns++;
cout << endl;
} // end while loop
if (winner == false) cout << endl << "NO ONE WON!";
return 0;
} // end main method
Change string board[3][3]; to char board[3][3]; , and "X" to 'X'.
The corrected code below should compile just fine.
#include <iostream>
using namespace std;
char board[3][3]; // creates the game board
void draw(int player, int num)
{
num--;
int row = num/3;
int col = num%3;
if ( player == 1 ) board[row][col] = 'X';
else board[row][col] = 'O';
}// end draw method
bool checkWin(int num)
{
bool win = false;
if (num == 1 || num == 2 || num == 3)
{
if ( board[0][0] == board[0][1] && board[0][0] == board[0][2])
return true;
}
if (num == 4 || num == 5 || num == 6)
{
if ( board[1][0] == board[1][1] && board[1][0] == board[1][2])
return true;
}
if (num == 7 || num == 8 || num == 9)
{
if ( board[2][0] == board[2][1] && board[2][0] == board[2][2])
return true;
}
if (num == 1 || num == 4 || num == 7)
{
if ( board[0][0] == board[1][0] && board[0][0] == board[2][0])
return true;
}
if (num == 2 || num == 5 || num == 8)
{
if ( board[0][1] == board[1][1] && board[0][1] == board[2][1])
return true;
}
if (num == 3 || num == 6 || num == 9)
{
if ( board[0][2] == board[1][2] && board[0][2] == board[2][2])
return true;
}
if (num == 1 || num == 5 || num == 9)
{
if ( board[0][0] == board[1][1] && board[0][0] == board[2][2])
return true;
}
if (num == 3 || num == 5 || num == 7)
{
if ( board[0][2] == board[1][1] && board[0][2] == board[2][0])
return true;
}
return win;
} // end checkWin method
int main()
{
cout << "C++ TIC TAC TOE GAME" << endl;
cout << "The board is labeled from 1-9 in row-major order." << endl;
bool winner = false;
int turns = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = '-';
cout << board[i][j] << ' ';
}
cout << endl; // "enters" to next line
} // prints the game board 2d array
while (winner == false && turns < 9)
{
int player = 0;
int placedAt = 0;
if ( turns % 2 == 0 )
{
int num1;
cout << "Player 1 enter what space to place X: ";
cin >> num1;
player = 1;
draw(player,num1);
placedAt = num1;
}
else
{
int num2;
cout << "Player 2 enter what space to place O: ";
cin >> num2;
player = 2;
draw(player,num2);
placedAt = num2;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << board[i][j] << " ";
}
cout << endl; // "enters" to next line
} // prints the game board 2d array
winner = checkWin(placedAt);
if (winner == true)
{
cout << endl << "Player " << player << " WINS!";
}
turns++;
cout << endl;
} // end while loop
if (winner == false) cout << endl << "NO ONE WON!";
return 0;
} // end main method

C++ Small Straight (like yahtzee or poker). 5 Dice roll (1234)/(2345)/(3456)

Im a beginner with C++ and this is for homework but Im stuck. I have one remaining problem and then im finished.
I can'T think of an algorithm that will tell if the user entered a small straight (1234) or (2345) or (3456).
I know how to do it using a loop but is it possible to not use a loop? When this was assigned, we did not learned about loops yet. I think we are only suppose to use if statements.
I started coding for it (I wrote what the dice can be, but cant figure out how to let only 4 dice go straight without an array and loop). Im stuck! Please help!
Can you also check at my code and see if there is anything wrong so far.
Assigned Problem:
Playing poker with dice. (Kinda like Yahtzee)
• Have the user enter 5 dice rolls (1-6) in any order. Have the user type in 5 numbers. If any are outside of the 1 to 6 inclusive range, just end the program.
• Count and print the number of ones entered.
• Count and print the number of twos entered.
• Count and print the number of threes entered.
• Count and print the number of fours entered.
• Count and print the number of fives entered.
• Count and print the number of sixes entered.
• Tell if there are three or more dice the same.
• Tell if there are four or more dice the same.
• Tell if there are five dice the same.
• Tell if there is a full house, 3 the same and 2 the same.
• Tell if there is a long straight ... 1 2 3 4 5 or 2 3 4 5 6
• Tell if there is a small straight (1 2 3 4) or (2 3 4 5) or (3 4 5 6)
My Code:
int main(int argc, char** argv)
{
//
int Roll1, Roll2, Roll3, Roll4, Roll5;
int numberOf1s = 0, numberOf2s = 0, numberOf3s = 0, numberOf4s = 0, numberOf5s = 0, numberOf6s = 0;
bool TwoOfaKind = false;
bool ThreeOfaKind = false;
cout << "Roll 5 dice. Enter them below." << endl;
cout << "Roll 1: ";
cin >> Roll1;
cout << "Roll 2: ";
cin >> Roll2;
cout << "Roll 3: ";
cin >> Roll3;
cout << "Roll 4: ";
cin >> Roll4;
cout << "Roll 5: ";
cin >> Roll5;
if (Roll1 > 6 || Roll1 < 1 || Roll2 > 6 || Roll2 < 1 || Roll3 > 6 || Roll3 < 1 || Roll4 > 6 || Roll4 < 1 || Roll5 > 6 || Roll5 < 1 )
{
exit(1);
}
if (Roll1 == 1)
{
numberOf1s += 1;
}
if (Roll2 == 1)
{
numberOf1s += 1;
}
if (Roll3 == 1)
{
numberOf1s += 1;
}
if (Roll4 == 1)
{
numberOf1s += 1;
}
if (Roll5 == 1)
{
numberOf1s += 1;
}
cout << "There are " << numberOf1s << " ones." << endl;
if (Roll1 == 2)
{
numberOf2s += 1;
}
if (Roll2 == 2)
{
numberOf2s += 1;
}
if (Roll3 == 2)
{
numberOf2s += 1;
}
if (Roll4 == 2)
{
numberOf2s += 1;
}
if (Roll5 == 2)
{
numberOf2s += 1;
}
cout << "There are " << numberOf2s << " twos." << endl;
if (Roll1 == 3)
{
numberOf3s += 1;
}
if (Roll2 == 3)
{
numberOf3s += 1;
}
if (Roll3 == 3)
{
numberOf3s += 1;
}
if (Roll4 == 3)
{
numberOf3s += 1;
}
if (Roll5 == 3)
{
numberOf3s += 1;
}
cout << "There are " << numberOf3s << " threes." << endl;
if (Roll1 == 4)
{
numberOf4s += 1;
}
if (Roll2 == 4)
{
numberOf4s += 1;
}
if (Roll3 == 4)
{
numberOf4s += 1;
}
if (Roll4 == 4)
{
numberOf4s += 1;
}
if (Roll5 == 4)
{
numberOf4s += 1;
}
cout << "There are " << numberOf4s << " fours." << endl;
if (Roll1 == 5)
{
numberOf5s += 1;
}
if (Roll2 == 5)
{
numberOf5s += 1;
}
if (Roll3 == 5)
{
numberOf5s += 1;
}
if (Roll4 == 5)
{
numberOf5s += 1;
}
if (Roll5 == 5)
{
numberOf5s += 1;
}
cout << "There are " << numberOf5s << " fives." << endl;
if (Roll1 == 6)
{
numberOf6s += 1;
}
if (Roll2 == 6)
{
numberOf6s += 1;
}
if (Roll3 == 6)
{
numberOf6s += 1;
}
if (Roll4 == 6)
{
numberOf6s += 1;
}
if (Roll5 == 6)
{
numberOf6s += 1;
}
cout << "There are " << numberOf6s << " sixes." << endl << endl;
if (numberOf1s == 2 || numberOf2s == 2 || numberOf3s == 2 || numberOf4s == 2 || numberOf5s == 2 || numberOf6s == 2)
{
TwoOfaKind = true;
}
if (numberOf1s == 3 || numberOf2s == 3 || numberOf3s == 3 || numberOf4s == 3 || numberOf5s == 3 || numberOf6s == 3)
{
cout << "Yes three of a kind!" << endl;
ThreeOfaKind = true;
}
else
{
cout << "No three of a kind" << endl;
}
if (numberOf1s == 4 || numberOf2s == 4 || numberOf3s == 4 || numberOf4s == 4 || numberOf5s == 4 || numberOf6s == 4)
{
cout << "Yes four of a kind!" << endl;
}
else
{
cout << "No four of a kind" << endl;
}
if (numberOf1s == 5 || numberOf2s == 5 || numberOf3s == 5 || numberOf4s == 5 || numberOf5s == 5 || numberOf6s == 5)
{
cout << "Yes five of a kind!" << endl;
}
else
{
cout << "No five of a kind" << endl;
}
//
if (TwoOfaKind == true && ThreeOfaKind == true)
{
cout << "Yes Full House!" << endl;
}
else
{
cout << "No Full House" << endl;
}
//
if (Roll1 == Roll2 && Roll2 == Roll3 && Roll3 == Roll4 && Roll4 == Roll5)
{
cout << "No Long Straight" << endl;
}
else
{
if (((Roll1 >= 1 && Roll1 < 6) && (Roll2 >= 1 && Roll2 < 6) && (Roll3 >= 1 && Roll3 < 6) && (Roll4 >= 1 && Roll4 < 6) && (Roll5 >= 1 && Roll5 < 6)) && (Roll1 != Roll2 && Roll2 != Roll3 && Roll3 != Roll4 && Roll4 != Roll5))
{
cout << "Yes Long Straight!" << endl;
}
else if (((Roll1 > 1 && Roll1 <= 6) && (Roll2 > 1 && Roll2 <= 6) && (Roll3 > 1 && Roll3 <= 6) && (Roll4 > 1 && Roll4 <= 6) && (Roll5 > 1 && Roll5 <= 6)) && (Roll1 != Roll2 && Roll2 != Roll3 && Roll3 != Roll4 && Roll4 != Roll5))
{
cout << "Yes Long Straight!" << endl;
}
else
{
cout << "No Long Straight" << endl;
}
//***HELP ME HERE PLEASE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!***
if (Roll1 == Roll2 && Roll2 == Roll3 && Roll3 == Roll4 && Roll4 == Roll5)
{
cout << "No Small Straight" << endl;
}
else
{
if (((Roll1 > 1 && Roll1 <= 4) && (Roll2 > 1 && Roll2 <= 4) && (Roll3 > 1 && Roll3 <= 4) && (Roll4 > 1 && Roll4 <= 4) && (Roll5 > 1 && Roll5 <= 4)) && (Roll1 != Roll2 && Roll2 != Roll3 && Roll3 != Roll4 && Roll4 != Roll5))
{
cout << "Yes Small Straight!" << endl;
}
else if (((Roll1 > 1 && Roll1 <= 5) && (Roll2 > 1 && Roll2 <= 5) && (Roll3 > 1 && Roll3 <= 5) && (Roll4 > 1 && Roll4 <= 5) && (Roll5 > 1 && Roll5 <= 5)) && (Roll1 != Roll2 && Roll2 != Roll3 && Roll3 != Roll4 && Roll4 != Roll5))
{
cout << "Yes Small Straight!" << endl;
}
else if (((Roll1 > 2 && Roll1 <= 6) && (Roll2 > 2 && Roll2 <= 6) && (Roll3 > 2 && Roll3 <= 6) && (Roll4 > 2 && Roll4 <= 6) && (Roll5 > 2 && Roll5 <= 6)) && (Roll1 != Roll2 && Roll2 != Roll3 && Roll3 != Roll4 && Roll4 != Roll5))
{
cout << "Yes Small Straight!" << endl;
}
else
{
cout << "No Small Straight" << endl;
}
}
return 0;
}
int bits = (1 << Roll1) | (1 << Roll2) | (1 << Roll3) | (1 << Roll4) | (1 << Roll5);
if((bits & 0x1E) == 0x1E || (bits & 0x3C) == 0x3C || (bits & 0x78) == 0x78)
cout << "Yes Small Straight!" << endl;
I decided to rewrite your program which refactors a lot of the code and also solves your problem. Do note I assumed you are using c++ but not necessarily c++11.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
int straight_checker = 0;
int rolls[5] = {0}, num_count[6] = {0};
// use char * die_names[6] if c
string die_names[6] = {"ones", "twos", "threes", "fours", "fives", "sixes"};
bool two_kind = false, three_kind = false, four_kind = false, five_kind = false;
cout << "Roll 5 dice. Enter them below." << endl;
for(unsigned int i = 0; i < sizeof(rolls) / sizeof(int); ++i)
{
cout << "Roll " << i + 1 << ": ";
cin >> rolls[i];
if(rolls[i] < 1 || rolls[i] > 6)
{
exit(1);
}
else
{
num_count[rolls[i] - 1]++;
// This will set a binary "1" at the location rolls[i] - 1, easy way to check straights
straight_checker ^= (-1 ^ straight_checker) & (1 << (rolls[i] - 1));
}
}
for(unsigned int i = 0; i < sizeof(num_count) / sizeof(int); ++i)
{
cout << endl << "There are " << num_count[i] << " " <<die_names[i];
// If you are using c++11, then use std::find outside loop
switch(num_count[i])
{
case 2:
two_kind = true;
break;
case 3:
three_kind = true;
break;
case 4:
four_kind = true;
break;
case 5:
five_kind = true;
break;
}
}
cout << endl;
if(four_kind) cout << "Yes four of a kind!" << endl;
if(five_kind) cout << "Yes five of a kind!" << endl;
if(two_kind && three_kind) cout << "Yes Full House!" << endl;
else
{
if(three_kind) cout << "Yes three kind" << endl;
else if(two_kind) cout << "Yes two kind" << endl;
}
// 31 in binary is 011111, and 62 is 111110 (ie 5 straight 1s)
if(straight_checker == 31 || straight_checker == 62)
{
cout << "Yes long straight!" << endl;
}
// 47 in binary is 101111, 30 is 011110, 61 is 111101, etc (ie 4 straight 1s)
if(straight_checker == 15 || straight_checker == 47 || straight_checker == 30 || straight_checker == 60 || straight_checker == 61)
{
cout << "Yes short straight" << endl;
}
return 0;
}
I combine all the rolls in a single variable.
A 32 bits long can easily hold all the counts:
//Number of ones V
long result = 0x000000;
// sixes ^
Each hexadecimal digit can hold a value between 0 and F (15) so that's sufficient for 15 rolls, and you only need 5.
Your long straight would be 0x111110 or 0x011111. A full house 555-33 is 0x030200. A short straight is a bit more complex, it looks like 0x101111 or 0x001121. To get rid of that 2, I'd use a bit shift:
long test = (result | (result>>1)) & 0x777777 and then it's a straightforward check: test & 0x001111 == 0x001111 etc.