To sort an array with tiebreaker criteria if one of the fields is equal

Asked

Viewed 61 times

0

Since I only compare the number of goals of the first placed if they have the same number of points, there is a way to do this by comparing items in different arrays?

I looked at the exercise response and after the else he put: My doubt is that as he is inside an IF he every round* will add the number of goals with the number of points, I do not see the logic of adding the two to define the first placed, a team can lose from 7x6 and make 6 points and a team win from 1x0 and make 4 points.

timesRj[anfitriao][3] = (timesRj[anfitriao][1] + timesRj[anfitriao][2]);
timesRj[convidado][3]= (timesRj[convidado][1]) + timesRj[convidado][2];           

//ordem por número de pontos
timesRj.sort((a,b) => a[3] - b[3]);



<!DOCTYPE html>
<html lang="pt-br">
<head>

    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Curso Javascript</title>

    <script type="text/javascript" src="js/main.js"></script>

</head>
<body>

    <h1>Javascript Start</h1>

    
    <script>


//Times para o campeonato

let timesRj = [["Flamengo",0,0],["Fluminense",0,0],["Botafogo",0,0],["Vasco",0,0], ["America", 0,0]];


//Campeonato Carioca

//total de times

let totalTimesRj = timesRj.length;

for(let anfitriao = 0; anfitriao < totalTimesRj; anfitriao++){
    for(let convidado = 0; convidado < totalTimesRj; convidado++){

        if(anfitriao !== convidado){

            let limiteGols = Math.round(Math.random()* 8);
            let golsAnfitriao = Math.round(Math.random() * limiteGols);
            let golsConvidado = Math.round(Math.random() * limiteGols);
            timesRj[anfitriao][2] += golsAnfitriao;
            timesRj[convidado][2] += golsConvidado;

            let time1 = `${timesRj[anfitriao][0]}`;
            let time2 = `${timesRj[convidado][0]}`;

            console.log(`Jogo: ${time1} ${golsAnfitriao} X ${time2} ${golsConvidado}`);

            //Atribui pontuação para os times

            if(golsAnfitriao > golsConvidado){
                timesRj[anfitriao][1] += 3;

            }
            else if(golsConvidado > golsAnfitriao){
                timesRj[convidado][1] += 3;

            }
            else{
                timesRj[anfitriao][1] +=1;
                timesRj[convidado][1] +=1;
            }
            }
            }
            }

           let campeaoNome =  `${timesRj[totalTimesRj -1][0]}`;
        //ordem por número de pontos
        timesRj.sort((a,b) => a[1] - b[1]);
        alert(timesRj[totalTimesRj - 1] [0]);

        if(timesRj[totalTimesRj - 1][1] == timesRj[totalTimesRj - 2][1] && timesRj[totalTimesRj - 1][2] < timesRj[totalTimesRj - 2][2]){
            campeaoNome =  `${timesRj[totalTimesRj -2][0]}`;
        }
        else{
            campeaoNome =  `${timesRj[totalTimesRj -1][0]}`;
        }


        //Exibe a tabela do campeonato

        alert(`${campeaoNome}`);

        //Exibe o campeão



        let campeaoPontos = `${timesRj[totalTimesRj - 1] [1]}`;
        let gols = `${timesRj[totalTimesRj - 1] [2]}`;
        
        console.log(`O campeão foi o ${campeaoNome} com ${campeaoPontos} pontos e ${gols} gols.`);

        alert(timesRj);
       


    </script>
    
</body>
</html>

1 answer

0

In fact this logic of adding the goals to the points is stuck. It can even work in many cases (since in thesis a team that won more games, usually scored more goals than the others), but we know that this is not always the case.

It is possible, for example, that team A lost a game without scoring goals, and won 4 shutouts (therefore, made 12 points and say about 20 goals), while team B won 5 games of 1 x 0 (thus making 15 points and 5 goals). If you use this logic of scoring goals with points, team A will be considered champion, but if the criteria is who scored the most points, and the goals are only for tiebreakers, then team B should be the champion.

So the right way to do it would be:

  • forget this logic of adding goals with points, so you don’t need these lines:

    timesRj[anfitriao][3] = (timesRj[anfitriao][1] + timesRj[anfitriao][2]);
    timesRj[convidado][3] = (timesRj[convidado][1]) + timesRj[convidado][2];
    
  • the sorting function has to implement the correct rule:

    function comparaPontosGols(a, b) {
        // primeiro compara pontos
        let cmp = a[1] - b[1];
        if (cmp == 0) { // somente se pontuação é igual, compara gols
            cmp = a[2] - b[2];
        }
        return cmp;
    }
    
    // ordena segundo o critério acima
    timesRj.sort(comparaPontosGols);
    // Exibe o campeão (usar destructuring assignment para obter os dados)
    let [ campeaoNome, campeaoPontos, campeaoGols ] = timesRj[timesRj.length - 1];
    console.log(`O campeão foi o ${campeaoNome} com ${campeaoPontos} pontos e ${campeaoGols} gols.`);
    

That is, I only compare the goals if the score is equal.

And since the team is represented by an array with 3 elements, I can use the destructuring assingment to get the values directly, one in each variable.

Browser other questions tagged

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