# Section with answers created automatically

My question is quite similar to this one, but I think a slightly different approach is needed.

I have a document with a lot of exercices and I'd like to add aswers and hints to them in a certain section.

I don't want to do this manually, since, if I add an exercice, I'll have to make that the answers and hints keep the right order. Also, it's possible that not all exercices have an answer and a hint with them, so the numbering of answers and hints should be completely dependent of the numbering of exercices.

I.e, things like

1. Some hint for exercice 1
2. Some hint for exercice 2
4. Some hint for exercice 4
99. Some hint for exercice 99


should be possible.

For example:

\documentclass[12pt,a4paper]{article}
\usepackage[dutch]{babel}
\usepackage{amsthm}

\newtheorem{ex}{Exercice}
\newtheorem{ans}{} % Abbreviation for answer. No text needed because I just want numbers with the answers next to them.
\newtheorem{hi}{} % Same here.

\begin{document}

\section{Algebra}
\begin{ex}What is $1+3$?\end{ex}
\begin{hi}First consider $1+0$, $1+1$, $1+2$ and try to find a pattern.\end{hi}
\begin{ans}It's $4$!\end{ans}

\section{Grammar}
\setcounter{ex}{0} % So the counter is set to zero when a new section begins.

\begin{ex}The first letter of the alphabet?\end{ex}
%No hint given here
\begin{ans}A\end{ans}

\subsection{Section Algebra}
%Answer should be here, but of course it isn't.

\subsection{Section Grammar}
%Same.

\section*{Hints}
\subsection{Section Algebra}
%Hint here.

\subsection{Section Grammar}
% No hint because I didn't ask Latex to do so.

\end{document}


So in fact I need some \magicCommandThatPutsAnswersAndHintsSomewhereElse. If there's more then one answer in a section, I'd like them to be numbered like theorems.

As you may have noticed in the example, I want the answers and hints in a subsection that refers to their section.

• I've done this for my book. I could show you the code (email me if you want) but basically: to output answers to somewhere else I used the answers package and to refer to things in the main text from the answers file I used the xr package. (Also, there is a counter giving the current exercise number and you can define the environment ans to start with \textbf{that counter} so your answer file is not just taking the answer numbers in ascending order.) – Jim Hefferon Aug 21 '13 at 11:31
• @JimHefferon that sounds useful - and also suggests a possible solution for non-broken hyperref endnotes... – Joe Corneli Aug 21 '13 at 13:18
• @JimHefferon thanks, I'll first try myself to fix it using answers and xr, and I'll report back when I have some results. – Schneider Aug 21 '13 at 15:26
• @JimHefferon I'm just wondering: what exactly did you need the xr package for? It seems like I can freely refer to labels in the main text from the answers. When I refer from the main text to the answers, it seems that the answers are simply numbered continuously, but the number that is displayed is the same as the corresponding exercise. For example if I number the answers per sections like 1.1, 1.2, 2.1, 2.2 the answers are 'labeled' 1, 2, 3, 4 while the displayed numbering is really 1.1, 1.2, 2.1, 2.2. – Schneider Jun 25 '14 at 13:01
• I allow for something more complicated that sequentially numbered exercises. For instance, I allow for the publication of a list of answers of the questions that are checkmarked. (I also number the exercises in sequence with the theorems.) – Jim Hefferon Jun 25 '14 at 19:54

I face the same issue as you do. I create my exercises lists with two features: I can print it with the answers (for students) or with the solutions (for me; in this case, the answers disappear).

I will show you here pieces of my code (it is too huge and, believe me, is not worth to paste it as a whole here). So, let's start...

I created the commands \problem where I state the problem and \answer where I store the answer to each problem, as well as the environment solution where I store the solution to the problem (with the argument, I can set the number of columns to arrange the solution in order to make it more compact):

%-> Defining COUNTERS:
\newcounter{problem}

%-> Defining the numbered environment for QUESTIONS, TESTS, EXERCISES, PROBLEMS, and CHALLENGES:
\newcommand{\problem}{%
\par\bigskip
\refstepcounter{problem}
\noindent\textbf{\theproblem}
}

%-> Defining the environment for the ANSWERS to QUESTIONS
\let\thefootnote\relax %... suppresses the footnote numbering
\footnote{\textbf{\theproblem-} #1}%
}

\newif\ifcols

%-> Defining the environment for the SOLUTIONS:
\newenvironment{solution}[1]{%
\setlength{\parindent}{0cm}
\vspace{-2.5mm}
\textbf{\footnotesize Solution:}\par
\vspace{-3mm}
\footnotesize
\ifnum #1 > 1
\colstrue
\begin{multicols}{#1}
\fi
}{%
\ifcols
\end{multicols}
\fi
\colsfalse
}


Lattar on, I create the Boolean \ifshowans for which \showanstrue can be commented out whenever I want to hide the solution and show the answer (in case I want to prin material for the students). Otherwise, it will print the solution and hide the answers:

%-> Defining the MATERIAL TYPE:
\newif\ifshowans
\showanstrue
\ifshowans
\else
\let\solution\comment
\let\endsolution\endcomment
\fi


Up to here, you can observe that in my case, I preferred to show the solutions in the footnotes. Since you want to display them at the end of the document, you should modify the \answer command to something like this:

%-> Defining the environment for the ANSWERS to QUESTIONS
\let\theendnote\relax %... suppresses the endnote numbering
\endnote{\textbf{\ptype\ \mnumber.\theproblem-} #1}%
}


I hope this helps you.

## Edit:

This is an example of use (my students are Brazilian, so the problems are stated in Portuguese... sorry for that):

\problem
O dia 21 de dezembro marca o solstício de verão no hemisfério sul. Nesse dia do ano, as sombras das pessoas em São Paulo (SP) têm comprimento nulo. Em uma viagem a Brasília nesse dia, a sombra projetada no chão de uma pessoa em pé ao meio-dia local tem um comprimento de 23,7 cm. Sabendo que a altura da pessoa é de 1,73 m e que uma volta à Terra tem comprimento $C = 40\ \v{mil\ km}$, calcule a distância entre São Paulo e Brasília.

%---------- SOLUTION ----------%
\begin{solution}{2}
Do triângulo formado pela pessoa, sua sombra e o raio de luz do Sol, tem-se
$$\tan\theta = \frac{23,7}{173} = 0,137 \ \ \ \Rightarrow \ \ \ \theta = 7,80\deg$$

Por regra de três simples,
$$\begin{array}{rcl} 360\deg & \rightarrow & 40 000\ \v{km} \\ 7,80\deg & \rightarrow & d \end{array} \ \ \ \Rightarrow \ \ \ d = 870\ \v{km}$$
\end{solution}


## Edit 2: I just removed some undefined (and meaningless) commands

Here is a minimal version of what I did. It does not include additions such as: page numbers in the solutions section, links that point back to the exercise, an indication next to an exercise if there is a written solution, ... for the sake of brevity.

In the code below I assume that there is a counter exercise, which in your case may be theorem. (See the bottom for a MWE.)

I use the package environ to define an environment solution whose \BODY I can access. Its body is written verbatim to a file solutions.txt, which is included in the document later on. Note how every backslash has to be escaped.(Source)

\usepackage{environ}
\newwrite\SolutionWriter
\makeatletter
\NewEnviron{solution}{%
\immediate\write\SolutionWriter{%
\@backslashchar noindent%
\@backslashchar textbf{Solution \theexercise}.{ }%
\detokenize\expandafter{\BODY}%
}%
}
\makeatother


Then put \immediate\openout\SolutionWriter=solutions.txt after \begin{document}. You can now do things like

\begin{exercise}What is $1+3$?\end{exercise}
\begin{solution}It's $4$!\end{solution}


provided you write

\immediate\closeout\SolutionWriter
\section{Solutions}
\input{solutions.txt}


later in the document. (When there are no more exercises).

To add section titles in the solutions section, one can probably use etoolbox's apptocmd, but as soon as you start customizing sections, it is probably a good idea to use titlesec. Since there can be sections which you don't want to appear in the solutions section, I create a \ifexercises which you can set to false for a specific section. (See here for an approximation of the default section formats.)

\newif\ifexercises
\exercisestrue
\usepackage[explicit]{titlesec}
\makeatletter
\titleformat{\section}
{\normalfont\Large\bfseries}
{\thesection}
{1em}
{#1}
[\ifnum\value{section}=0\else% exclude contents
\ifexercises\immediate\write\SolutionWriter{%
\fi\fi%
\global\exercisestrue]
\makeatother


Then put \exercisesfalse just before the section which you don't want to appear between the solutions.

MWE

\documentclass{article}

\usepackage{environ}
\newwrite\SolutionWriter
\makeatletter
\NewEnviron{solution}{%
\immediate\write\SolutionWriter{%
\@backslashchar noindent%
\@backslashchar textbf{Solution \theexercise}.{ }%
\detokenize\expandafter{\BODY}%
}%
}

\newif\ifexercises
\exercisestrue
\usepackage[explicit]{titlesec}
\titleformat{\section}{\normalfont\Large\bfseries}{\thesection}{1em}{#1}
\makeatother

\usepackage{amsthm}
\newtheorem{exercise}{Exercise}

\begin{document}
\immediate\openout\SolutionWriter=solutions.txt

\section{Algebra}

\begin{exercise}What is $1+3$?\end{exercise}
\begin{solution}It's $4$.\end{solution}

\section{Grammar}

\begin{exercise}What is the first letter of the alphabet?\end{exercise}
\begin{solution}A and this is a solution which is made very long on purpose so that it spans multiple lines.\end{solution}

\begin{exercise}What is the second letter of the alphabet?\end{exercise}
\begin{solution}B\end{solution}

\exercisesfalse %alternatively, close the writer before the solutions section
\section{Solutions}
\immediate\closeout\SolutionWriter
\input{solutions.txt}

\end{document}


The spacing around the solutions is not perfect. I tried to imitate the spacing from the amsthm package.