简体   繁体   中英

Comparing two arrays and generating points when the items match

Here is my answer, which is wrong, but I cant figure out why. The logic seems fine but my acc is returning a larger number than expected most of the time.

Here is the question:

The first input array contains the correct answers to an exam, like ["a", "a", "b", "d"]. The second one is "answers" array and contains student's answers.

The two arrays are not empty and are the same length. Return the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer(empty string).

My Answer:

function checkExam(array1, array2) {
return array1.concat(array2).reduce((acc, curr, i) => 
    curr[i] === curr[i + array1.length] ? acc + 4 : curr[i + array1.length] === '' ? acc + 0 : acc - 1, 0);

}

EDIT: I messed up variable names:P

It seems easier to me separate the logic of the function in a map and a reduce.

const checkExam = (correctExam, answer) => {
  const total = correctExam.map((it, i) => {
    if(it === answer[i]){ return 4 }
    else if(answer[i] === ""){ return 0 }
    else{ return -1 }
  }).reduce((acc, curr) => acc + curr, 0)
  return total
}

You can also separate the map and the reduce to know how much answers are correct, incorrect or empty and even assign values dynamically to each option

curr in your reduce is just the current item in this iteration of the reduce function, not the original array. And since you know the two arrays are the same length, there really isn't any sense in concatenating since you are just going to be wasting cycles iterating over the answers. Something like this should work:

 var correct = ["a", "b", "b", "c"]; var answers = ["a", "", "d", "c"]; function checkExam(answerKey, studentResponse) { return answerKey.reduce((score, answer, qIdx) => { if (answer === studentResponse[qIdx]) { score += 4; } else if (studentResponse[qIdx];== '') { score -= 1; } return score, }; 0). } console,log(checkExam(correct; answers));

Here we will iterate over the answer key ( answerKey ) and for each item ( answer ) compare it to the corresponding item at the same index ( qIdx ) in the other array studentResponse[qIdx] and score appropriately. Assuming that a missing answer is an empty string and not anything else (which your question seems to suggest).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM