1

I'm trying to create a function that compare 2 arrays and decide a winner who won more rounds. Each item of the array represents the points each player made in their respective rounds. So the winner of the round is who made more points.

for example:

player1= [4,5,7,8] player2= [5,3,2,1]

the result should be player1 because he won more rounds (5>3, 7>2 8>1).

function solution(result1,result2) {

   let player1 = 0
   let player2 = 0

   for(let i=0; i<result1.length; i++){
      if (result1[i] > result2[i]){
         player1++
      }else if(result2[i]>result1[i]){
         player2++
      
      }else(result1[i] == result[i]);{
         player1++
         player2++

      }if (player1 > player2){
         console.log("PLAYER1")
      }else if(player1 == player2){
         console.log("TIE")
      }else {
         console.log("PLAYER2")
      }
   }
}```
  • Please see [ask], then revise your post title to ask a clear, specific question about your _code_ rather than stating your requirements. – isherwood Feb 23 '23 at 19:26
  • Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Feb 23 '23 at 19:26
  • 1
    At a glance... What do you think `else(result1[i] == result[i]);` does and why? – David Feb 23 '23 at 19:29

1 Answers1

-1
  • Check the number of wins after the loop, when all the counts have been set correctly.
  • Also, there is no need to update any values in the case of a tie.
function solution(result1, result2) {
    let player1 = 0
    let player2 = 0
    for (let i = 0; i < result1.length; i++) {
        if (result1[i] > result2[i]) {
            player1++
        } else if (result2[i] > result1[i]) {
            player2++
        }
    }
    if (player1 > player2) {
        console.log("PLAYER1")
    } else if (player1 == player2) {
        console.log("TIE")
    } else {
        console.log("PLAYER2")
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80