- 12.9k
- 2
- 71
- 55
Regex (Perl / PCRE), 36 bytes
x(x*),((x(?=((?(4)4円)1円)))*)4円?+(x*)
Takes its arguments in unary, as two strings of x characters whose lengths represent the numbers. The divisor comes first, followed by a , delimiter, followed by the dividend. The quotient and remainder are returned in the capture groups 2円 and 5円, respectively.
In contrast to the ECMAScript regex solution, this one doesn't have to do anything anywhere near as fancy or mathematically interesting. Just count the number of times \$divisor\$ fits into \$dividend\$ by splitting the divisor to keep two tandem running totals that are both subtracted from \$dividend\$, one that keeps subtracting \$divisor-1\$, and one that keeps subtracting \1ドル\$ and adding it to the total quotient. We must do a split like this, because regex refuses to repeat a zero-width group more than once (this, along with the limited space to work in, is exactly what prevents it from being Turning-complete).
I never wrote a division algorithm in any regex flavor besides ECMAScript before. So it's interesting to now know how they compare in golfed size.
x(x*), # 1円 = divisor-1; tail = dividend
( # 2円 = what will be the quotient
(
x # tail -= 1
(?=
( # 4円 = running total
(?(4)4円) # recall the previous contents of 4,円 if any
1円 # 4円 += divisor-1
)
)
)* # Loop the above as many times as possible (zero or more); if
# it loops zero times, 4円 will be unset (we'll treat that as 0)
)
4円?+ # tail -= 4,円 or leave tail unchanged if 4円 is unset
(x*) # 5円 = remainder
Regex (.NET), 29 bytes
(x+),(?=(1円)*(x*))((?<-2>x)*)
This uses .NET's Balanced Groups feature. It returns the quotient and remainder in 4円 and 3円, respectively.
(x+), # 1円 = divisor; assert 1円 > 0; tail = dividend
(?=
(1円)* # push 2円 onto the stack for each time 1円 fits into dividend
(x*) # 3円 = remainder
)
((?<-2>x)*) # 4円 = quotient: pop all 2円 from stack, doing 4円 += 1 for each
- 12.9k
- 2
- 71
- 55