Reputation: 21
I'm designing a quiz motivator, i.e. if a user inputs any number of correct answers he's gonna get rewarded with a "star" or smth. The array in a pseudo code below represents a range of correct answers to choose from:
var rightAnswers = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
if (rightAnswers.chooseAny(3)) {user gets a star}
else if (rightAnswers.chooseAny(6)) {user gets 2 stars}
else if (rightAnswers.chooseAny(9) {user gets 3 stars}
I haven't found anything that would work instead of my pseudo "chooseAny()", any ideas, please?
Upvotes: 0
Views: 51
Reputation: 16779
You probably aren't looking for a chooseAny
function; I think what you're really asking for is a way to count how many answers were correct given a set of answers
and an answerKey
.
The getTotalCorrect
function below does that for you using a for-loop and identity comparison, and you can use getStars
to determine how many stars should be awarded based on the score that is returned.
var answerKey = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
function getTotalCorrect (answers, answerKey) {
for (var correct = 0, i = 0; i < answerKey.length; i++) {
if (answers[i] === answerKey[i]) correct++
}
return correct
}
function getStars (totalCorrect) {
return (totalCorrect / 3) | 0
}
var totalCorrect = getTotalCorrect(['a', 'a', 'c', 'c', 'e', 'e', 'e'], answerKey)
console.log(totalCorrect) //=> 3
var stars = getStars(totalCorrect)
console.log(stars) //=> 1
Upvotes: 1