diff --git a/exercises/practice/allergies/.docs/hints.md b/exercises/practice/allergies/.docs/hints.md new file mode 100644 index 000000000..a7bd602a8 --- /dev/null +++ b/exercises/practice/allergies/.docs/hints.md @@ -0,0 +1,19 @@ +# Hints + +## Choosing an approach + +Every allergen value is a power of 2, so a score is really a row of on/off flags: eggs is the 1s place, peanuts the 2s place, shellfish the 4s place, and so on. Whatever approach you pick has to answer one question for each allergen: *is its flag on in this score?* + +Two common ways to ask it: + +- **Bit operations.** Combine the score with the allergen's value using a bitwise AND. The result keeps only that allergen's flag, so if you get the allergen's value back, the flag was on. +- **Arithmetic.** Divide the score by the allergen's value to move its flag into the 1s place, then check whether the result is odd or even. + +**Worked input: score 34** (peanuts 2 + chocolate 32, which is `100010` in binary). + +| Allergen | Bit operations | Arithmetic | Allergic? | +|---|---|---|---| +| peanuts (2) | `34 & 2` gives 2, equal to the value | 34 / 2 = 17, odd | yes | +| eggs (1) | `34 & 1` gives 0, not equal to the value | 34 / 1 = 34, even | no | + +**Trade-off.** Bit operations are one step per allergen and are the usual way to work with flags, but they assume you are comfortable with binary. Arithmetic needs no binary knowledge, so it can be easier to follow, at the cost of a division and a remainder per allergen. Neither needs extra memory, and both rely on the values being powers of 2. Both also ignore scores above 128 as long as you only check the eight known allergens. Pick bit operations if you want the idiomatic version, or arithmetic if readability for newcomers matters more. \ No newline at end of file diff --git a/work/R20-T056/alternative.cpp b/work/R20-T056/alternative.cpp new file mode 100644 index 000000000..b3632b0a8 --- /dev/null +++ b/work/R20-T056/alternative.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include + +#include "allergies.h" + +namespace allergies { + +allergy_test::allergy_test(unsigned int test_result) : result(test_result) {} + +bool allergy_test::is_allergic_to(std::string const& allergen) const { + unsigned int allergen_value = allergies::ALLERGENS.at(allergen); + return (result / allergen_value) % 2 == 1; +} + +std::unordered_set allergy_test::get_allergies() const { + std::unordered_set allergies; + + for (auto const& entry : allergies::ALLERGENS) + if ((result / entry.second) % 2 == 1) + allergies.insert(entry.first); + + return allergies; +} + +} // namespace allergies diff --git a/work/R20-T056/alternative_test_output.txt b/work/R20-T056/alternative_test_output.txt new file mode 100644 index 000000000..cfd3b2b73 --- /dev/null +++ b/work/R20-T056/alternative_test_output.txt @@ -0,0 +1,3 @@ +=============================================================================== +All tests passed (50 assertions in 50 test cases) + diff --git a/work/R20-T056/check.py b/work/R20-T056/check.py new file mode 100644 index 000000000..05e760b68 --- /dev/null +++ b/work/R20-T056/check.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Task R20-T056: check that two allergies implementations pass the same tests. + +Run from anywhere: python3 work/R20-T056/check.py +Exits 0 only if every check passes. Any problem exits non-zero. +""" +import json +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent # work/R20-T056 +REPO = HERE.parents[1] # repository root +EXERCISE = REPO / "exercises" / "practice" / "allergies" +CMAKE_FLAG = "-DEXERCISM_RUN_ALL_TESTS=ON" +PASS_LINE = re.compile(r"All tests passed \((\d+) assertions? in (\d+) test cases?\)") + + +class CheckError(Exception): + """Raised when any check fails.""" + + +def need(condition, message): + if not condition: + raise CheckError(message) + + +def run(cmd, cwd): + return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) + + +def count_enabled_cases(tests_toml): + """Count the [uuid] sections in tests.toml that are not marked include = false.""" + count, enabled = 0, None + for raw in tests_toml.read_text().splitlines(): + line = raw.strip() + if re.fullmatch(r"\[[0-9a-fA-F-]{36}\]", line): + if enabled: + count += 1 + enabled = True + elif re.fullmatch(r"include\s*=\s*false", line): + enabled = False + if enabled: + count += 1 + return count + + +def save_tool_versions(): + lines = [] + for cmd in (["cmake", "--version"], ["g++", "--version"], [sys.executable, "--version"]): + result = run(cmd, REPO) + lines.append("$ " + " ".join(cmd)) + lines.append((result.stdout + result.stderr).strip()) + lines.append("") + (HERE / "tool_versions.txt").write_text("\n".join(lines)) + + +def build_and_test(label, replacements, expected_cases): + """Build the exercise in a temporary copy with `replacements` swapped in, then run its tests.""" + with tempfile.TemporaryDirectory() as tmp: + # Keep the folder name: CMake names the test program after it. + copy = Path(tmp) / EXERCISE.name + shutil.copytree(EXERCISE, copy) # copies dotfiles such as .meta and .docs too + for name, source in replacements.items(): + shutil.copyfile(source, copy / name) + + step = run(["cmake", "-S", ".", "-B", "build", CMAKE_FLAG], copy) + need(step.returncode == 0, f"[{label}] cmake configure failed:\n{step.stdout}{step.stderr}") + + step = run(["cmake", "--build", "build"], copy) + need(step.returncode == 0, f"[{label}] build failed:\n{step.stdout}{step.stderr}") + + exe = copy / "build" / EXERCISE.name + need(exe.exists(), f"[{label}] test program not found at {exe}") + + result = run([str(exe)], copy) + output = result.stdout + result.stderr + (HERE / f"{label}_test_output.txt").write_text(output) + need(result.returncode == 0, f"[{label}] tests failed (exit code {result.returncode}):\n{output}") + + match = PASS_LINE.search(output) + need(match, f"[{label}] could not find the 'All tests passed' summary:\n{output}") + cases = int(match.group(2)) + need(cases > 0, f"[{label}] zero test cases ran") + need(cases == expected_cases, f"[{label}] expected {expected_cases} test cases but {cases} ran") + + return { + "label": label, + "exit_code": result.returncode, + "expected_cases": expected_cases, + "actual_cases": cases, + "assertions": int(match.group(1)), + } + + +def main(): + config = json.loads((EXERCISE / ".meta" / "config.json").read_text()) + solution = config["files"]["solution"] + example = config["files"]["example"] + need(len(solution) == len(example), "config.json: solution and example lists differ in length") + + # The learner stub and test files must stay exactly as they are in git. + # (hints.md is allowed to change: that is the contribution.) + protected = [str(EXERCISE / name) for name in solution + config["files"]["test"]] + status = run(["git", "status", "--porcelain", "--", *protected], REPO) + need(status.returncode == 0, f"git status failed: {status.stderr}") + need(status.stdout.strip() == "", f"learner files were modified:\n{status.stdout}") + + expected = count_enabled_cases(EXERCISE / ".meta" / "tests.toml") + need(expected > 0, "found no enabled test cases in tests.toml") + + reference = {sol: EXERCISE / ex for sol, ex in zip(solution, example)} + + alt_cpp = HERE / "alternative.cpp" + need(alt_cpp.exists(), f"missing {alt_cpp}") + cpp_name = next(name for name in solution if name.endswith(".cpp")) + alternative = dict(reference) # same header as the reference, different .cpp + alternative[cpp_name] = alt_cpp + need( + alt_cpp.read_text() != reference[cpp_name].read_text(), + "alternative.cpp is identical to the reference", + ) + + save_tool_versions() + results = [ + build_and_test("reference", reference, expected), + build_and_test("alternative", alternative, expected), + ] + + evidence = { + "inputs": { + "reference_files": {k: str(v.relative_to(REPO)) for k, v in reference.items()}, + "alternative_files": { + k: str(v.relative_to(REPO)) for k, v in alternative.items() + }, + "cmake_flag": CMAKE_FLAG, + }, + "expected_cases": expected, + "results": results, + } + (HERE / "evidence.json").write_text(json.dumps(evidence, indent=2)) + + for r in results: + print(f"{r['label']}: {r['actual_cases']} test cases ran " + f"({r['assertions']} assertions), expected {r['expected_cases']}, exit code {r['exit_code']}") + print(f"PASS: reference and alternative both passed the same {expected} enabled test cases") + + +if __name__ == "__main__": + try: + main() + except CheckError as err: + print(f"FAIL: {err}") + sys.exit(1) + except OSError as err: + print(f"FAIL: could not run a required tool or read a file: {err}") + sys.exit(1) \ No newline at end of file diff --git a/work/R20-T056/evidence.json b/work/R20-T056/evidence.json new file mode 100644 index 000000000..660a42e22 --- /dev/null +++ b/work/R20-T056/evidence.json @@ -0,0 +1,30 @@ +{ + "inputs": { + "reference_files": { + "allergies.cpp": "exercises/practice/allergies/.meta/example.cpp", + "allergies.h": "exercises/practice/allergies/.meta/example.h" + }, + "alternative_files": { + "allergies.cpp": "work/R20-T056/alternative.cpp", + "allergies.h": "exercises/practice/allergies/.meta/example.h" + }, + "cmake_flag": "-DEXERCISM_RUN_ALL_TESTS=ON" + }, + "expected_cases": 50, + "results": [ + { + "label": "reference", + "exit_code": 0, + "expected_cases": 50, + "actual_cases": 50, + "assertions": 50 + }, + { + "label": "alternative", + "exit_code": 0, + "expected_cases": 50, + "actual_cases": 50, + "assertions": 50 + } + ] +} \ No newline at end of file diff --git a/work/R20-T056/reference_test_output.txt b/work/R20-T056/reference_test_output.txt new file mode 100644 index 000000000..cfd3b2b73 --- /dev/null +++ b/work/R20-T056/reference_test_output.txt @@ -0,0 +1,3 @@ +=============================================================================== +All tests passed (50 assertions in 50 test cases) + diff --git a/work/R20-T056/tool_versions.txt b/work/R20-T056/tool_versions.txt new file mode 100644 index 000000000..4b5d1965a --- /dev/null +++ b/work/R20-T056/tool_versions.txt @@ -0,0 +1,13 @@ +$ cmake --version +cmake version 4.5.1 + +CMake suite maintained and supported by Kitware (kitware.com/cmake). + +$ g++ --version +Apple clang version 21.0.0 (clang-2100.3.34.2) +Target: arm64-apple-darwin27.2.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + +$ /Library/Frameworks/Python.framework/Versions/3.14/bin/python3 --version +Python 3.14.7