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?
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:
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.
Comments