Number of repetitions per character

Asked

Viewed 145 times

8

A friend passed me the following exercise:

Create a function frequencyLetra(text) that returns an object containing the amount of occurrences of each character present in the text.

I started from the assumption that the argument passed is a string. According to my logic I created two structures of for and the innermost has a if to check if the letter exists in the past text. However for more internal it does not return to the external, and terminates the logic in the first iteration.

Follow the code so you can see what I’m doing:

function letterFrequence(text) {
    var repeticao;
    var listaComRepeticoes = [];
    var text = text.split("");

    for (var i = 0; i < text.length; i++) {
        repeticao = 0 ;
        var caractere = text[i];
        console.log("test");
        listaComRepeticoes.push(caractere);

        for (var i = 0; i < text.length; i++) {
            console.log("teste2");
            if (caractere === text[i]) {
                repeticao = repeticao + 1;
            } else {

            }
        };
        listaComRepeticoes.push(repeticao);
    };
    return listaComRepeticoes ;
}

var repeticoes =  letterFrequence("David Bastos");
console.log(repeticoes);

Console Output:

test
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
[ 'D', 1 ]
[Finished in 0.1s]

Note that the for the innermost wheel of the 12 interactions of the text.lenght, but not the most external! What could I be doing wrong?

2 answers

8


To carlospheric response solves the problem, but has an easier way to count: instead of the array, use an object as dictionary, with each character as key and the corresponding amount as value. For example:

function letterFrequence(text) {
    var frequencias = {}
    for(var i=0; i<text.length; i++) {
        // se já temos esse caractere no dicionário, 
        // incrementa a quantidade  
        if(frequencias[text[i]]) {
            frequencias[text[i]]++;   

        // se ainda não temos, inicializa como 1
        } else {
            frequencias[text[i]] = 1;
        }
    }
    return frequencias;
}

http://jsfiddle.net/hqot1fke/

Output example for letterFrequence("David Bastos"):

inserir a descrição da imagem aqui


Note: Older Javascript implementations do not accept picking characters from a string using subscript (ie, brackets). For greater compatibility, it is better to use text.charAt(i) instead of text[i].

  • Which is basically what the PHP.JS people did XD

  • Their version is a little more complex, and the output is in another format. I prefer simplicity...

  • 1

    It is that they insist on porting PHP pro JS as much as possible, so you have to follow the letter, with all available modes and etc. I think it’s silly. I don’t think I’ve ever used this function even in PHP. :p

5

In your function you "declared" the variable i twice: once in the for external, and a for internal. However, for Javascript, the variable is declared only once. What happens is that at the end of the internal loop the variable i will have the value of text.length, what satisfies the stop condition of the external loop.

Note that this is typical Javascript behavior (scope of the variable linked to the function); in other languages (C, C++, C#, Java IIRC, etc.) the scope of the variable is linked to the block in which she was declared.

If you switch to using another variable in the internal loop (as in the example below) you will see the external loop running multiple times.

    for (var j = 0; j < text.length; j++) {
        console.log("teste2");
        if (caractere === text[j]) {
            repeticao = repeticao + 1;
        } else {
        }
    };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.