Number of repetitions per character

8

A friend gave me the following exercise:

  

Create a text-frequency function that returns an object containing the number of occurrences of each character in the text.

I assumed that the argument passed is a string. According to my logic I have created two structures of for and the inner one has a if to check if there is the letter in the last text. However, when the inner% wrap is finished, it does not return to the outer wrapper, and ends 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 Exit:

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

Notice that the% innermost% with% of the% of the% of the% of the innermost interacts, but the outermost does not! What could I be doing wrong?

    
asked by anonymous 09.09.2014 / 17:57

2 answers

8

The carlosfigueira's answer solves the problem, but there is an easier way to do the counting: instead of the array, use an object as a dictionary, with each character as a key and the corresponding quantity 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;
}

link

Output example for letterFrequence("David Bastos") :

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

    
09.09.2014 / 18:37
5

In your role you have "declared" the variable i twice: one in the for external, and one in the for internal. However, for JavaScript, the variable is declared only once. What happens is that at the end of the inner loop the variable i will have the value of text.length , which satisfies the outer loop stop condition.

Note that this is a typical JavaScript behavior (function-bound variable scope); in other languages (C, C ++, C #, Java IIRC, etc.) the scope of the variable is bound to the block where it was declared.

If you change to another variable in the internal loop (as in the example below) you will see the external loop being executed multiple times.

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