In C, you can only put scalar constants in one switch
. A string is a pointer type variable, so we will have difficulties using exactly this method.
At Stackoverflow in English, who replied suggested that a function of hash
to use the switch
with the string; or else use what they called "ladder" if-else
.
Wikipedia has a input explaining hash functions. A function of hash
for a generic string can be defined like this (I will not do null-safe
):
int hash_function(char *str) {
int acc = 0;
int peso = 1;
int base = 256;
int len = strlen(str);
int modulus = 65000;
int i;
for (i = 0; i < len; i++) {
int char_at = str[i]; /* char é um número de 8 bits, enquanto que int é um número de 16 ou 32 bits, dependendo do compilador */
acc = (acc*base + peso*char_at) % modulus;
peso = (peso % 10) + 1; /* peso varia de 1 a 10 */
}
return acc;
}
Having the function of hash
predetermined, we already know what can be the value of "School" and creating the macro HASH_ESCOLA
:
int tratar_escola(char *lugar) {
int hash_lugar = hash_function(lugar);
switch (hash_lugar) {
case HASH_ESCOLA:
/* vamos checar se deu positivo verdadeiro? */
if (strcmp(lugar, "Escola") == 0) {
printf("Estudar\n");
return 1;
}
}
return 0;
}
An algorithm of hash
/dispersion algorithm can generate collisions (wikipedia article), which in this case is another object that returns the same value as your desired object. To prevent it from colliding with a value other than Escola
, i do the comparison with the original string.
This is not possible, we can do with
if
or a much more complex solution (hash for example). Actually the code has other problems, it is even allowing to type the word.– Maniero
So, with if I can do this ? I want to know how, as it is even really allowing you to type the word.
– Mondial
Mondial, did you notice that you are reading only one character? You are not reading a string. Use
scanf("%s", lugar)
to read a string.– Jefferson Quesado
Thank you Jefferson for the clarification, I was wrong in some exercises simply because of this mistake, well, I have corrected here and I will remember in the future about this.
– Mondial