Testing AI Code Generation Capabilities with the N-Back Experiment

    This article explores how to use the N-Back cognitive experiment to evaluate the code generation capabilities of AI programming assistants. It covers breaking down experimental rules into executable specifications, designing structured prompts, and implementing core logic. By providing a detailed acceptance checklist and troubleshooting guide, developers can ensure that AI-generated code meets precise requirements and effectively handles state management, timing control, and result statistics.

    Introduction

    An increasing number of developers are integrating large language model (LLM) programming assistants into their daily workflows. These tools can generate page skeletons, auto-complete functions, write unit tests, and explain unfamiliar code. However, whether the generated code is ready for direct delivery depends on the clarity of the requirement description, the explicitness of the acceptance criteria, and the developer’s ability to quickly identify errors.

    The N-Back experiment serves as an ideal sample task for testing these capabilities. Its rules are simple, yet it encompasses multiple stages such as timing control, state management, user input, and result statistics. It can evaluate both the model’s comprehension of requirements and expose detailed implementation issues. This article discusses the complete process from requirement breakdown to acceptance verification based on this specific task.

    Principles and Requirement Breakdown of the N-Back Experiment

    N-Back is a working memory paradigm commonly used in cognitive psychology and neuroscience research. Subjects are presented with a series of stimuli sequentially. For each new stimulus, they must determine whether it is identical to the one presented N steps back. As N takes values like 2, 3, or 4, the task difficulty increases accordingly.

    Before writing the requirements, the experimental rules must be converted into an executable specification. Below is a specification that can be directly handed to a programming assistant:

    1. Stimulus Sequence: Characters are selected from 10 common Chinese characters: “国, 火, 道, 市, 天, 家, 理, 态, 至, 心”.
    2. Presentation Rhythm: A character is presented every 1 second, with each character displayed for 1 second.
    3. Judgment Rules: If the current character is the same as the character N steps back, the user should select “Yes”; otherwise, they select “No”.
    4. Parameter Settings: Before starting the experiment each time, the user must choose a value for N from 2, 3, or 4.
    5. Result Statistics: Record the number of hits, misses, and false alarms, and display a summary at the end of the experiment.

    Two points require attention during breakdown. First, every rule should yield a measurable outcome, avoiding unverifiable descriptions like “the interface should be aesthetically pleasing.” Second, boundary conditions must be clearly defined, such as how to handle sequences shorter than N, and how to score when a user clicks multiple times within a single stimulus cycle.

    Four Elements of Prompt Design

    The quality of the prompt directly impacts the quality of the generated code. A structured prompt typically contains the following four elements.

    The first is the Goal. State what needs to be done and the format of the final deliverable, such as a single-file HTML page or a component within a specific frontend framework.

    The second is Constraints. This includes the tech stack, browser compatibility range, permission to use third-party libraries, code style, etc. Without constraints, the model might choose a solution with mismatched complexity.

    The third is Rules. Write down the specifications from the previous section item by item, especially time parameters, randomization rules, and scoring methods.

    The fourth is the Acceptance Method. Tell the model how to verify the results, such as requesting test cases for key functions or asking it to explain how timers are cleared when the page switches.

    Below is an example structure of a prompt:

    1. Goal: Implement a single-page web application for an N-Back cognitive experiment.
    2. Constraints: Use vanilla HTML, CSS, and JavaScript without relying on external libraries.
    3. Rules:
    4. - Stimuli are randomly selected from 10 given Chinese characters, switching every 1 second, with each character displayed for 1 second.
    5. - Before starting, let the user choose N from the options 2, 3, or 4.
    6. - If the current character matches the one N steps back, the user clicks "Yes" for a correct answer; otherwise, "No".
    7. - After the experiment ends, display the number of hits, misses, and false alarms.
    8. Acceptance: List test cases for the scoring function, and explain how the timer is cleared when the experiment ends.

    Key Points for Implementing Core Logic

    While the model can freely design the user interface, the core logic must be independently verifiable. It is recommended to separate sequence generation, scoring, and timing into independent functions for easier isolated testing.

    The following code demonstrates the basic concept of sequence generation and scoring, illustrating the structure only:

    1. const POOL = ["国", "火", "道", "市", "天", "家", "理", "态", "至", "心"];
    2. // Generate a stimulus sequence of specified length.
    3. // To ensure enough matching samples, reuse the character from n positions back at a certain probability.
    4. function generateSequence(length, n, pool = POOL, matchRate = 0.3) {
    5. const seq = [];
    6. for (let i = 0; i < length; i++) {
    7. if (i >= n && Math.random() < matchRate) {
    8. seq.push(seq[i - n]);
    9. } else {
    10. seq.push(pool[Math.floor(Math.random() * pool.length)]);
    11. }
    12. }
    13. return seq;
    14. }
    15. // Determine if the stimulus at index matches the one n positions back.
    16. function isMatch(seq, index, n) {
    17. return index >= n && seq[index] === seq[index - n];
    18. }
    19. // Calculate statistical results based on user answers and ground truth.
    20. function score(seq, answers, n) {
    21. const result = { hit: 0, miss: 0, falseAlarm: 0, correctRejection: 0 };
    22. for (let i = 0; i < seq.length; i++) {
    23. const target = isMatch(seq, i, n);
    24. const said = answers[i] === true;
    25. if (target && said) result.hit++;
    26. else if (target && !said) result.miss++;
    27. else if (!target && said) result.falseAlarm++;
    28. else result.correctRejection++;
    29. }
    30. return result;
    31. }

    Several details in this code are worth noting. When generating the sequence, the first n positions have no prior characters to compare against, so they are not reused. During scoring, “no answer” must be treated as “No”; otherwise, unattended stimuli would be incorrectly counted as correct rejections. The match probability needs to be configurable to adjust the difficulty of the experiment.

    User Interface and Interaction Considerations

    At the interface level, three issues are easily overlooked.

    First is timer management. If multiple setInterval calls are used in the page, they must be cleared when the experiment ends or the user exits midway; otherwise, stimuli might continue jumping and statistics will become disordered. It is recommended to use a unified state machine to separately manage “preparing,” “in progress,” and “ended” states.

    Second is input timing. The user’s response should be bound to the time window of the current stimulus. If a response is submitted only after the next stimulus appears, it must be predefined which stimulus it counts toward.

    Third is keyboard and touchscreen compatibility. Many users operate using keyboard shortcuts. The interface should simultaneously support mouse, touchscreen, and keyboard events, providing clear visual state feedback on the buttons.

    Acceptance Checklist

    Before delivering the generated code, it is recommended to verify the following items one by one:

    1. The choice of N can only be 2, 3, or 4, and it must be re-selected before each start.
    2. Stimuli are generated strictly from the specified 10 Chinese characters, with no other characters appearing in the sequence.
    3. The display duration and switching interval of each stimulus conform to the rules, verifiable via timing logs.
    4. The scoring function correctly handles the first n positions without generating false matches due to out-of-bounds access.
    5. Unanswered stimuli are counted as “No,” and the summed statistical results equal the sequence length.
    6. Timers are cleared after the experiment ends, and the state is correctly reset upon restarting.

    During acceptance, the most effective method is to write test cases for the scoring function using fixed sequences. For example, given the sequence “国, 火, 国, 火” with N=2, the 3rd and 4th positions should both be judged as matches. Fixed input, fixed output tests can quickly expose logic errors.

    Common Issues and Troubleshooting

    In practice, generated code commonly exhibits the following types of issues.

    The first type is boundary errors. A typical manifestation is that the first few positions of the sequence are incorrectly judged as matches. The cause is usually accessing an out-of-bounds position like seq[-1], or failing to check whether the index is greater than or equal to N first.

    The second type is timing deviations. Browser timers do not guarantee strict precision. If heavy computations are executed within callbacks, stimulus switching will experience jitter. A more robust approach is to record the actual timestamp of each switch and calculate reaction times based on that, rather than assuming a constant interval.

    The third type is state residue. If the user starts the experiment multiple times, old timers or old answer arrays that are not cleared will contaminate the statistical results with data from the previous round. The solution is to create a new session object at the start of each run.

    When encountering issues, do not simply ask the model to rewrite the entire page. A more effective approach is to provide the error symptoms, reproduction steps, and the relevant functions to the model, asking it to explain the cause first, and then provide a minimal fix.

    Conclusion

    Although the N-Back experiment is a small task, it comprehensively covers development phases such as requirement comprehension, state management, timing control, and result statistics. By converting rules into executable specifications, designing structured prompts, and verifying core logic with fixed tests, developers can leverage LLMs to accomplish similar tasks with greater confidence.

    This methodology applies equally to the development of other interactive tools. The key is to make requirements verifiable, keep code testable, and ensure that developers remain accountable for the final outcome.