DEV Community

Discussion on: Check the Examination

Collapse
 
fidr profile image
Robin

Nice code. I actually think walking the lists in parallel is a nice solution in elixir, although it might be harder to read at first glance:

defmodule CheckExam do
  def check_exam(correct, answer, score \\ 0)
  def check_exam([a | correct], [a | answer], score), do: check_exam(correct, answer, score + 4)
  def check_exam([a | correct], ["" | answer], score), do: check_exam(correct, answer, score)
  def check_exam([a | correct], [b | answer], score), do: check_exam(correct, answer, score - 1)
  def check_exam([], [], score) when score < 0, do: 0
  def check_exam([], [], score), do: score
end

CheckExam.check_exam(["a", "a", "b", "b"], ["a", "c", "b", "d"])
CheckExam.check_exam(["a", "a", "c", "b"], ["a", "a", "b",  ""])
CheckExam.check_exam(["a", "a", "b", "c"], ["a", "a", "b", "c"])
CheckExam.check_exam(["b", "c", "b", "a"], ["",  "a", "a", "c"])
Collapse
 
gsarwate profile image
Ganesh Sarwate

Thanks! Your solution also works well here. To improve readability, parameters to check_exam/3 could be named explicitly e.g. right instead of a and wrong instead of b. Also unused parameters should be marked with _.

Something like

  def check_exam([right | correct], [right | answer], score), do: check_exam(correct, answer, score + 4)
  def check_exam([_right | correct], ["" | answer], score), do: check_exam(correct, answer, score)
  def check_exam([_right | correct], [_wrong| answer], score), do: check_exam(correct, answer, score - 1)
Collapse
 
adolfont profile image
Adolfo Neto • Edited

Thanks to both of you. The combination of your solution looks great!

defmodule CheckExam do
  def check_exam(correct, answer, score \\ 0)
  def check_exam([right | correct], [right | answer], score), do: check_exam(correct, answer, score + 4)
  def check_exam([_right | correct], ["" | answer], score), do: check_exam(correct, answer, score)
  def check_exam([_right | correct], [_wrong| answer], score), do: check_exam(correct, answer, score - 1)
  def check_exam([], [], score) when score < 0, do: 0
  def check_exam([], [], score), do: score
end

CheckExam.check_exam(["a", "a", "b", "b"], ["a", "c", "b", "d"])
CheckExam.check_exam(["a", "a", "c", "b"], ["a", "a", "b",  ""])
CheckExam.check_exam(["a", "a", "b", "c"], ["a", "a", "b", "c"])
CheckExam.check_exam(["b", "c", "b", "a"], ["",  "a", "a", "c"])