summaryrefslogtreecommitdiff
path: root/macros/latex/contrib/exam-randomizechoices/exam-randomizechoices.sty
blob: b64ae9982c774c46bbaa8f48097f7a05f2bfb445 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
%%
%% exam-randomizechoices.sty
%%
%% Randomize m.c. choices using the exam class
%%
%% Copyright (c)2021, Jesse E. J. op den Brouw
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.3
%% of this license or (at your option) any later version.
%% The latest version of this license is in
%%   http://www.latex-project.org/lppl.txt
%% and version 1.3 or later is part of all distributions of LaTeX 
%% version 2003/12/01 or later.
%%
%% This work consists of the files exam-randomizechoices.sty,
%% exam-randomizechoices.tex and exam-randomizechoices-doc.tex

%% This software is provided 'as is', without warranty of any kind,
%% either expressed or implied, including, but not limited to, the
%% implied warranties of merchantability and fitness for a
%% particular purpose.

%% Jesse op den Brouw
%% Department of Electrical Engineering
%% The Hague University of Applied Sciences
%% Rotterdamseweg 137, 2628 AL, Delft
%% Netherlands
%% J.E.J.opdenBrouw@hhs.nl

%% The newest version of this package should always be available
%% from GitHub: https://github.com/jesseopdenbrouw/exam-randomizechoices

%% Version 0.1 [09/01/2019]: Initial release
%% Version 0.2 [31/07/2021]: Added \savekeylist
%%                           Adapted \printkeytable to accept optional range
%%                           Minor cosmetic changes

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% What LaTeX format do we need and version and date
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\NeedsTeXFormat{LaTeX2e}[1994/06/01]
%% Version and date
\def\fileversion{0.2}
\def\filedate{2021/07/31}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Sign up to LaTeX
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ProvidesPackage{exam-randomizechoices}[\filedate\space \fileversion\space
 LaTeX package for creating random placed choices in multiple choice environments using the exam document class]


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Check if the exam class is loaded
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\@ifclassloaded{exam}%
  {}%
  {\PackageError{exam-randomizechoices}{The exam class is not loaded. Emergency stop!}{You didn't load the exam class explicit using \string\documentclass\space or implied by another class.}\stop}%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Process package options
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Want debug messages
\newif\if@@ercdebug\@@ercdebugfalse
\DeclareOption{debug}{\PackageWarning{exam-randomizechoices}{Debug turned on}\@@ercdebugtrue}

%% Want to overload or not overload the *choices and *checkboxes environments?
\newif\if@@ercoverload\@@ercoverloadfalse
\DeclareOption{overload}{\if@@ercdebug\PackageWarning{exam-randomizechoices}{Overload turned on}\fi\@@ercoverloadtrue}
\DeclareOption{nooverload}{\if@@ercdebug\PackageWarning{exam-randomizechoices}{Overload turned off}\fi\@@ercoverloadfalse}

%% Global keeplast
\newif\if@@ercgkeeplast\@@ercgkeeplastfalse
\DeclareOption{keeplast}{\if@@ercdebug\PackageWarning{exam-randomizechoices}{Global keeplast turned on}\fi\@@ercgkeeplasttrue}
\DeclareOption{nokeeplast}{\if@@ercdebug\PackageWarning{exam-randomizechoices}{Global keeplast turned off}\fi\@@ercgkeeplastfalse}

%% Global random
\newif\if@@ercgrandom\@@ercgrandomtrue
\DeclareOption{randomize}{\if@@ercdebug\PackageWarning{exam-randomizechoices}{Global randomization turned on}\fi\@@ercgrandomtrue}
\DeclareOption{norandomize}{\if@@ercdebug\PackageWarning{exam-randomizechoices}{Global randomization turned off}\fi\@@ercgrandomfalse}

%% Unknown option
\DeclareOption*{\PackageWarning{exam-randomizechoices}{Unknown option '\CurrentOption'}}
\ProcessOptions\relax


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                                                       %%
%% Load needed packages                                  %%
%%                                                       %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% http://ctan.org/pkg/{environ,etoolbox,pgffor}
\RequirePackage{environ}
\RequirePackage{etoolbox}
\RequirePackage{pgffor}

%% A scratch counter
\newcounter{erc@counter}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                                                       %%
%% Loading the randomizer seed                           %%
%%                                                       %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newif\iferc@seedset\erc@seedsetfalse
\newcommand{\setrandomizerseed}[1]{
	\pgfmathsetseed{#1}
	\global\erc@seedsettrue
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                                                       %%
%% Key list question nam and key name                    %%
%%                                                       %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\keylistquestionname}[1]{\edef\erc@keylistquestionname{#1}}
\keylistquestionname{Question}
\newcommand{\keylistkeyname}[1]{\edef\erc@keylistkeyname{#1}}
\keylistkeyname{Key}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                                                       %%
%% \erc@createrandomlist                                 %%
%%                                                       %%
%% This macro creates a randomly ordered list from the   %%
%% choices given in the environments randomizechoices,   %%
%% randomizeoneparchoices, randomizecheckboxes, and      %%
%% randomizeoneparcheckboxes. Typesetting is left to the %%
%% respective environment.                               %%
%%                                                       %%
%% Ideas taken from the mcexam package,                  %%
%% see https://ctan.org/pkg/mcexam                       %%
%%                                                       %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcounter{erc@nrcorrectchoices}

\newif\iferc@keeplast
\newif\iferc@random
\newif\iferc@nolabel
\newcommand{\erc@createrandomlist}[1][]{%
  %%
  \if@@ercdebug
    \PackageWarning{exam-randomizechoices}{Parsing question \thequestion}%
  \fi
  %%
  %% Copy the global package options
  \if@@ercgkeeplast\erc@keeplasttrue\else\erc@keeplastfalse\fi
  \if@@ercgrandom\erc@randomtrue\else\erc@randomfalse\fi
  %%
  %% Check if label can be used
  \erc@nolabelfalse
  %%
  %% Check if the user has defined our special command
  \ifdefined\inaccessible
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{You should NOT define \noexpand\inaccessible}%
    \else
      \PackageError{exam-randomizechoices}{You should NOT define \noexpand\inaccessible. Emergency stop!}{Somewhere in your document, you have defined the macro \noexpand\inaccessible. This package relies on the fact that this macro is not defined. Please use another macro name instead. I have to stop now. Sorry.}%
      \stop
    \fi
  \fi
  %%
  %% Parse options to question
  \foreach \erc@option in {#1} {%
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{I found option: "\erc@option"}%
    \fi
    \ifdefstring{\erc@option}{keeplast}{\global\erc@keeplasttrue}{}%
    \ifdefstring{\erc@option}{nokeeplast}{\global\erc@keeplastfalse}{}%
    \ifdefstring{\erc@option}{randomize}{\global\erc@randomtrue}{}%
    \ifdefstring{\erc@option}{norandomize}{\global\erc@randomfalse}{}%
    \ifdefstring{\erc@option}{nolabel}{\global\erc@nolabeltrue}{}%
  }%
  %%
  %% Counter for counting the number of choices
  \setcounter{erc@counter}{-1}%
  %% Counter for counting the number of correct choices
  \setcounter{erc@nrcorrectchoices}{0}%
  %% Useful \def
  \def\erc@incr{\stepcounter{erc@nrcorrectchoices}}%
  %%
  %% Patch \BODY, \correctchoice and \CorrectChoice are replaced by \choice \inaccessible
  %% We need to do this for the following step, which is splitting the list
  %% into list items, because the list parser can only handle one separator at
  %% a time.
  \newbool{erc@stillpatching}%
  \booltrue{erc@stillpatching}%
  \whileboolexpr{ test {\ifbool{erc@stillpatching}}}{%
    \patchcmd{\BODY}{\CorrectChoice}{\choice \inaccessible }{\erc@incr}{\boolfalse{erc@stillpatching}}%
  }%
  \booltrue{erc@stillpatching}%
  \whileboolexpr{ test {\ifbool{erc@stillpatching}}}{%
    \patchcmd{\BODY}{\correctchoice}{\choice \inaccessible }{\erc@incr}{\boolfalse{erc@stillpatching}}%
  }%
  %%
  %% We need exactly one \CorrectChoice, so throw a warning if not.
  \ifnum \theerc@nrcorrectchoices=1\relax\else
    \PackageWarning{exam-randomizechoices}{You need exactly one \string\CorrectChoice, I found \theerc@nrcorrectchoices\space in question \thequestion}%
  \fi
  %%
  %% Declare list \erc@list and separator \choice
  \DeclareListParser{\erc@list}{\choice}%
  %% Declare list iterator command
  \renewcommand\do[1]{%
    \stepcounter{erc@counter}%
    \long\csgdef{erc@answer\roman{erc@counter}}{##1}%
  }%
  %% Put an \@empty in front of \BODY and create the list
  \expandafter\erc@list\expandafter{\expandafter\@empty\BODY}%
  %%
  %% Emit the number of choices found, warning if less than two.
  \ifnum \theerc@counter<2\relax
    \PackageWarning{exam-randomizechoices}{You need at least two choices in question \thequestion}%
  \else
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{I found \theerc@counter\space choices}%
    \fi
  \fi
  %%
  %% Check if there is text before the first \choice, \CorrectChoice or \correctchoice
  %% and emit an error if so.
  \setbox0=\hbox{\csuse{erc@answer}\unskip}%
  \ifdim\wd0=0pt\else
    \PackageError{exam-randomizechoices}{Something's wrong, perhaps a missing \string\choice\space or \string\CorrectChoice\space or \string\correctchoice\space in question \thequestion}{You cannot have text before the first \string\choice, \string\CorrectChoice\space or \string\correctchoice.}%
  \fi
  %%
  %% Create a set of macros in the form of \erc@answerTempnum<number> where
  %% we keep track of the choice numbers.  
  \foreach \a in {1,...,\theerc@counter}{%
    \csxdef{erc@answerTempnum\a}{\a}%
  }%
  %%
  %% If randomize question...
  \iferc@random
    %% If we should randomize...
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Randomizing...}%
    \fi
    %%
    %% We need to perform a number of swaps to perform randomization
    %% We do this on the \erc@answerTempnum<number> macros because it's
    %% a pain to do it on the choices itself
    \numdef\@numberofswaps{\theerc@counter-1}%
%    \PackageWarning{test}{++> \@numberofswaps\space \theerc@counter}%
    %%
    %% User didn't set the seed	
	\iferc@seedset
	\else
	  \PackageWarning{exam-randomizechoices}{You didn't set the randomizer seed}%
	\fi
    %%
    %% Randomize the choice number list 
    \foreach \x in {1,...,\@numberofswaps} {%
      \iferc@keeplast
        \pgfmathrandominteger{\r}{\x}{\@numberofswaps}%
      \else
	    \pgfmathrandominteger{\r}{\x}{\theerc@counter}%
      \fi
	  %%   
      %% Swap the items
      \letcs\erc@temp{erc@answerTempnum\x}%
      \global\csletcs{erc@answerTempnum\x}{erc@answerTempnum\r}%
      \global\cslet{erc@answerTempnum\r}{\erc@temp}%
    }%
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Done randomizing...}%
    \fi
  \fi	
  %%
  %% We travel the list items. If an item begins with the special marker
  %% \inaccessible, we prepend it with \correctchoice, otherwise we prepend it
  %% with \choice. At the end we have all the list items prepended with
  %% either \choice or \correctchoice. Then we append the list item to
  %% the list.
  %%
  %% This list to typeset
  \gdef\erc@typesetchoices{}%
  \ifnum\theerc@counter>0\relax
    \foreach \@x in {1,...,\theerc@counter} {%
      %% Patchcmd doesn't like \usecs as command, so use an temporary macro with \let
      \letcs{\erc@tempnr}{erc@answerTempnum\@x}%
      \letcs{\erc@temp}{erc@answer\romannumeral \erc@tempnr}%
      %%
        %% Patch \inaccessible for \correctchoice in \erc@temp, otherwise prepend \choice to \erc@temp
        \iferc@nolabel
          \patchcmd{\erc@temp}{\inaccessible }{\correctchoice }{}{\gpreto{\erc@temp}{\choice}}%
        \else
          \patchcmd{\erc@temp}{\inaccessible}{\correctchoice \label{question@\thequestion @correctchoice}}{}{\gpreto{\erc@temp}{\choice}}%
        \fi
      %% Add expanded once version of \erc@temp to the list
      \xappto{\erc@typesetchoices}{\expandonce{\erc@temp}}%
    }%
  \fi
}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Overloading the choices, oneparchoices, checkboxes and oneparcheckboxes
%% environments (or not overloading)
%%
%% See https://tex.stackexchange.com/questions/116670/duplicating-environments
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%
%% Overload the choices environment
%%

\if@@ercoverload
  \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Overloading choices environment}%
  \fi

  %% Save choices environment
  \let\erc@oldchoices\choices
  \let\enderc@oldchoices\endchoices

  %% Renew the choices environment
  \RenewEnviron{choices}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1]%
    %%
    %% Start the choices environment
    \begin{erc@oldchoices}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldchoices}%
  }

  \NewEnviron{randomizechoices}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1]%
    %%
    %% Start the choices environment
    \begin{erc@oldchoices}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldchoices}%
  }
\else
  \NewEnviron{randomizechoices}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1]%
    %%
    %% Start the choices environment
    \begin{choices}%
      % Execute the list
      \erc@typesetchoices%
    \end{choices}%
  }
\fi

%%
%% Overload the oneparchoices environment
%%
\if@@ercoverload
  \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Overloading oneparchoices environment}
  \fi

  %% Save oneparchoices environment
  \let\erc@oldoneparchoices\oneparchoices
  \let\enderc@oldoneparchoices\endoneparchoices

  %% Renew the oneparchoices environment
  \RenewEnviron{oneparchoices}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1]%
    %%
    %% Start the oneparchoices environment
    \begin{erc@oldoneparchoices}%
      % Execute the list
      \erc@typesetchoices
    \end{erc@oldoneparchoices}%
  }

  \NewEnviron{randomizeoneparchoices}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1]%
    %%
    %% Start the oneparchoices environment
    \begin{erc@oldoneparchoices}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldoneparchoices}%
  }
\else
  \NewEnviron{randomizeoneparchoices}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1]%
    %%
    %% Start the oneparchoices environment
    \begin{oneparchoices}%
      % Execute the list
      \erc@typesetchoices%
    \end{oneparchoices}%
  }
\fi

%%
%% Overload the checkboxes environment
%%
\if@@ercoverload
  \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Overloading checkboxes environment}
  \fi

  %% Save choices environment
  \let\erc@oldcheckboxes\checkboxes
  \let\enderc@oldcheckboxes\endcheckboxes

  %% Renew the oneparchoices environment
  \RenewEnviron{checkboxes}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1,nolabel]%
    %%
    %% Start the choices environment
    \begin{erc@oldcheckboxes}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldcheckboxes}%
  }

  \NewEnviron{randomizecheckboxes}[1][]{%
    %%
    %% Create a random list
    \erc@createrandomlist[#1,nolabel]%
    %%
    %% Start the choices environment
    \begin{erc@oldcheckboxes}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldcheckboxes}%
  }
\else
  \NewEnviron{randomizecheckboxes}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1,nolabel]%
    %%
    %% Start the oneparchoices environment
    \begin{checkboxes}%
      % Execute the list
      \erc@typesetchoices%
    \end{checkboxes}%
  }
\fi

%%
%% Overload the oneparcheckboxes environment
%%
\if@@ercoverload
  \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Overloading oneparcheckboxes environment}
  \fi

  %% Save oneparcheckboxes environment
  \let\erc@oldoneparcheckboxes\oneparcheckboxes
  \let\enderc@oldoneparcheckboxes\endoneparcheckboxes

  %% Renew the oneparcheckboxes environment
  \RenewEnviron{oneparcheckboxes}[1][]{
    %%
    %% Create a random list
    \erc@createrandomlist[#1,nolabel]%
    %%
    %% Start the oneparcheckboxes environment
    \begin{erc@oldoneparcheckboxes}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldoneparcheckboxes}%
  }

  \NewEnviron{randomizeoneparcheckboxes}[1][]{%
    %%
    %% Create a random list
    \erc@createrandomlist[#1,nolabel]%
    %%
    %% Start the oneparcheckboxes environment
    \begin{erc@oldoneparcheckboxes}%
      % Execute the list
      \erc@typesetchoices%
    \end{erc@oldoneparcheckboxes}%
  }
\else
  \NewEnviron{randomizeoneparcheckboxes}[1][]{%
    %%
    %% Create a random list
    \erc@createrandomlist[#1,nolabel]%
    %%
    %% Start the onrparcheckboxes environment
    \begin{oneparcheckboxes}%
      % Execute the list
      \erc@typesetchoices%
    \end{oneparcheckboxes}%
  }
\fi

%%
%% Simple key table printer, with key range
%%
%% Building a table with \foreach from the pgffor package is hard to do.
%% See https://tex.stackexchange.com/questions/367979/latex-foreach-in-tabular-environment
%% So we use \gappto and \xappto to build the table. At the end, we expand the macro
%%

\newcounter{erc@printstart}\setcounter{erc@printstart}{0}
\newcounter{erc@printstop}\setcounter{erc@printstop}{0}

\newcommand{\printkeytable}[1][-]{%
  \erc@printkeytable#1\@nil%
}

\def\erc@printkeytable#1-#2\@nil{%
  %% Grab arguments
  \setcounter{erc@printstart}{0#1}%
  \setcounter{erc@printstop}{0#2}%
  %% Sanity check
  \ifnum\value{erc@printstart}<1\setcounter{erc@printstart}{1}\fi%
  \ifnum\value{erc@printstop}<1\setcounter{erc@printstop}{\thequestion}\fi%
  \ifnum\value{erc@printstop}>\thequestion\setcounter{erc@printstop}{\thequestion}\fi%
  \if@@ercdebug
    \PackageWarning{exam-randomizechoices}{Writing key table}%
  \fi
  %% Create the key table typesetting macro
  \xdef\erc@keytable{}%
  %%
  %% Add the preamble of the table {regular tabular}
  \gappto\erc@keytable{\begin{tabular}[t] {|c|c|} \hline}%
  \xappto\erc@keytable{\erc@keylistquestionname\space & \erc@keylistkeyname}%
  \gappto\erc@keytable{ \\ \hline}%
  %%
  %% Write the table entries.
  \ifnum\thequestion=0\relax
  \else
%    \foreach \x in {1,...,\thequestion} {%
    \foreach \x in {\arabic{erc@printstart},...,\arabic{erc@printstop}} {%
      %%
      %% Add '\ref{question@\x} & ', \x should be expandend, \ref not 
      \gappto\erc@keytable{\ref}%
      \xappto\erc@keytable{{question@\x}}%
      \gappto\erc@keytable{ & }%
      \@ifundefined{r@question@\x @correctchoice}{%
        %not found
        \gappto\erc@keytable{\textbf{??} \\ }%
      }{%
        %found
        \gappto\erc@keytable{\ref}%
        \xappto\erc@keytable{{question@\x @correctchoice}}%
        \gappto\erc@keytable{ \\ }%
      }%
    }%
  \fi
  %%
  %% Add the epilogue
  \gappto\erc@keytable{\hline \end{tabular}}%
  %%
  %% Typeset the table
  \erc@keytable%
}

%%
%% Simple key list file writer
%%
\def\writekeylist{\@ifnextchar[{\erc@writekeylist}{\erc@writekeylist[\jobname.keylist]}}%
\def\erc@writekeylist[#1]#2{%
  %%
  \if@filesw
    %%
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Writing key list to file}%
    \fi
    \def\erc@macroname{#2}%
    %% Open the key list file for writing and add some preface content.
    \newwrite\tempfile
    \immediate\openout\tempfile=#1%
    \immediate\write\tempfile{\@percentchar}%
    \immediate\write\tempfile{\@percentchar\space Automatically generated key list file}%
    \immediate\write\tempfile{\@percentchar\space written by package exam-randomizechoices}%
    \immediate\write\tempfile{\@percentchar\space File written at \today\space (\number\year/\two@digits\month/\two@digits\day)}% doesn't behave well
    \immediate\write\tempfile{\@percentchar}%
    \immediate\write\tempfile{\@percentchar\space Edits to this file are lost}%
    \immediate\write\tempfile{\@percentchar\space This file may safely be removed}%
    \immediate\write\tempfile{\@percentchar}%
    %%
    %% Create a command that has all the question numbers / question keys
    %% separated by a /
    \gdef\erc@keylist{\@gobble}%
    %% Write the list entries.
    \ifnum\thequestion=0\relax
      \gdef\erc@keylist{}%
    \else
      \foreach \x in {1,...,\thequestion} {%
        \@ifundefined{r@question@\x @correctchoice}{%
          %not found
          \xdef\erc@keylist{\erc@keylist,\x/?}%
        }{%
          %found
         \xdef\erc@keylist{\erc@keylist,\x/\getrefnumber{question@\x @correctchoice}}%
        }%
      }%
    \fi
    %%
    %% Write the gdef with key list in one write. This prevents Latex to
    %% add end-of-line characters. After that, close the file. 
    \immediate\write\tempfile{\string\gdef\expandafter\string\erc@macroname\@charlb\erc@keylist\@charrb}%
    \immediate\write\tempfile{\string\endinput}%
    \immediate\closeout\tempfile
  \else
    \PackageError{exam-randomizechoices}{Cannot write key list file}{The writing of files is disabled by the system, so no key list file is generated.}%
  \fi
}

%%
%% Simple key list saver. Saves the key list in a macro
%%
\def\savekeylist{\@ifnextchar[{\erc@savekeylist}{\erc@savekeylist[\keylist]}}%
\def\erc@savekeylist[#1]{%
    %%
    \if@@ercdebug
      \PackageWarning{exam-randomizechoices}{Saving key list to macro}%
    \fi
    %%
    %% Create a command that has all the question numbers / question keys
    %% separated by a / (but nothing if there are no questions)
    \ifnum\thequestion=0\relax
      \gdef\erc@keylist{}%
    \else
      %% Write the list entries.
      \gdef\erc@keylist{\@gobble}%
      \foreach \x in {1,...,\thequestion} {%
        \@ifundefined{r@question@\x @correctchoice}{%
          %not found
          \xdef\erc@keylist{\erc@keylist,\x/?}%
        }{%
          %found
         \xdef\erc@keylist{\erc@keylist,\x/\getrefnumber{question@\x @correctchoice}}%
        }%
      }%
    \fi%
    %% Save the keylist in the supplied macro
    \expandafter\xdef\expandafter#1\expandafter{\erc@keylist}%
}

\endinput