#include <iostream>
using namespace std;
int main()
{
int tablica[9];
string inputromanum;
cout << "ROMAN: ";
cin >> inputromanum;
int maxindeks;
bool disablenextcomp = false;
int readysolution = 0;
maxindeks = inputromanum.length() - 1;{}{}
for (int i = 0; i <= maxindeks; i++)
{
if (inputromanum[i] == 'M' || inputromanum[i] == 'm')
{
tablica[i] = 1000;
}
if (inputromanum[i] == 'D' || inputromanum[i] == 'd')
{
tablica[i] = 500;
}
if (inputromanum[i] == 'C'|| inputromanum[i] == 'c')
{
tablica[i] = 100;
}
if (inputromanum[i] == 'L' || inputromanum[i] == 'l')
{
tablica[i] = 50;
}
if (inputromanum[i] == 'X' || inputromanum[i] == 'x')
{
tablica[i] = 10;
}
if (inputromanum[i] == 'V' || inputromanum[i] == 'v')
{
tablica[i] = 5;
}
if (inputromanum[i] == 'I' || inputromanum[i] == 'i')
{
tablica[i] = 1;
}
}
cout<<endl;
for(int i4 = 0; i4 <= maxindeks; i4++)
{
cout<<"tablica["<<i4<<"] = "<<tablica[i4]<<endl;
}
for (int i2 = 0; i2 <= maxindeks; i2++)
{
int i5 = i2 + 1;
if (i5 <= maxindeks)
{
//cout<<endl<<"tablica[i2 + 1] = "<<tablica[i2 + 1];
//cout<<endl<<"tablica[i2] = "<<tablica[i2];
//cout<<endl<<"tablica[i2 + 1] - tablica[i2] = "<<tablica[i2 + 1] - tablica[i2];
if (tablica[i2 + 1] - tablica[i2] > 0 && disablenextcomp == false)
{
//cout<<endl<<"readysolution + (tablica[i2 + 1] - tablica[i2]) = "<<readysolution + (tablica[i2 + 1] - tablica[i2])<<endl;
readysolution = readysolution + (tablica[i2 + 1] - tablica[i2]);
disablenextcomp = true;
}
else
{
if(disablenextcomp == false)
{
//cout<<endl<<"readysolution + tablica[i2] = "<<readysolution + tablica[i2]<<endl;
readysolution = readysolution + tablica[i2];
}
else
{
disablenextcomp = false;
}
}
}
else
{
if(disablenextcomp == false)
{
//cout<<endl<<endl<<"OSTATNI INDEKS";
//cout<<endl<<"tablica[i2] = "<<tablica[i2];
//cout<<endl<<"readysolution + tablica[i2] = "<<readysolution + tablica[i2];
readysolution = readysolution + tablica[i2];
}
}
i5++;
}
cout << endl << readysolution;
}
This is my program. made for decoding roman numerals into arabic ones. It works as intended in most cases, however, one of my colleagues found it to produce this error while inputting MMMCMXCVIII into the program:
*** stack smashing detected ***: terminated
It would refuse to work afterwards.
I wasn't able to find different numbers that would cause this error except MMMMMMMMMMM.
It seems to fail when the index of tablica array exceeds 10. I don't know why it does so, as i am a novice in c++. It should've outputted 3999 instead of the error appearing. The numbers it should process successfully should range from 1 to 5000.
Thanks to folks in the comments, I've found the cause.
The tablica[9] array is supposed to store 9 or less characters.
The length of the input (MMMCMXCVIII in this case) has more characters, therefore it makes the for loop responsible for storing values for each character to cause mentioned above error, as there are no remaining units to store the values in.
I've expanded the storage of tablica to 25 characters.
In modern C++ it is considered bad practice to use C-style arrays and index loops whenever you can avoid this. So, fo example you can rewrite first loop like this:
std::vector<int> tablica;
tablica.reserve(inputromanum.size()); // This line is not necessary, but it can help optimize memory allocations
for (char c : inputromanum)
{
if (c == 'M' || c == 'm')
{
tablica.push_back(1000);
}
if (c == 'D' || c == 'd')
{
tablica.push_back(500);
}
if (c == 'C'|| c == 'c')
{
tablica.push_back(100);
}
if (c == 'L' || c == 'l')
{
tablica.push_back(50);
}
if (c == 'X' || c == 'x')
{
tablica.push_back(10);
}
if (c == 'V' || c == 'v')
{
tablica.push_back(5);
}
if (c == 'I' || c == 'i')
{
tablica.push_back(1);
}
}
And you will avoid your issue completly. Something similar can be done with other loops too. This approach also has benefit of (somewhat) properly handling situations when input line has other symbols, which is not roman number. Try it on your version and you will see what I mean.
One more point. When you need to do something different depending of value of one variable, like you did with all those ifs. There is special statement in C/C++ for this: switch. So instead of those ifs you can do this:
std::vector<int> tablica;
tablica.reserve(inputromanum.size()); // This line is not necessary, but it can help optimize memory allocations
for (char c : inputromanum)
{
switch(c)
{
case 'M':
case 'm':
tablica.push_back(1000);
break;
case 'D':
case 'd':
tablica.push_back(500);
break;
case 'C':
case 'c':
tablica.push_back(100);
break;
case 'L':
case 'l':
tablica.push_back(50);
break;
case 'X':
case 'x':
tablica.push_back(10);
break;
case 'V':
case 'v':
tablica.push_back(5);
break;
case 'I':
case 'i':
tablica.push_back(1);
break;
}
}
Related
In C++, how do I avoid walls of ifs using for loops?
stackoverflow is requesting more text soo...
Code Example:
if(masiv[0][0] == 'X'){
masiv[0][0] = '1';
}
if(masiv[0][1] == 'X'){
masiv[0][1] = '2';
}
if(masiv[0][2] == 'X'){
masiv[0][2] = '3';
}
if(masiv[1][0] == 'X'){
masiv[1][0] = '4';
}
if(masiv[1][1] == 'X'){
masiv[1][1] = '5';
}
if(masiv[1][2] == 'X'){
masiv[1][2] = '6';
}
if(masiv[2][0] == 'X'){
masiv[2][0] = '7';
}
if(masiv[2][1] == 'X'){
masiv[2][1] = '8';
}
if(masiv[2][2] == 'X'){
masiv[2][2] = '9';
}
for (int y = 0; y < 3; ++y) {
for (int x = 0; x < 3; ++x) {
if (masiv[y][x] == 'X') {
masiv[y][x] = '1' + 3 * y + x;
}
}
}
Some explanation follows.
The following pattern is repeating:
if (masiv[...][...] == 'X') {
masiv[...][...] = '...';
}
Because it is repeating, we put it to the body of the for loop.
We need 2 for loops, because the first and the second indexes in masiv[...][...] go over all possible values independently, and each variation is present. We will use a separate loop variable for each index, thus it becomes masiv[y][x].
The lower limit for y is 0 (inclusive) and the upper limit for y is 3 (exclusive), hence the for line looks like: for (int y = 0; y < 3; ++y) {. Similarly for x.
We need a different character after the masiv[y][x] =. Since digits are next to each other in the ASCII table (e.g. '5' + 3 == '8'). we use an expression like '1' + ...y... + ...x.... The actual value starts from '1' in the beginning, and it increases by 1 as x increases, and it increases by 3 when y increases. Thus it's '1' + 3 * y + x.
Yesterday I started developing a encrypting machine, that works like a Caesar cipher. You put a message (e.g., HELLO), choose a key value (e.g., 3) and the result is KHOOR (3 letters forward).
The problem is that, if I use "cin >> msg;" I can only codify one word. If I use "getline (cin, msg);", the code doesn't work. Maybe it's a simple problem, but I can't solve it... :(
string msg;
int a, b, i, key_value;
char c;
cout << "WRITE YOUR MESSAGE:" << endl;
cin >> msg; //HERE IS THE PROBLEM!!!
system ("cls");
cout << "PUT A KEY VALUE:" << endl;
cin >> key_value;
system ("cls");
cout << "THE CODIFIED MESSAGE IS:" << endl;
for (i=0; i < msg.length(); i++) {
if (msg[i] == 'A') a = 1;
if (msg[i] == 'B') a = 2;
if (msg[i] == 'C') a = 3;
if (msg[i] == 'D') a = 4;
if (msg[i] == 'E') a = 5;
if (msg[i] == 'F') a = 6;
if (msg[i] == 'G') a = 7;
if (msg[i] == 'H') a = 8;
if (msg[i] == 'I') a = 9;
if (msg[i] == 'J') a = 10;
if (msg[i] == 'K') a = 11;
if (msg[i] == 'L') a = 12;
if (msg[i] == 'M') a = 13;
if (msg[i] == 'N') a = 14;
if (msg[i] == 'O') a = 15;
if (msg[i] == 'P') a = 16;
if (msg[i] == 'Q') a = 17;
if (msg[i] == 'R') a = 18;
if (msg[i] == 'S') a = 19;
if (msg[i] == 'T') a = 20;
if (msg[i] == 'U') a = 21;
if (msg[i] == 'V') a = 22;
if (msg[i] == 'W') a = 23;
if (msg[i] == 'X') a = 24;
if (msg[i] == 'Y') a = 25;
if (msg[i] == 'Z') a = 26;
b = a + key_value;
if (b > 26) b -= 26;
if (b == 1) c = 'A';
if (b == 2) c = 'B';
if (b == 3) c = 'C';
if (b == 4) c = 'D';
if (b == 5) c = 'E';
if (b == 6) c = 'F';
if (b == 7) c = 'G';
if (b == 8) c = 'H';
if (b == 9) c = 'I';
if (b == 10) c = 'J';
if (b == 11) c = 'K';
if (b == 12) c = 'L';
if (b == 13) c = 'M';
if (b == 14) c = 'N';
if (b == 15) c = 'O';
if (b == 16) c = 'P';
if (b == 17) c = 'Q';
if (b == 18) c = 'R';
if (b == 19) c = 'S';
if (b == 20) c = 'T';
if (b == 21) c = 'U';
if (b == 22) c = 'V';
if (b == 23) c = 'W';
if (b == 24) c = 'X';
if (b == 25) c = 'Y';
if (b == 26) c = 'Z';
cout << c;
}
So your code works fine: http://ideone.com/lBhD78
If you're trying to accept more than 1 word the simple extraction operator will not work however. Which is probably what you're asking about. In this case you will want to use getline. Like this for instance:
getline(cin, msg, '\n');
So I'm not certain what you're complaining about, however this could be much improved by:
Being case-insensitive
Only modifying alpha-characters
You could accomplish this by doing something like:
transform(cbegin(msg), cend(msg), ostream_iterator<char>(cout), [&](unsigned char i){
if(isalpha(i)) {
const auto a = islower(i) ? 'a' : 'A';
i = (i - a + key_value) % 26 + a;
}
return i; });
I've written a Live Example complete with getline.
You have to be carefull to write questions.
BUT, without being clear what you mean, the answer is:
When you read cin>>s, by default, you are considering the data are separated by "white spaces". So, it skips spaces and read the string until a new space or end of input.
If you have problems with getline, probably the problem is before the code you are shown. If you read a value with, for example, cin>>integer, you push newline key at the end of the input, but this character is still in the stream. If the following line in your code es getline, probably you will read an empty line.
In the first item you find why you current code works, in the second one, why your getline-version doesn't.
I have a string of different 3 letter words:
catdogmattabratliematdogatt
I need to assign each of the words with an alphabet and print the final string.
cat: P, dog: A, mat: T, tab: I, rat: E, lie: O, att: L
so my output should be:
PATIEOTAL
I tried using a switch statement but it doesn't allow me to enter 3 characters together.
Use a map<string, char> to do the following:
map<string, char> wordToChar;
// Load wordToChar appropriately; c++11 you can use an initializer list for simplicity
for (int i = 0; i < strLen; i += 3)
{
string str;
str.push_back(theString[i]);
str.push_back(theString[i+1]);
str.push_back(theString[i+2]);
cout << wordToChar[theString] << endl;
}
It seems I can use three char in a switch-statement! It is also not just me but a standard features called "multicharacter literals" (see 2.14.3 [lex.ccon] paragraph 1; the type of these beasts is int). It isn't that I would advise anybody to use this hack but it works although the characters may need to be reversed in the computation depending on the Endianess of the system (I'm not sure about that detail). Here is a complete example (although the input wants separate words rather than one string which needs to be separated):
#include <iostream>
#include <string.h>
int main(int ac, char* av[])
{
typedef unsigned char u;
for (int i(1); i != ac; ++i) {
if (strlen(av[i]) == 3)
{
std::cout << std::hex;
int value(u(av[i][2])
+ 256u * (u(av[i][1])
+ 256u * u(av[i][0])));
switch (value) {
default:
std::cout << "option not found!: '" << av[i] << "'\n";
break;
case 'cat': std::cout << 'P'; break;
case 'dog': std::cout << 'A'; break;
case 'mat': std::cout << 'T'; break;
case 'tab': std::cout << 'I'; break;
case 'rat': std::cout << 'E'; break;
case 'lie': std::cout << 'O'; break;
case 'att': std::cout << 'L'; break;
}
}
}
std::cout << '\n';
}
Since you asked about using switch statements, I assume that it would be acceptable to have a hard-coded list of 3-letter words and their corresponding letters. In that case, I would solve this problem using a sequence of if-then-else statements, each attempting to match the characters of the 3-letter words. Alternatively, you could use nested switch statements, but the syntax makes that solution a bit harder to read IMO.
static char match_word(std::string const &str, std::size_t offset)
{
char ret = '?';
if (str[offset + 0] == 'c' && str[offset + 1] == 'a' && str[offset + 2] == 't') {
ret = 'P';
}
else if (str[offset + 0] == 'd' && str[offset + 1] == 'o' && str[offset + 2] == 'g') {
ret = 'A';
}
else if (str[offset + 0] == 'm' && str[offset + 1] == 'a' && str[offset + 2] == 't') {
ret = 'T';
}
else if (str[offset + 0] == 't' && str[offset + 1] == 'a' && str[offset + 2] == 'b') {
ret = 'I';
}
else if (str[offset + 0] == 'r' && str[offset + 1] == 'a' && str[offset + 2] == 't') {
ret = 'E';
}
else if (str[offset + 0] == 'l' && str[offset + 1] == 'i' && str[offset + 2] == 'e') {
ret = 'O';
}
else if (str[offset + 0] == 'a' && str[offset + 1] == 't' && str[offset + 2] == 't') {
ret = 'L';
}
return ret;
}
Then you can test the code with a simple main function like this:
int main(int argc, char **argv)
{
if (argc != 2) {
std::cerr << "USAGE: " << argv[0] << " ENCODED" << std::endl;
return 1;
}
else {
std::string example(argv[1]);
for (std::size_t idx = 0; idx < example.size(); idx += 3) {
std::cout << match_word(example, idx);
}
std::cout << std::endl;
return 0;
}
}
Then just run the program with the encoded string as the one and only argument like this:
$ ./a.out catdogmattabratliematdogatt
PATIEOTAL
For a homework assignment: I'm supposed to create randomized alphabetial keys, print them to a file, and then hash each of them into a hash table using the function "goodHash", found in my below code.
When I try to run the below code, it says my "goodHash" "identifier isn't found". What's wrong with my code?
#include <iostream>
#include <vector>
#include <cstdlib>
#include "math.h"
#include <fstream>
#include <time.h>
using namespace std;
// "makeKey" function to create an alphabetical key
// based on 8 randomized numbers 0 - 25.
string makeKey() {
int k;
string key = "";
for (k = 0; k < 8; k++) {
int keyNumber = (rand() % 25);
if (keyNumber == 0)
key.append("A");
if (keyNumber == 1)
key.append("B");
if (keyNumber == 2)
key.append("C");
if (keyNumber == 3)
key.append("D");
if (keyNumber == 4)
key.append("E");
if (keyNumber == 5)
key.append("F");
if (keyNumber == 6)
key.append("G");
if (keyNumber == 7)
key.append("H");
if (keyNumber == 8)
key.append("I");
if (keyNumber == 9)
key.append("J");
if (keyNumber == 10)
key.append("K");
if (keyNumber == 11)
key.append("L");
if (keyNumber == 12)
key.append("M");
if (keyNumber == 13)
key.append("N");
if (keyNumber == 14)
key.append("O");
if (keyNumber == 15)
key.append("P");
if (keyNumber == 16)
key.append("Q");
if (keyNumber == 17)
key.append("R");
if (keyNumber == 18)
key.append("S");
if (keyNumber == 19)
key.append("T");
if (keyNumber == 20)
key.append("U");
if (keyNumber == 21)
key.append("V");
if (keyNumber == 22)
key.append("W");
if (keyNumber == 23)
key.append("X");
if (keyNumber == 24)
key.append("Y");
if (keyNumber == 25)
key.append("Z");
}
return key;
}
// "makeFile" function to produce the desired text file.
// Note this only works as intended if you include the ".txt" extension,
// and that a file of the same name doesn't already exist.
void makeFile(string fileName, int n) {
ofstream ourFile;
ourFile.open(fileName);
int k; // For use in below loop to compare with n.
int l; // For use in the loop inside the below loop.
string keyToPassTogoodHash = "";
for (k = 1; k <= n; k++) {
for (l = 0; l < 8; l++) { // For-loop to write to the file ONE key
ourFile << makeKey()[l];
keyToPassTogoodHash += (makeKey()[l]);
}
ourFile << " " << k << "\n";// Writes two spaces and the data value
goodHash(keyToPassTogoodHash); // I think this has to do with the problem
makeKey(); // Call again to make a new key.
}
}
// Primary function to create our desired file!
void mainFunction(string fileName, int n) {
makeKey();
makeFile(fileName, n);
}
// Hash Table for Part 2
struct Node {
int key;
string value;
Node* next;
};
const int hashTableSize = 10;
Node* hashTable[hashTableSize];
// "goodHash" function for Part 2
void goodHash(string key) {
int x = 0;
int y;
int keyConvertedToNumber = 0;
// For-loop to produce a numeric value based on the alphabetic key,
// which is then hashed into hashTable using the hash function
// declared below the loop (hashFunction).
for (y = 0; y < 8; y++) {
if (key[y] == 'A' || 'B' || 'C')
x = 0;
if (key[y] == 'D' || 'E' || 'F')
x = 1;
if (key[y] == 'G' || 'H' || 'I')
x = 2;
if (key[y] == 'J' || 'K' || 'L')
x = 3;
if (key[y] == 'M' || 'N' || 'O')
x = 4;
if (key[y] == 'P' || 'Q' || 'R')
x = 5;
if (key[y] == 'S' || 'T')
x = 6;
if (key[y] == 'U' || 'V')
x = 7;
if (key[y] == 'W' || 'X')
x = 8;
if (key[y] == 'Y' || 'Z')
x = 9;
keyConvertedToNumber = x + keyConvertedToNumber;
}
int hashFunction = keyConvertedToNumber % hashTableSize;
Node *temp;
temp = new Node;
temp->value = key;
temp->next = hashTable[hashFunction];
hashTable[hashFunction] = temp;
}
// First two lines are for Part 1, to call the functions key to Part 1.
int main() {
srand ( time(NULL) ); // To make sure our randomization works.
mainFunction("sandwich.txt", 5); // To test program
cin.get();
return 0;
}
I realize my code is cumbersome in some sections, but I'm a noob at C++ and don't know much to do it better.
I'm guessing another way I could do it is to AFTER writing the alphabetical keys to the file, read them from the file and hash each key as I do that, but I wouldn't know how to go about coding that.
C++ expected everything to be declared in order, so that nothing's used before it's declared.
If you need to refer to a function higher in the file than where it's defined, you need to have a function prototype near the top of the file that declares the function. (Writing prototypes for all functions is a standard practice as a result of this.)
Near the top of the file (after the #includes) simply add
void goodHash(string key);
Definitions
Function declaration: something that declares the name of the function and the types the function takes.
Function definition: something that specifies the actual code of the function.
if you insert
void goodHash(string key);
in the line under "using namespace..." it will work
The issue is that you have to forward declare goodHash or define goodHash before makeFile if you want to use goodHash in makeFile. Otherwise, when the compile is in makeFile, it sees the token goodHash and hasn't found out what it means, which is why you are getting the compile-time error.
EDIT: Here is a good resource on forward declarations
you forgot the function prototype just add this in the top:
void goodHash(string key);
and btw your makeKey() is too long
you can try this instead:
string makeKey() {
int k;
string key = "";
for (k = 0; k < 8; k++) {
int keyNumber = (rand() % 25);
char app[2];
app[0] = keyNumber + 'A';
app[1] = 0;
key.append(app);
}
return key;
}
Working through more book examples- this one is a partial poker program-
This segment deals with straight hand....
First what was given- only relevant parts....will provide entire code if needed...
int suits[5]; //index 1..4- value start at 1
int values[14]; //index 1..13- value same as rank, A = 1, K = 13
cin.get(rankCh);
switch (toUpper(rankCh)) {
case 'A': values = 1; break;
case '2': values = 2; break;
case '3': values = 3; break;
case '4': values = 4; break;
case '5': values = 5; break;
case '6': values = 6; break;
case '7': values = 7; break;
case '8': values = 8; break;
case '9': values = 9; break;
case 'T': values = 10; break;
case 'J': values = 11; break;
case 'Q': values = 12; break;
case 'K': values = 13; break;
default:
badCard = true;
}
Other functions:
bool isFlush(int suits[]) {
for(i = 1; i <= 4; i++)
if (suits[i] == 5) //5 here is Number of Cards
return true;
return false;
}
Yeah, I know about the array declarations but that is how it is defined- nice justification for it in the text...starting to number at 1
I want my straight hand to handle both Ace high and low- right now as define above aces are low...
Two versions: 1st appears not sure correct with low aces...
CODE
bool isStraight(int values[]) //Version one only straight- low aces only
{
int count = 0;
for (i = 1; i <= 13; i++) {
if (values[i] != 1) {
count++;
} else
count = 0;
if (count == 5) //5 is NUMCARDS
return true;
}
return false;
}
Now this is the where I need some recommendation: to have a function to handle both ace high and low:
bool isStraight(int values[]) //Version handles both high and low
{
int count = 0;
for (i = 1; i <= 13; i++) {
if (values[i] != 1) {
count++;
// if(i == 1 && values[1] != 0) //Check for high and low
// count++;
} else
count = 0;
if (count == 5) //5 is NUMCARDS
return true;
}
return false;
}
Would what I have in comments work to handle both ace high and low...
Since i = 1 is represented as ace and not sure what values[1] is correct should it be values[13] or what...maybe something like
if (i == 1)
values[13] //not sure...
Recommendations-
do not want wholesale changes- just to have minor changes with what I have...I do not want to sort or solve by brute force i.e like values[1] == 1 && values [2] ==1 you get the point- the text does that already but I am trying to rewrite it this way...
Thanks...Hope I am getting across my modification I would like...
EDIT: I figured I'd would first answer your question directly. Lets first clear up how the original algorithm worked. Basically it loops from 1 to 13, and each time it sees a card in that slot, it adds to count. If anything ever breaks the sequence, it resets the counter. Finally, if the counter reaches 5, you have a straight.
I can't say off hand if your solution would work, I say give it a go. However, a simple quick patch to the original would probably go something like this:
//Version handles both high and low
bool isStraight(int values[]) {
int count = 0;
for (i = 1; i <= 13; i++) {
if (values[i] != 1) {
count++;
} else
count = 0;
if (count == 5) //5 is NUMCARDS
return true;
}
// handle ace high.
if(count == 4 && values[1] != 0) {
return true;
}
return false;
}
Basically what that does is say "if we already have 4 in a row, and we've just looked at the very last card (the loop is over), then check an ace is there, if so, we do have a straight and it is ace high".
ORIGINAL ANSWER:
I think the easiest way to handle ace high and low is to have the "get rank" function have two modes, one which returns ace high, the other which returns ace low. Then just calculate the hand value for each case and take the better one.
Also, your get rank could be way simpler :-P.
int get_rank(char card) {
static const char *cards = "A23456789TJQK";
char *p = strchr(cards, toupper(card));
if(p) {
return (p - cards) + 1;
} else {
return -1;
}
}
so if you want to have a get_rank which has an ace_high or an ace_low, you could do this:
int get_rank(char card, bool ace_high) {
static const char *cards_high = "23456789TJQKA";
static const char *cards_low = "A23456789TJQK";
const char *cards = ace_high ? cards_high : cards_low;
char *p = strchr(cards, toupper(card));
if(p) {
return (p - cards) + 1;
} else {
return -1;
}
}
EDIT:
for fun, i've made a quick and dirty program which detects straights (handling both high and low ace). It is fairly simple, but could be shorter (also note that there is no attempt at buffer safety with these arrays, something of production quality should use something safer such as std::vector:
#include <algorithm>
#include <iostream>
#include <cstring>
int get_rank(char card, bool ace_high) {
static const char *cards_high = "23456789TJQKA";
static const char *cards_low = "A23456789TJQK";
const char *cards = ace_high ? cards_high : cards_low;
char *p = strchr(cards, toupper(card));
if(p) {
return (p - cards) + 1;
} else {
return -1;
}
}
bool is_rank_less_low(int card1, int card2) {
return get_rank(card1, false) < get_rank(card2, false);
}
bool is_rank_less_high(int card1, int card2) {
return get_rank(card1, true) < get_rank(card2, true);
}
bool is_straight(int hand[], bool ace_high) {
std::sort(hand, hand + 5, ace_high ? is_rank_less_high : is_rank_less_low);
int rank = get_rank(hand[0], ace_high);
for(int i = 1; i < 5; ++i) {
int new_rank = get_rank(hand[i], ace_high);
if(new_rank != rank + 1) {
return false;
}
rank = new_rank;
}
return true;
}
bool is_straight(int hand[]) {
return is_straight(hand, false) || is_straight(hand, true);
}
int main() {
int hand1[5] = { 'T', 'J', 'Q', 'K', 'A' };
int hand2[5] = { 'A', '2', '3', '4', '5' };
std::cout << is_straight(hand1) << std::endl;
std::cout << is_straight(hand2) << std::endl;
}
The case where an ace-high straight exists can be found by changing the final test:
if (count == 5 || count == 4 && values[1] == 1) // 2nd case handles ace-high straight
return true;
It's a special case, so it must be handled separately.