Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

1 of 17
Deadcode
  • 12.9k
  • 2
  • 71
  • 55

Regex (Perl / PCRE / .NET), 36 bytes

x(x*),((x(?=((?(4)4円)1円)))*)4円?+(x*)

Try it online!

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 4円 and 3円, 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
Deadcode
  • 12.9k
  • 2
  • 71
  • 55

AltStyle によって変換されたページ (->オリジナル) /