<>= p <- c(sample(1:3, 1), sample(1:5, 1)) q <- c(sample((p[1] + 1):5, 1), sample(1:5, 1)) d <- abs(p - q) sol <- round(c(sum(d), sqrt(sum(d^2)), max(d)), digits = 3) @ \begin{question} Given two points $p = (\Sexpr{p[1]}, \Sexpr{p[2]})$ and $q = (\Sexpr{q[1]}, \Sexpr{q[2]})$ in a Cartesian coordinate system: \begin{answerlist} \item What is the Manhattan distance $d_1(p, q)$? \item What is the Euclidean distance $d_2(p, q)$? \item What is the maximum distance $d_\infty(p, q)$? \end{answerlist} \end{question} \begin{solution} The distances are visualized below in green ($d_1$), red ($d_2$), and blue ($d_\infty$). <>= par(mar = c(4, 4, 1, 1)) plot(0, type = "n", xlim = c(0, 6), ylim = c(0, 6), xlab = "x", ylab = "y") grid(col = "slategray") if(d[1] >= d[2]) { lines(c(p[1], q[1]), c(q[2], q[2]) - 0.05, lwd = 2, col = "darkblue") } else { lines(c(p[1], p[1]) - 0.05, c(p[2], q[2]), lwd = 2, col = "darkblue") } lines(rbind(p, q), lwd = 2, col = "darkred") lines(c(p[1], p[1], q[1]), c(p[2], q[2], q[2]), lwd = 2, col = "darkgreen") points(rbind(p, q), pch = 19) text(rbind(p, q), c("p", "q"), pos = c(2, 4)) @ \begin{answerlist} \item $d_1(p, q) = \sum_i |p_i - q_i| = |\Sexpr{p[1]} - \Sexpr{q[1]}| + |\Sexpr{p[2]} - \Sexpr{q[2]}| = \Sexpr{sol[1]}$. \item $d_2(p, q) = \sqrt{\sum_i (p_i - q_i)^2} = \sqrt{(\Sexpr{p[1]} - \Sexpr{q[1]})^2 + (\Sexpr{p[2]} - \Sexpr{q[2]})^2} = \Sexpr{sol[2]}$. \item $d_\infty(p, q) = \max_i |p_i - q_i| = \max(|\Sexpr{p[1]} - \Sexpr{q[1]}|, |\Sexpr{p[2]} - \Sexpr{q[2]}|) = \Sexpr{sol[3]}$. \end{answerlist} \end{solution} %% META INFORMATION %% \extype{cloze} %% \exsolution{\Sexpr{sol[1]}|\Sexpr{sol[2]}|\Sexpr{sol[3]}} %% \exclozetype{num|num|num} %% \exname{Distances} %% \extol{0.01}