Skip to content

Instantly share code, notes, and snippets.

@kaz-utashiro
Last active March 9, 2025 06:41
Show Gist options
  • Save kaz-utashiro/ad8979f0c2bc5e4475e5db0e19fc85f1 to your computer and use it in GitHub Desktop.
Save kaz-utashiro/ad8979f0c2bc5e4475e5db0e19fc85f1 to your computer and use it in GitHub Desktop.
「7の倍数」を表す正規表現
#!/usr/bin/perl
# https://qiita.com/jkr_2255/items/8bae27d026754d4e2474
# 「7の倍数」を表す正規表現
use v5.24;
use warnings;
use Data::Dumper;
my $NUM_STATES = 7;
my @states;
my @BASE = qw( [07] [18] [29] 3 4 5 6 );
for my $from (0..6) {
for my $to (0..6) {
$states[$from][$to] = sprintf("%s", $BASE[($to - 10 * $from) % 7]);
}
}
for my $n (reverse(1 .. $NUM_STATES - 1)) {
for my $i (0..$n) {
for my $j (0..$n) {
$states[$i][$j] = sprintf("(%s|%s)",
$states[$i][$j],
qq/$states[$i][$n]$states[$n][$n]*$states[$n][$j]/
)
}
}
}
my $re = qr/\A$states[0][0]+\z/n;
say $re;
my $count = 200;
my $match;
for (1 .. $count) {
my $rand = int rand(~0 >> 1);
my $mod = $rand % 7;
if ($rand =~ /$re/) {
$match++;
if ($mod) {
say "$rand\tmod=$mod"
} else {
printf "$rand = %d * 7 + %d\n", $rand / 7, $mod;
}
} else {
say "$rand\terror" if $mod == 0;
}
}
printf "%d/%d = %f\n", $match, $count, $match / $count;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment