Isabella Chen Isabella Chen - 5 days ago 5
Javascript Question

Comparison operator not returning correct value

Given two strings, each representing a member of the sides of good or evil, find out which side will win.

Good: Hobbits - 1, Men - 2, Elves - 3, Dwarves - 3, Eagles - 4, Wizards - 10

Evil: Orcs - 1, Men - 2, Wargs - 2, Goblins - 2, Uruk Hai - 3, Trolls - 5, Wizards - 10

I have written a function to figure out which side will win. It works most of the time, but sometimes it behaves weird.

function goodVsEvil(good, evil){
//string to array good and array evil in integers
var aG = good.split(" ").map(x=>parseInt(x))
var aE = evil.split(" ").map(x=>parseInt(x))

//calculate final score good and final score evil
var fSG = aG[0]*1 + aG[1]*2 + aG[2]*3 + aG[3]*3 + aG[4]*4 + aG[5]*10
var fSE = aE[0]*1 + aE[1]*2 + aE[2]*2 + aE[3]*2 + aE[4]*3 + aE[5]*5 + aE[5]*10

console.log('equals: '+ (fSG == fSE))
console.log('good > evil: '+(fSG > fSE))
console.log('good < evil: '+(fSG < fSE))
}


Some error cases:

var result = goodVsEvil('1 0 0 0 1 0', '0 0 0 0 0 1 0')
//output
good: 5
evil: 5
equals: false
good > evil: false
good < evil: true


another:

good: 10
evil: 10
equals: false
good > evil: false
good < evil: true


another:

good: 2
evil: 2
equals: false
good > evil: true
good < evil: false


Here, it's working fine

var result = goodVsEvil('1 1 0 0 0 0', '0 0 0 0 1 0 0')
good: 3
evil: 3
equals: true
good > evil: false
good < evil: false


This puzzle is from codewars: https://www.codewars.com/kata/good-vs-evil/train/javascript

Answer

If you log fSG and fSE, you will notice that fSE in fact equals 15 in your first example, not 5.

That is because you have a typo in the line that calculates the value. You are using aE[5] twice instead of aE[6]:

var fSE = aE[0]*1 + aE[1]*2 + aE[2]*2 + aE[3]*2 + aE[4]*3 + aE[5]*5 + aE[5]*10

This should be

var fSE = aE[0]*1 + aE[1]*2 + aE[2]*2 + aE[3]*2 + aE[4]*3 + aE[5]*5 + aE[6]*10

As a side note, please try to find more comprehensive names for your variables. Scrambled three letter combinations make it really hard to understand the intentions behind the values! :-)