Comparing two arrays with nested for loops

edmamerto

Problem: Given two arrays x and y, x being Alice's score, and y being Bob's score. Compare similar indices between Alice and Bob and give 1 point to whomever is greater than for every compared indices (no point if Equal).

INPUT:

x = [4,1,6]
y = [1,1,5]

EXPECTED OUTPUT:

{Alice:2, Bob: 0}

MY CODE:

x = [4,1,6]
y = [1,1,5]

results = {'Alice':0, 'Bob': 0}

for (var i = 0; i < x.length; i++){
  for (var j = 0; j < y.length; j++){
    if (x[i] > y[j]){
      results['Alice'] += 1
    }else if (x[i] < y[j]){
      results['Bob'] += 1
    }
  }
}

console.log(results)

ACTUAL OUTPUT:

{Alice: 5, Bob: 2}

QUESTION:

Where did I go wrong in my code?

JLRishe

The problem is that you shouldn't use a nested loop. What you are doing here is comparing all of Alice's results against all of Bob's, in this order:

  • Alice[0] vs. Bob[0] - 1 point to Alice
  • Alice[0] vs. Bob[1] - 1 point to Alice
  • Alice[0] vs. Bob[2] - 1 point to Bob
  • Alice[1] vs. Bob[0] - Tie
  • Alice[1] vs. Bob[1] - Tie
  • Alice[1] vs. Bob[2] - 1 point to Bob
  • Alice[2] vs. Bob[0] - 1 point to Alice
  • Alice[2] vs. Bob[1] - 1 point to Alice
  • Alice[2] vs. Bob[2] - 1 point to Alice

To fix this, get rid of the inner loop and j, and just use i.

var x = [4, 1, 6]
var y = [1, 1, 5]

var results = {
  'Alice': 0,
  'Bob': 0
}

for (var i = 0; i < x.length; i++) {
  if (x[i] > y[i]) {
    results['Alice'] += 1
  } else if (x[i] < y[i]) {
    results['Bob'] += 1
  }
}

console.log(results)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related