Not falling in the if according to the number being higher or lower

Asked

Viewed 50 times

-3

The program I want to create should return an array with the number of records reached from a list of scores and the number of the position of the lowest score, respectively. However, it returns something different.

let stringPontuacoes = "10, 20, 4, 8, 9, 22, 12, 43, 22"


function avaliaPontuacoes (stringPontuacoes) {
    let pontuacoes = stringPontuacoes.split(", ")
    let qtdQuebraDeRecords = 0
    let piorJogo = 1
    let maiorPontuacao = pontuacoes[0]
    let menorPontuacao = pontuacoes[0]

    for (let i = 1; i < pontuacoes.length; i++) {
        if(pontuacoes[i] > maiorPontuacao) {
            maiorPontuacao = pontuacoes[i]
            qtdQuebraDeRecords++ 
        }else if (pontuacoes[i] < menorPontuacao) {
            menorPontuacao = pontuacoes[i]
            piorJogo = i+1;
        }
    }
    return [qtdQuebraDeRecords, piorJogo]
}

console.log(avaliaPontuacoes(stringPontuacoes))

The code returns "[ 4, 1 ]", instead of "[ 3, 3 ]". I would really like your help in figuring out how to solve this problem.

1 answer

0


You’re saving text instead of number, then you do math operations and comparisons with that information which goes wrong, so you have to convert to number before you do this. A lot of things could go wrong, but it seems you have control over the format so I won’t make further checks.

function avaliaPontuacoes (stringPontuacoes) {
    let pontuacoes = stringPontuacoes.split(", ");
    let qtdQuebraDeRecords = 0;
    let piorJogo = 1;
    let maiorPontuacao = pontuacoes[0];
    let menorPontuacao = pontuacoes[0];
    for (let i = 1; i < pontuacoes.length; i++) {
        let pontuacao = parseInt(pontuacoes[i]);
        if (pontuacao > maiorPontuacao) {
            maiorPontuacao = pontuacao;
            qtdQuebraDeRecords++;
        } else if (pontuacao < menorPontuacao) {
            menorPontuacao = pontuacao;
            piorJogo = i + 1;
        }
    }
    return [qtdQuebraDeRecords, piorJogo];
}

console.log(avaliaPontuacoes("10, 20, 4, 8, 9, 22, 12, 43, 22"));

I put in the Github for future reference.

Browser other questions tagged

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