I’m working on checking student input for a puzzle activity where the rules allow them to use each number exactly once. I haven’t had much luck finding examples of using p.repeat in the forums yes but I am confident this can be done.
I’d like to look at an expression such as 3+2^{2}-2(7-4) and tell the student “oops, you used 2 three times instead of once.”
I’m picturing a combination of p.literal, p.contains, and p.repeat and I’ve tried something like:
p.repeat(p.contains(p.literal(2)).parse(this.latex).term1.n and I’m not even sure what type of value is generated by it. I see also the term1.nth option as well and have no idea what it does.
Long story short, can I use pattern matching to count the number of instances of a particular digit or number in an expression?
I think I tried to use p.contains inside of p.repeat to achieve something before, and it didn’t like it at all. You would also tend to use p.integer.satisfies(`x=2`) I think, rather than p.literal(2).
That all having been said, a much easier solution is countNumberUsage:
Brilliant, thank you so much. I had seen countNumberUsage before and made a note of it for future reference, then completely forgot about it while trying to make this CL happen.
I also wonder if I am fundamentally misunderstanding the purpose of p.repeat? Is it meant to recognize repeating decimal numbers?
I think it’s for repeated operations, although I’m going completely from memory here and haven’t tested this. I’ve never used it successfully in a ‘live’ activity.
Something like p.repeat(p.sum(p.number,p.number)) I think works, and possibly then you’re also able to pull out individual terms using term1 etc.
Glad this does the trick! Also might be worth knowing that countNumberUsage(...) without a second argument just counts how many numbers are used - so if you just want to ensure that 2, 3, 6 and 8 are used exactly once and no other numbers are there, you can also just have countNumberUsage(this.latex)=4 alongside the p2, p3, etc. without any pattern matching at all. (Although pi probably still sneaks through!)