20 TeX是否有办法在顺序的执行次序下获取之后文本的信息

发布于 2025-01-24 23:27:55

这个标题很令人摸不着头脑,但大致是下面的需求:
下面有一小段代码用于排版problem-solution的内容:

\documentclass{article}
\usepackage[many]{tcolorbox}
\newcounter{problem}
\newcounter{solution}
\newcommand*{\Problem}[1]{%
    \setcounter{solution}{0}
    \refstepcounter{problem}%
    \begin{tcolorbox}[enhanced,title={\bfseries Problem~\theproblem},colframe=magenta!80!white,colback=magenta!20!white]
        #1
    \end{tcolorbox}    
}
\newcommand*{\Solution}[1]{%
    \refstepcounter{solution}%
    \begin{tcolorbox}[enhanced,title={\bfseries Solution~\theproblem-\thesolution},colframe=cyan!80!white,colback=cyan!20!white]
        #1
    \end{tcolorbox}    
}
\begin{document}
    \Problem{This is the problem statement.}
    
    \Solution{This is the first solution of the problem}
xi
    \Problem{This is another problem but two solution multiple line.}

    \Solution{This is the second solution.}
    
    \Solution{This is the second solution.}

    \Problem{This is another problem balabalabala}

    \Solution{This is the only solution}

    \Problem{This is another problem balabalabala}
\end{document}

效果图如下,由一个问题可能有1个解答,或者多于1个解答。

image.png

希望:

  • 只有一个解答的时候,标题不要出现Solution 3-1,而只出现Solution 3
  • 多于一个解答时保留现状

于是出现了如题所述的“TeX是否有办法在顺序的执行次序下获取之后文本的信息”问题?是否有比较优雅的方式实现这一点进行逻辑判断。

查看更多

关注者
0
被浏览
87
雾月
雾月 1天前
这家伙很懒,什么也没写!

这类问题总是可以通过把必要的信息写入到辅助文件中解决。

\documentclass{article}
\usepackage[many]{tcolorbox}
\newcounter{problem}
\newcounter{solution}

\makeatletter
\protected\def\solutionwriteaux{\immediate\write\@auxout{%
  \global\string\@namedef
  {solution@count@of-\number\value{problem}}{\number\value{solution}}}}
\def\solutionmaxcount{\@ifundefined{solution@count@of-\number\value{problem}}
  {1}{\@nameuse{solution@count@of-\number\value{problem}}}}
\def\thesolutionornone#1{\ifnum\number\solutionmaxcount>\@ne #1\thesolution\fi} % #1: sep
\makeatletter

\newcommand*{\Problem}[1]{%
    \setcounter{solution}{0}
    \refstepcounter{problem}%
    \begin{tcolorbox}[enhanced,title={\bfseries Problem~\theproblem},colframe=magenta!80!white,colback=magenta!20!white]
        #1
    \end{tcolorbox}    
}
\newcommand*{\Solution}[1]{%
    \refstepcounter{solution}%
    \solutionwriteaux        % <- 这里写入辅助文件
    \begin{tcolorbox}[enhanced,
      title={\bfseries Solution~\theproblem \thesolutionornone{-}}, % <- 检查是否多于一个
      colframe=cyan!80!white,colback=cyan!20!white]
        #1
    \end{tcolorbox}    
}
\begin{document}
    \Problem{This is the problem statement.}
    
    \Solution{This is the first solution of the problem}
xi
    \Problem{This is another problem but two solution multiple line.}

    \Solution{This is the second solution.}
    
    \Solution{This is the second solution.}

    \Problem{This is another problem balabalabala}

    \Solution{This is the only solution}

    \Problem{This is another problem balabalabala}
\end{document}
1 个回答

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览