← 输入框|github.com|刷新
Skip to content

Chapter 4. Bubbles 2.  #27

Open
Open

Description

@Dexter1996777

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;

}

Activity

  1. bethrobson commented on Jan 14, 2024

    @bethrobson
    Owner

    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?

  2. Dexter1996777 commented on Jan 14, 2024

    @Dexter1996777
    Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions