Skip to content

Chapter 4. Bubbles 2. #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Dexter1996777 opened this issue Jan 13, 2024 · 2 comments
Open

Chapter 4. Bubbles 2. #27

Dexter1996777 opened this issue Jan 13, 2024 · 2 comments

Comments

@Dexter1996777
Copy link

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;

}

@bethrobson
Copy link
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?

@Dexter1996777
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants