0

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?

8
  • What's the expected output from .chooseAny(N)? Commented Mar 7, 2017 at 3:31
  • Where's the user input? Commented Mar 7, 2017 at 3:32
  • the name chooseAny is cryptic , explain further on your idea ? Commented Mar 7, 2017 at 3:35
  • Expected output is just a ranking - if any 3 answers of 15 in total are correct user gets 1 badge, if 6 are correct - 2 badges and so on. Each input is done through the inputField.value and matched with individual array of correct answers for each question Commented Mar 7, 2017 at 3:37
  • name chooseAny is not a part of the code it's just an idea of how i want it Commented Mar 7, 2017 at 3:38

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that i guess i can make sense of!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.