Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting unique words in strings

Below I am trying to give string arrays to a function that adds unique words to a words array, and if the word is already in the array to increase the count of the corresponding element in the count array:

var words = [];
var counts = [];

calculate([a, b]);
calculate([a, c]);

function calculate(result) {
    for (var i = 0; i < result.length; i++) {
        var check = 0;
        for (var j = 0; i < tags.length; i++) {
            if (result[i] == tags[j]) {
                check = 1;
                counts[i] = counts[i] + 20;
            }
        }
        if (check == 0) {
            tags.push(result[i]);
            counts.push(20);
        }
        check = 0;
    }
}

However the output turns out like this:

words = a, b count = 2, 1

When I expect it to be: words = a,b,c count = 2,1,1

Thanks for any help in advance

like image 717
Grace O'Brien Avatar asked Dec 12 '25 01:12

Grace O'Brien


2 Answers

Breaking the problem down into methods with good names helps you to work out your logic.

Try this:

<script type="text/javascript">
var words = [];
var counts = [];
calculate(["a", "b"]);
calculate(["a", "c"]);
console.log(words);
console.log(counts);

function calculate(result) {
    for (var i=0; i<result.length; i++) {
        if (array_contains(words, result[i])) {
            counts[result[i]]++;
        } else {
            words.push(result[i]);
            counts[result[i]] = 1;
        }
    }
}

function array_contains(array, value) {
    for (var i=0; i<array.length; i++)
        if (array[i] == value)
            return true;
    return false;
}

</script>

Output:

["a", "b", "c"]
[]
a 2
b 1
c 1

like image 107
Ozzy Avatar answered Dec 13 '25 14:12

Ozzy


Please check this : you can test it on : http://jsfiddle.net/knqz6ftw/

var words = [];
var counts = [];

calculate(['a', 'b']);
calculate(['a', 'c']);
calculate(['a', 'b', 'c']);

function calculate(inputs) {
    for (var i = 0; i < inputs.length; i++) {
    var isExist = false;
    for (var j = 0; j < words.length; j++) {
        if (inputs[i] == words[j]) {
            isExist = true
            counts[i] = counts[i] + 1;
        }
    }
    if (!isExist) {
        words.push(inputs[i]);
        counts.push(1);
    }
    isExist = false;
}
}

console.log(words);
console.log(counts);

Output is :

["a", "b", "c"] (index):46
[3, 2, 2] 
like image 41
krishna Prasad Avatar answered Dec 13 '25 14:12

krishna Prasad