开发者

How to determine order of a sequence of chars (No arrays!) in C

开发者 https://www.devze.com 2023-04-12 03:46 出处:网络
This is what I\'m up to so far char max = 0, here; while(scanf(\"%c\", &here) == 1 && here != \'\\n\')

This is what I'm up to so far

char max = 0, here;
while(scanf("%c", &here) == 1 && here != '\n')
    if(here > max)
        max = here;
printf("max='%c'\n", max);

The user could enter a sequence of characters, and I'd get back 开发者_StackOverflow社区the letter with the highest ASCII value. In Computer Fun, this would be u. But if CompUter Fun were the input, I'd want to get U back because it has been entered first in the sequence.

I could have two variables saving the highest capital letter and the highest simple letter, but how would I then know which came first?

Thanks in advance. Explaining the logic is just fine, if you don't want to write out the code fragment that does this.


You only need one variable—just keep track of the character that wins up to this point.

As you scan over the input CompUter Fun, you first see C. Since its the first character, its the winner so far. Then you see o. o comes after C, so its now the winner; your variable now contains o. And so on. You only replace the stored character if the new one wins, so you'll get the first one in case of ties.

(When comparing, you need to do a case-insensitive compare; an easy way to do this is tolower on both sides of the compare).

input  winner
C      C       # first letter always wins
o      o       # o > c
m      o       
p      p       # p > o
U      U       # U > o
t      U
e      U
r      U
       U       # space
F      U
u      U       # u == U, so !(u > U), so U stays winner
n      U

gives the ultimate winner, U.

This is an efficient general algorithm for finding the maximum (or minimum, by reversing the compare) of an unordered input. It can also be extended to keep track of 2nd (etc.) place, though at some point sorting becomes more efficient, especially on data like this where you can use radix O(n) sorts.


You could just use one variable like you have, but instead of just checking if here > max, it could check if the new value is a lower case or uppercase version of the letter currently in max. This way you wont overwrite the current max if a new letter of equal value comes along.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号