Home > Software design >  How do I make a clean if statement with multiple clauses?
How do I make a clean if statement with multiple clauses?

Time:10-25

I am tasked to create a little scrabble game and one of my "micro" tasks is computing the score of a given word based on a chart with letter associated with points:

Points Letters

1: a, e, i, l, n, o, r, s, t, u

2: d, g

3: b, c, m, p

4: f, h, v, w, y

5: k

8: j, x

10: q, z

Anyways, My first thought was just looping through the given word and checking each letter with an if loop.

for(auto ch: word){
  // as an example this if loop would check if the letter the for loop is on is an 'a' or 'e' or .... 
  // and then adds 1 point to integer 'score' as defined by the bale above
  if(ch == a || ch == e || ch == i || ch == l){
    score = score   1;
  }
}

So my question is, is there a cleaner way of making that if loop? something like: if(ch == a,e,i,l...) something like that? For my task I am only allowed to use c 17 but I am fairly new to c and am not aware of its fullest potential. Hopefully one of you can tell me what is possible. Thank you

CodePudding user response:

Write a function to compute the value, and implement it with a switch statement:

Int score(char ch) {
    switch(ch) {
        case ‘a’:
        case ‘e’:
        case ‘i’:
        // etc.
            return 1;
        case ‘d’:
        case ‘g’:
            return 2;
    // and so on …
    }
}

The compiler will generate efficient code for this. It will work correctly for any character encoding and is easily extended for richer character sets. It will use far less memory than an unordered_map and will almost certainly be faster.

CodePudding user response:

Since you have all the characters in the alphabet, you can have an array of the char values, using the character as the offset: (note in this case the mapping is A->J are 1 point, K and L are 2 points etc. You'll have to tweak the mapping for your points.)

int point_mapping[] =
{
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2, 2,
  3, 3, 3, 3,
  4, 4, 4, 4, 4,
  5,
  8, 8,
  10, 10
};

for (auto& ch : word)
{
    score  = point_mapping[tolower(ch) - 'a'];
}
  • Related