-2

Well, I have to make a task, that will sort elements of array in UNIQUE way.

So, for example, if I input 1st string: BOB, I have to do: 2+15+2 (because of their positioning in the alphabet) and then divide by amount of chars /3 and do that for all inputted strings and then sort them by highest to lowest. :)

My question is, how do I set value 1,2,3,4,5... for A,B,C,D,E..... (only big letters).

Thank you.

John Smith
  • 47
  • 1
  • 3
  • 9

4 Answers4

2

If the underlying encoding is seuqential, such as ascii.

letter - 'A' + 1

A more robust and general approach, would be to examine the char_traits of the character type.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2

You need to define a function

int weight(const std::string& s);

And then iterate on the string char by char and do following:

w = ch - 'A' + 1

You also may check that the char is before 'A' and 'Z' or assume that.

You need to read more about ASCII

EDIT: Code of weight function (simplified):

int weight(const std::string& s) {
    int sum = 0, i = 0;
    for(i = 0; i < s.size(); i++) {
        char ch = s[i];
        sum += ch - 'A' + 1;
    }
    return sum/i;
}
SlavaNov
  • 2,447
  • 1
  • 18
  • 26
1

If you are working on an ASCII machine, @StoryTeller's answer works. Otherwise you can create an array to map between the two:

const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const int numbers [ 256 ] = { 0 };

for ( size_t index = 0; index < sizeof letters; ++index ) {
    numbers [ letters [ index ] ] = index + 1;
}

assert ( numbers [ 'A' ] == 1 )
assert ( numbers [ 'Z' ] == 26 )
Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
  • What is an ASCII machine? – John Smith Feb 28 '13 at 14:54
  • @JohnSmith a machine which uses ASCII for character representation, which is most machines now-a-days. Some mainframes used EBCDIC http://en.wikipedia.org/wiki/EBCDIC which has gaps, for example between I and J, so `'J' - 'I' != 1` – Pete Kirkham Feb 28 '13 at 15:15
0

To get the values you could use the following code:

int getValue(char which)
    {
    int ret = 0;
    switch(which)
       {
       case 'a' : ret = 1 ; break;
       case 'A' : ret = 27 ; break;
       case 'b' : ret = 2 ; break;
       case 'B' : ret = 28 ; break;
       // and so on....
       }
    return ret;
    }
  int result = 0;
  while(....)
     {
     result = result + getValue(myarray[counter]);
     }

You only need to escape the string to array and loop through it...

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • He asked only for big letters and you don't need to use such table, you may just using it's ASCII value (see answers below) – SlavaNov Feb 28 '13 at 14:38
  • That's true... I don't need small chars, only big. And I was gonna use ASCII method except I wasn't sure how to do it. – John Smith Feb 28 '13 at 14:40