42

How can I produce exercises in one part of a LaTeX document with selected answers in another? I could, of course, simply typeset the questions and the answers separately, but this is too likely lead to divergence in the labels for the questions and the answers as the document is edited.

What I'd really like is a command that would allow me to typeset exercises at the point at which the command was used and which took an optional argument for a solution to be stored until a final section (chapter, or part) "Selected Exercise Answers". I'd like the questions (and the selected answers) to be labeled in the output by Chapter.Section.Question or even Chapter.Question.

Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036
vanden
  • 30,891
  • 23
  • 67
  • 87

7 Answers7

23

You can use the exam document class in both your documents. Then refer to chapter 8: including solutions.

Basically, anywhere in the document you can just specify \printanswers or \noprintanswers or use the answers option when loading the document class.

It’s easiest if you have the actual questions and answers in a separate document that you \input into both the exercise document and the sample solution document.

If you want an extra section with the answers, you could instead \input the questions document twice, once before and once after the \printanswers document: this will cause the first appearance of the questions to be printed without answers, and the second appearance with answers.

Konrad Rudolph
  • 39,394
  • 22
  • 107
  • 160
7

The answers package appears to do something like this (do texdoc answers, or the equivalent on your platform, for the documentation).

If that doesn't work, or isn't really suitable, then I've got a hand-rolled solution to exactly this problem which I could post here.

(duplicated from a stackoverflow question)


OK: Sam Nead, in the comments, wanted to see the hand-rolled version, so I've included it in part below. The comments report an inheritance from Victor Eijkhout's comment.sty, but he's not to blame for the way I've butchered it. This isn't complete, as it doesn't show the output file being read in at the end. It illustrates that if you want to write out stuff with backslashes, you might have to do entertaining things with catcodes. Certainly, I learned a few things from examining and adapting Eijkhout's code.

No warranty expressed or implied; contents may settle during handling; do not ingest; and keep well out of the reach of children.

%%% {examples} environment -- problem/example, to be collected at the end
%
% \if@examples is a flag to tell us if we've seen any examples yet.
\newif\if@examples \@examplesfalse
\newwrite\@exampleaux
\@definecounter{example}
%
% Don't use \newenvironment.  Instead use the fact that \begin{env}
% turns into \begingroup\env .  This code is simplified from
% Eijkhout's comment.sty
%
% The \@bsphack...\@esphack pair doesn't seem to want to work, here
% (well, it does in horizontal, but not in vertical, mode).
%
% The {example} environment takes an optional argument, giving the
% number of dangerousbend symbols to attach to the example.  The
% default is zero (negative numbers are treated the same as zero,
% numbers larger than about 2 are probably silly, but will work).
%
% Unfortunately, because of the \@ifnextchar, and the fact that the
% contents of this environment are processed oddly, you can't have
% anything expandable immediately after the \begin{example}, unless
% you write \begin{example}[0] or \begin{example}\relax.
%
% The end of the environment must be \end{example} alone on a line
% (ie, no whitespace before or after).  The same is true for the
% beginning and end of the {examplenotes} environment.
%
\def\makeother#1{\catcode`#1=12 }
\def\example{\@bsphack\@ifnextchar[%]
    \@example{\@example[0]}}
% \@openexamples opens the examples file.  Nilpotent.
\def\@openexamples{%
    \if@examples \else
        \immediate\openout\@exampleaux\jobname.examples%
        \immediate\write\@exampleaux{\relax}%
        \global\@examplestrue
    \fi
}
\def\theexample{\@arabic\c@example}
\def\@example[#1]{%
    \@openexamples
    \refstepcounter{example}%
    % Read in contents line by line, with all catcodes `other'
    \let\do\makeother \dospecials %
    \makeother\^^L%
    \endlinechar`\^^M \catcode`\^^M=12 %
    \immediate\write\@exampleaux %
        {\string\begin{examplebody}%
            {\theexample}%
            {\csname the\LN@currsectionlevel\endcsname}%
            {#1}%
        }%
    \if@screenpdf %
        \marginpar{\small{\hyperlink{ex-\@arabic\c@example}{Ex.\theexample}}}%
    \else %
        \marginpar{\small{See example \theexample}}%
    \fi %
        \@tempswatrue
    \ProcessExampleLine %
}
%
% Define \EndExampleTest, with all catcodes other
{\escapechar=-1 \xdef\EndExampleTest{\string\\end\string\{example\string\}}}
{\escapechar=-1 \xdef\BeginNotesTest{\string\\begin\string\{examplenotes\string\}}}
{\escapechar=-1 \xdef\EndNotesTest{\string\\end\string\{examplenotes\string\}}}
% Write out the body of the {example}, carefully surrounding the
% content of the {examplenotes} environment with
% \ifexamplenotes...\fi.  Note this _requires_ that the beginning and 
% end of the {examplenotes} environment appear on lines by
% themselves.  Change the escape character so that we can write out
% \if..\fi without problems.
{\catcode`\^^M=12 \endlinechar=-1 \catcode`\|=0 |catcode`|\=12 %
 |gdef|ProcessExampleLine#1^^M{|def|test{#1}%
        |if@tempswa
          |immediate|write|@exampleaux{\ifexampletext}|@tempswafalse
        |fi
    |ifx|BeginNotesTest|test %
        |immediate|write|@exampleaux{\fi\ifexamplenotes}%
    |fi %
    |ifx|EndExampleTest|test %
        |edef|next{%
            |immediate|write|@exampleaux{\fi\end{examplebody}}%
            |@esphack %
            |endgroup %
            }%
    |else %
        |immediate|write|@exampleaux{#1}%
        |ifx|EndNotesTest|test %
            |immediate|write|@exampleaux{\fi\ifexampletext}%
        |fi %
        |let|next|ProcessExampleLine %
    |fi %
    |next}%
}

% Add text to the examples file
\long\def\addtoexamples#1{%
    \@openexamples
    {\@temptokena{#1}%
     \immediate\write\@exampleaux{\the\@temptokena}}}
Norman Gray
  • 7,497
  • 2
  • 25
  • 35
6

My ExSheets package is designed for exactly this purpose. It gives you the possibility to print the answers to the exercises all at once, selected by section or chapter, or print them by question ID. The example below assumes that every exercise has an answer but that's actually not necessary.

One could also collect all the exercises and their solutions in a seperate file (or maybe one file per part?) and include selected exercises where they should be input. This of course still means that the answers could be printed selectively.

\documentclass{book}
\usepackage{exsheets}
\SetupExSheets{
  % question numbering: »chapter.question«
  % use `ch.se.qu' for »chapter.section.question«
  counter-format = ch.qu
}
% Adjust the heading so there's are gap between heading and
% the previous paragraph a littler larger than the default:
\DeclareInstance{exsheets-heading}{block}{default}
  {
    join   = { title[r,B]number[l,B](1ex,0pt) } ,
    attach =
      {
        main[l,vc]title[l,vc](0pt,0pt) ;
        main[r,vc]points[l,vc](\marginparsep,0pt)
      },
    above  = \baselineskip-.5ex ,
    below  = .5ex
  }

\usepackage{kantlipsum}

\begin{document}
\chapter{One}\exlabel{chap:one}
\section{One A}
\kant[2]

\begin{question}[ID=one:a]
 Question of section one a.
\end{question}
\begin{solution}
 Solution to the question one a.
\end{solution}

\section{One B}
\kant[3]

\begin{question}[ID=one:b]
 Question of section one b.
\end{question}
\begin{solution}
 Solution to the question one b.
\end{solution}

\chapter{Two}\exlabel{chap:two}
\section{Two A}
\kant[4]

\begin{question}[ID=two:a]
 Question of section two a.
\end{question}
\begin{solution}
 Solution to the question two a.
\end{solution}

\section{Two B}
\kant[5]

\begin{question}[ID=two:b]
 Question of section two b.
\end{question}
\begin{solution}
 Solution to the question two b.
\end{solution}

\chapter{Selected Exercise Answers}
\printsolutions
% or select by ID:
% \printsolutions[byID={one:a,two:b}]
% or select by chapter:
% \printsolutions[chapter=\exref{chap:two}]

\end{document}
cgnieder
  • 66,645
  • Awesome package, Clemens! :) – Paulo Cereda Oct 20 '12 at 00:08
  • @cgnieder Can I use your package in Vietnamese? How can I rename 'Question' and 'Solution'? – minthao_2011 Nov 02 '14 at 11:38
  • @minthao_2011 There are two possibilities both described in the manual: a) there are options to set the names manually b) there is a way to add translations that will be used if the babel language is chosen. – cgnieder Nov 03 '14 at 12:17
  • @cgnieder I used \usepackage[vietnam]{babel}, but the Questions and the Solutions did not translate. – minthao_2011 Nov 03 '14 at 16:06
  • That's because I and hence exsheets don't know the correct translations. But the manual explains how they can be added. Search the manual for "translation" or "internationalization – cgnieder Nov 03 '14 at 17:01
  • @minthao_2011 BTW: if you send me the translations I'm glad to add them to exsheets – cgnieder Jul 06 '15 at 06:33
  • This is exactly what I need. But I am not sure on How to print only the solutions to odd exercises. – JPMD Aug 02 '23 at 13:29
4

Strange that nobody mentioned the exercise package. See the following example, in which the answers are 'created' just after the exercises, but only printed later in the second section. Things like difficulty level, exercise header, etc. can all be defined.

\documentclass{article}

\usepackage[answerdelayed,lastexercise]{exercise}

\begin{document}
\section{Questions}
Here are some questions:
\begin{Exercise}[title={First question}]
  This is the first exercise.
\end{Exercise}
\begin{Answer}
  This is the first answer.
\end{Answer}

\begin{Exercise}[title={Second question},difficulty=3]
  Questions number two, without an anwer.
\end{Exercise}

\begin{Exercise}[title={Third question}]
  Question number three, this one has an answer again.
\end{Exercise}
\begin{Answer}
  Answer number three.
\end{Answer}

\section{Answers}
Here we print the answers:
\shipoutAnswer


\end{document}
ph0t0nix
  • 1,200
1

If you can't find a LaTeX package to do your job, this can be done with the \openout, \write and \closeout commands of TeX to output whatever you want to an auxilliary file, and then import it back by running \input on it. The file writing functions are described on pages 226--228 in the TeXBook.

1

You try this code.

\documentclass[12pt,openany,twoside]{book} 
\usepackage{fouriernc}
\usepackage[thmmarks,standard,thref]{ntheorem}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{answers}

\theoremseparator{.}
\theorembodyfont{\upshape}
\newtheorem{pro}{Problem}[chapter]

\Newassociation{loigiai}{Answer}{loigiaichung}


\begin{document}
\chapter{Firist }
\thispagestyle{empty}
\Opensolutionfile{loigiaichung}[pro]
\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\Closesolutionfile{loigiaichung}
\section{This is solution}
\input{pro}

\chapter{Firist }
\thispagestyle{empty}
\Opensolutionfile{loigiaichung}[pro]
\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\Closesolutionfile{loigiaichung}
\section{This is solution}
\input{pro}

\end{document}
cgnieder
  • 66,645
minthao_2011
  • 4,534
  • 7
  • 36
  • 61
1

This is another solution

\documentclass[12pt,openany,twoside]{book} 
\usepackage{fouriernc}
\usepackage[thmmarks,standard,thref]{ntheorem}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{answers}

\theoremseparator{.}
\theorembodyfont{\upshape}
\newtheorem{pro}{Problem}[chapter]

\Newassociation{loigiai}{Answer}{loigiaichung}


\begin{document}
\chapter{Firist }
\thispagestyle{empty}
\Opensolutionfile{loigiaichung}[pro]
\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}




\chapter{Second }
\thispagestyle{empty}
\Opensolutionfile{loigiaichung}[pro]
\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}


\begin{pro}
This is a problem
\begin{loigiai}
This is a solution
\end{loigiai}
\end{pro}

\Closesolutionfile{loigiaichung}
\section{This is solution}
\input{pro}

\end{document}
minthao_2011
  • 4,534
  • 7
  • 36
  • 61