Since your question is about storing, maintaining and referencing a large set of exercises (potentially in the order of 10,000), I'm going to concentrate on that, so the style here is very basic.
It's possible to define conditionals using \newif
(or through commands provided by packages such as etoolbox
). For example:
\newif\ifsolutions
\newif\ifcomplete
These default to false, but can be switched on:
\solutionstrue
\completetrue
It's also useful to provide syntactic commands to mark the solution. For example:
\newcommand{\solutionname}{Solution}
\newcommand{\solution}{\par\textbf{\solutionname}:\par}
As has been mentioned in one of the other answers, it's also possible to use environments and the comment
package. For multilingual support, the caption hooks can be used to redefine \solutionname
as appropriate. For example:
\usepackage[USenglish]{babel}
\addto\captionsUSenglish{%
\renewcommand\solutionname{Solution}%
}
Now an exercise can be written using these commands. For example:
$y = \sin(2x)$
\ifsolutions
\solution
\ifcomplete
Intermediate steps, further details etc.
\fi
$y' = 2\cos(2x)$
\fi
Environments provide a more LaTeXy feel, but let's concentrate on storing and accessing the questions.
The simple method, which has already been suggested, is to put each question in a separate file and load it with \input
. For example, if this exercise is in the file exercises/calculus/easy/dsin.tex
then the following MWE works:
\documentclass{article}
\newif\ifsolutions
\newif\ifcomplete
\solutionstrue
\completetrue
\newcommand{\solutionname}{Solution}
\newcommand{\solution}{\par\textbf{\solutionname}:\par}
\begin{document}
\begin{enumerate}
\item \input{exercises/calculus/easy/dsin}
\end{enumerate}
\end{document}
This is a relatively generic method, which can easily be translated to other TeX formats. For example, the Plain TeX equivalent is:
\newif\ifsolutions
\newif\ifcomplete
\solutionstrue
\completetrue
\def\solutionname{Solution}
\long\def\solution{\par{\bf\solutionname}:\par}
\newcount\questionnum
\long\def\question{%
\par
\advance\questionnum by 1\relax
\number\questionnum.
}
\question \input exercises/calculus/easy/dsin
\bye
The problem is that, although this structure is fine for a small number of questions, it can become unmanageable for 10,000. I mentioned datatooltk
in the comments, which can read and write .dbtex
files (datatool
's internal format), but I don't recommend using this format directly. These files just contain LaTeX code that defines the internal registers and control sequences used by datatool
to store the required data. There's no compression and it takes up a huge amount of resources. The datatooltk
application works better as an intermediary that can pull filtered, shuffled or sorted data from external sources in a way that can easily be input in the document. (See the datatool
performance page that compares build times for large databases.)
There are switches, such as --shuffle
or --sort
, which instructs datatooltk
to shuffle or sort the data after it's been pulled from the data source. This uses Java, which is more efficient than TeX, but if the data is stored in a SQL database, it's even more efficient to include these steps in the actual --sql
switch. (Currently, datatooltk
is only configured for MySQL, but it may be possible to use something else if the necessary .jar
file can be added to the class path.)
SQL databases can be optimized to improve performance. Suppose you want to randomly select 20 questions from 500. How do you perform that selection in LaTeX? First you'd need to use the shell to find out all the available files (or have an index file that can be parsed). Then you need to shuffle the list. That will take a while to do with TeX. It's more efficient to do this with SQL. (See, for example, MySQL select 10 random rows from 600K rows fast.)
If you decide to use SQL, the next thing to consider is the table structure.
- You'll need a unique id field. With this you'll be able to specifically select certain questions rather than have a random selection. (An auto increment primary key is best.)
- A field containing the question. (Let's call it
Question
.)
- A field containing the brief answer. (Let's call it
Answer
.)
- A field containing the extended answer. (Let's call it
ExtendedAnswer
.)
- A field identifying the difficulty level. (Let's call it
Level
.) This could be an integer (1 = easy) or an enumeration (easy
, medium
, hard
).
- A field identifying the topic. (Let's call it
Topic
.) An enumeration is probably the simplest type (for example, calculus
, settheory
).
I'm not quite sure about the language. There are two approaches that I can think of: have fields for the other language (For example, QuestionPortuges
, AnswerPortuges
and ExtendedAnswerPortuges
) or have a separate entry for the question in a different language with an extra field for the language.
So the above exercise example, could have
Question
=> $y = \sin(2x)$
Answer
=> $y' = 2\cos(2x)$
ExtendedAnswer
=> Intermediate steps, further details etc. \[y' = 2\cos(2x)\]
Level
=> 1
Topic
=> calculus
Language
=> english
or ExtendedAnswerPortuges
=> Passos intermédios, etc. \[y' = 2\cos(2x)\]
Note that this doesn't include the syntactic command \solution
or the conditionals \ifsolutions
and \ifcomplete
, which makes it easier to arrange the various parts of the question and answer.
It may be that some exercises require a particular package (such as amsmath
or graphicx
), so perhaps there could also be a field for the required packages. For example Packages
=> graphicx,amsmath
.
Any images or verbatim text must be stored outside the database somewhere on the file system. They could be on TeX's path or the database table could have a field with a list of external resources or the question/answer could simply use the full path.
The datatooltk
call can be done before the LaTeX run or using the shell escape. There's also a datatooltk
rule for arara
users. Let's suppose, I use datatooltk
to pull a random selection of questions and save the results in a file called exercises.dbtex
. This can then be loaded in the document using:
\DTLloaddbtex{\exercisedb}{exercises.dbtex}
If the data includes the Packages
field, you can make sure all the required packages are loaded by adding the following to the preamble:
\DTLforeach*{\exercisedb}{\Packages=Packages}
{\DTLifnullorempty{\Packages}{}{\usepackage{\Packages}}}
In the main part of the document:
\begin{enumerate}
\DTLforeach*{\exercisedb}% data base
{\Question=Question,\Answer=Answer,\ExtendedAnswer=ExtendedAnswer}% assignment list
{%
\item \Question
\ifsolutions
\solution
\ifcomplete
\ExtendedAnswer
\else
\Answer
\fi
\fi
}
\end{enumerate}
Further reading: Using the datatool Package for Exams or Assignment Sheets
It is possible to prepend the \chapter
command to write some information about the chapter into the record file. This will fail for the first chapter since the recording has not started then.
It will also fail if the chapter number is reset.
Since the prepending occurs before the chapter number is increased, I've decided to trick
\c@chapter
using a number increased by one within a TeX
group, so the counter value is not really changed but \thechapter
will use the tricked value for while and apply the correct format as defined for \thechapter
. This is better than using something like \arabic{chapter}
etc, in my point of view.
Change the \solutionchapterformat
macro at will to produce any nice/fancy heading of the solution-chapter-group (but leave the \bgroup...
\egroup
)
\documentclass{book}
\usepackage[most]{tcolorbox}
\usepackage{xpatch}
% Formatting command as a 'headline' of the solutions of chapter X
\NewDocumentCommand{\solutionchapterformat}{m}{%
\noindent \bgroup\bfseries Solutions of the exercises of the chapter #1\egroup%
}
\makeatletter
\xpretocmd{\chapter}{%
\begingroup
\ifnum\value{chapter}>0\relax
\tcbrecord{\string\clearpage}% Write a clearpage after the first chapter for each new chapter
\fi
\c@chapter \numexpr\c@chapter+1% Increase the count register `\@chapter` by one to trick `\thechapter` using the 'correct' chapter number
\tcbrecord{%
\solutionchapterformat{\thechapter}}%
\endgroup
}{}{}
\NewDocumentCommand{\extrasolutioncontent}{+m}{%
\tcbrecord{Extra solution stuff\par}% Remove this later on!
\tcbrecord{\detokenize{#1}}%
}
\newcommand{\fetchsolutions}{%
%For the first chapter
\begingroup
\c@chapter1%
\solutionchapterformat{\thechapter}%
\endgroup% Now get the rest of the stuff
\tcbinputrecords
}
\makeatother
%\tcbuselibrary{skins,breakable}
%\usepackage{polyglossia}
%\setmainlanguage{english}
%\usepackage{fontspec}
%\setmainfont{Times New Roman}
%\setsansfont{Arial}
%\setmonofont{Courier New}
\NewTColorBox[auto counter,number within=chapter]{exercise}{m+O{}}{%
enhanced,
colframe=green!20!black,
colback=yellow!10!white,
coltitle=green!40!black,
fonttitle=\bfseries,
underlay={\begin{tcbclipinterior}
\shade[inner color=green!80!yellow,outer color=yellow!10!white]
(interior.north west) circle (2cm);
\draw[help lines,step=5mm,yellow!80!black,shift={(interior.north west)}]
(interior.south west) grid (interior.north east);
\end{tcbclipinterior}},
title={Exercise~ \thetcbcounter:},
label={exercise:#1},
attach title to upper=\quad,
after upper={\par\hfill\textcolor{green!40!black}%
{\itshape Solution on page~\pageref{solution:#1}}},
lowerbox=ignored,
savelowerto=solutions/exercise-\thetcbcounter.tex,
record={\string\solution{#1}{solutions/exercise-\thetcbcounter.tex}},
#2
}
\NewTotalTColorBox{\solution}{mm}{%
enhanced,
colframe=red!20!black,
colback=yellow!10!white,
coltitle=red!40!black,
fonttitle=\bfseries,
underlay={\begin{tcbclipinterior}
\shade[inner color=red!50!yellow,outer color=yellow!10!white]
(interior.north west) circle (2cm);
\draw[help lines,step=5mm,yellow!80!black,shift={(interior.north west)}]
(interior.south west) grid (interior.north east);
\end{tcbclipinterior}},
title={Solution of Exercise~\ref{exercise:#1} on page~\pageref{exercise:#1}:},
phantomlabel={solution:#1},
attach title to upper=\par,
}{\input{#2}}
\tcbset{no solution/.style={no recording,after upper=}}
\begin{document}
\chapter{The first chapter}
\tcbstartrecording
\begin{exercise}{Ex1}[coltitle=cyan!80!black]
Compute the derivative of the following function:
\begin{equation*}
f(x)=\sin((\sin x)^2)
\end{equation*}
\tcblower
The derivative is:
\begin{align*}
f’(x) &= \left( \sin((\sin x)^2) \right)’
=\cos((\sin x)^2) 2\sin x \cos x.
\end{align*}
\end{exercise}
\vspace*{1cm}
The solution of the exercise \ref{exercise:Ex1} is in the page \pageref{solution:Ex1}
\vspace*{1cm}
%\tcbstoprecording
%\tcbinputrecords
\chapter{The second chapter}
%\tcbstartrecording
\begin{exercise}{Ex2}[coltitle=cyan!80!black]
Compute the derivative of the following function:
\begin{equation*}
f(x)=(x^2+1) \sqrt{x^4+1}
\end{equation*}
\tcblower
The derivative is:
\begin{align*}
f’(x) &= \left( (x^2+1) \sqrt{x^4+1} \right)’
= 2x\sqrt{x^4+1} + \frac{2x^3(x^2+1)}{\sqrt{x^4+1}}.
\end{align*}
\end{exercise}
\vspace*{1cm}
The solution of the exercise \ref{exercise:Ex2} is in the page \pageref{solution:Ex2}
\vspace*{1cm}
\chapter{The third chapter}
\begin{exercise}{Ex3}[coltitle=cyan!80!black]
Compute the derivative of the following function:
\begin{equation*}
f(x)=(x^2+1) \sqrt{x^4+1}
\end{equation*}
\tcblower
The derivative is:
\begin{align*}
f’(x) &= \left( (x^2+1) \sqrt{x^4+1} \right)’
= 2x\sqrt{x^4+1} + \frac{2x^3(x^2+1)}{\sqrt{x^4+1}}.
\end{align*}
\end{exercise}
\vspace*{1cm}
The solution of the exercise \ref{exercise:Ex3} is in the page \pageref{solution:Ex3}
\vspace*{1cm}
\extrasolutioncontent{$\textcolor{blue}{E=mc^2}$}
\begin{exercise}{Ex31}[coltitle=cyan!80!black]
Compute the derivative of the following function:
\begin{equation*}
f(x)=(x^2+1) \sqrt{x^4+1}
\end{equation*}
\tcblower
The derivative is:
\begin{align*}
f’(x) &= \left( (x^2+1) \sqrt{x^4+1} \right)’
= 2x\sqrt{x^4+1} + \frac{2x^3(x^2+1)}{\sqrt{x^4+1}}.
\end{align*}
\end{exercise}
\vspace*{1cm}
The solution of the exercise \ref{exercise:Ex31} is in the page \pageref{solution:Ex31}
\vspace*{1cm}
\chapter{The fourth chapter}
\begin{exercise}{Ex4}[coltitle=cyan!80!black]
Compute the derivative of the following function:
\begin{equation*}
f(x)=(x^2+1) \sqrt{x^4+1}
\end{equation*}
\tcblower
The derivative is:
\begin{align*}
f’(x) &= \left( (x^2+1) \sqrt{x^4+1} \right)’
= 2x\sqrt{x^4+1} + \frac{2x^3(x^2+1)}{\sqrt{x^4+1}}.
\end{align*}
\end{exercise}
\vspace*{1cm}
The solution of the exercise \ref{exercise:Ex4} is in the page \pageref{solution:Ex3}
\vspace*{1cm}
\tcbstoprecording
\newpage
\section{Solutions of the exercices}
\fetchsolutions
\end{document}

Best Answer
As mentioned in the comments the
exsheets
package can be used for this. The titles/names of the exercises can be given as a subtitle using thequestion
environment'ssubtitle
option. To actually print the subtitles a headings instance must be used that typesets it. The predefinedblock-subtitle
instance nearly looks the same as your own defined headings so it can be used.This means we set
which mimics the definitions in your question.
Next thing we need is obviously some
mainquestion
counter which can be used to print the question numbers as 1.1, 1.2, 2.1, etc. Like you I use thesection
counter for the task. Then we need\IfQuestionSubtitleT{:}
ensures that the colon only is typeset when a subtitle is given.For managing the exercises they can be defined in an external file,
myexercises.tex
, say. For the example below I saved it with the following contents:If we put everything together we get:
If you uncomment the line
in the above example you'll get
If you instead add
\printsolutions
at the end you'll getUnfortunately there's currently no way to add subtitles to solutions.