How to use p.repeat?

Hi all,

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?

Thanks in advance for the help!

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:

countNumberUsage(this.latex,2) will count the number of times the number 2 is used within the expression.

I think this counts numbers specifically, not digits - so 28 wouldn’t be counted as a 2, but 2^2 would be counted as two 2s.

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?

Ended up using this, and it works nicely, expect students can still sneak pi past the guards.

p = patterns
p2 = countNumberUsage(this.latex,2)
p3 = countNumberUsage(this.latex,3)
p6 = countNumberUsage(this.latex,6)
p8 = countNumberUsage(this.latex,8)

other = \left|x-2\right|\cdot\left|x-3\right|\cdot\left|x-6\right|\cdot\left|x-8\right|>0

ans =
p2 = 1 and
p3 = 1 and
p6 = 1 and
p8 = 1 and
not(p.contains(p.number.satisfies(other)).matches(this.latex)) 1
otherwise 0

correct: ans = 1
showSubmitButton: false

1 Like

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!)