Head-First-JavaScript-Programming icon indicating copy to clipboard operation
Head-First-JavaScript-Programming copied to clipboard

Chapter 4. Bubbles 2.

Open Dexter1996777 opened this issue 2 years ago • 2 comments

Hello everyone! I've got a question about the final version of the code in Chapter 4 (root: Chapter 4 -> bubbles2.html). The function getMostCostEffectiveSolution(scores, costs, highScore) is meant to choose the lower price for the highest scores that repeat twice. The best costs turned out to be .22 and .25. As a result of invoking the built-in return function, we get .22, but how does the function understand that we need a lower price, though we didn't mention any condition for that?

function getMostCostEffectiveSolution(scores, costs, highScore) { var cost = 100; // much higher than any of the costs var index;

for (var i = 0; i < scores.length; i++) {
	if (scores[i] == highScore) {
		if (cost > costs[i]) {
			index = i;
			cost = costs[i];
		}
	}
}
return index;

}

Dexter1996777 avatar Jan 13 '24 22:01 Dexter1996777

Notice that we define index to be undefined at the top of the function. Then we loop through all the scores. If a given score is a high score, then we check to see if cost is greater than costs[i] (i.e. the cost of the solution with one of the high scores). Let's say i = 23, cost[23] = .22. Is cost > .22? Yes! So set index to 23 and set cost to .22. Continue looping. Now let's say we find another score with the high score at i = 26, and cost[26] = .25. So does cost > cost[26]? no, because cost is .22 and cost[26] is .25. So we do NOT change cost and we do NOT change index. Continue looping until we're done. Then return index. That's the index of the most cost effective bubble solution because it has the high score and also the lowest cost.

Does that help?

bethrobson avatar Jan 14 '24 00:01 bethrobson

@bethrobson Dear Bethrobson, thank you ver much for the detailed explanation! Have a nice day! Now, everything is clear to me!

Dexter1996777 avatar Jan 14 '24 12:01 Dexter1996777